Repository navigation
Expand file tree
/
Copy pathch24.html
More file actions
1594 lines (1377 loc) · 59.9 KB
/
Copy pathch24.html
File metadata and controls
1594 lines (1377 loc) · 59.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="AI学习笔记 - 从零开始系统学习人工智能,涵盖前置基础、核心原理、工程实践、应用工具、进阶展望">
<meta name="keywords" content="AI, 人工智能, 机器学习, 深度学习, Python, 数学基础">
<meta name="author" content="AI Learner">
<title>第二十四章:综合实战——搭建个人AI助手 - AI学习笔记</title>
<!-- Google Fonts - Inter -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- KaTeX - 轻量级数学公式渲染 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"
onload="renderMathInElement(document.body, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '\\[', right: '\\]', display: true},
{left: '\\(', right: '\\)', display: false},
{left: '$', right: '$', display: false}
],
throwOnError: false
});"></script>
<!-- Prism.js 代码高亮 - tomorrow-night 主题 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
<!-- 自定义样式表 -->
<link rel="stylesheet" href="../../css/main.css">
<link rel="stylesheet" href="../../css/dark-mode.css">
<link rel="stylesheet" href="../../css/mobile-optimizations.css">
<!-- 内联CSS样式 -->
<!-- AI-Notes共享样式 -->
<link rel="stylesheet" href="assets/ai-notes.css">
</head>
<body>
<!-- ==================== 导航栏 ==================== -->
<nav class="ai-nav">
<a href="../../index.html" class="ai-nav-brand">
<i class="fas fa-brain"></i>
AI学习笔记
</a>
<ul class="ai-nav-links" id="navLinks">
<li><a href="../../index.html"><i class="fas fa-home"></i> 首页</a></li>
<li><a href="ch15.html"><i class="fas fa-robot"></i> Agent</a></li>
<li><a href="ch16.html"><i class="fas fa-tools"></i> 工具</a></li>
<li><a href="ch17.html"><i class="fas fa-book-open"></i> 知识库</a></li>
<li><a href="ch18.html"><i class="fas fa-layer-group"></i> 记忆</a></li>
<li><a href="ch19.html"><i class="fas fa-comment-dots"></i> 提示</a></li>
<li><a href="ch20.html"><i class="fas fa-database"></i> 数据</a></li>
<li><a href="ch21.html"><i class="fas fa-exclamation-circle"></i> 局限</a></li>
<li><a href="ch22.html"><i class="fas fa-toolbox"></i> 平台</a></li>
<li><a href="ch23.html"><i class="fas fa-history"></i> 简史</a></li>
<li><a href="ch24.html"><i class="fas fa-rocket"></i> 实战</a></li>
</ul>
<button class="ai-nav-toggle" id="navToggle" aria-label="切换导航">
<i class="fas fa-bars"></i>
</button>
</nav>
<!-- ==================== Hero Section ==================== -->
<section class="ai-hero">
<h1><i class="fas fa-brain"></i> AI 学习笔记</h1>
<p>第二十四章:综合实战——搭建个人AI助手</p>
<div class="ai-hero-badges">
<span class="ai-hero-badge"><i class="fas fa-book"></i> 系统学习</span>
<span class="ai-hero-badge"><i class="fas fa-code"></i> 实践导向</span>
</div>
</section>
<!-- ==================== 主内容区域 ==================== -->
<div class="content-wrapper">
<!-- ========== 主内容 ========== -->
<main class="main-content">
<nav class="ai-chapter-nav">
<div class="breadcrumb">
<a href="../../index.html"><i class="fas fa-home"></i> 首页</a>
<span class="separator">/</span>
<span class="current">第二十四章:综合实战——搭建个人AI助手</span>
</div>
<div class="chapter-nav-links">
<a href="appendix-b.html" class="prev-chapter"><i class="fas fa-arrow-left"></i> 上一章</a>
<a href="appendix-c.html" class="next-chapter">下一章 <i class="fas fa-arrow-right"></i></a>
</div>
</nav>
<!-- 第二十四章:综合实战——搭建个人AI助手 -->
<!-- ============================================================ -->
<h2 class="ai-section-title">第二十四章:综合实战——搭建个人AI助手</h2>
<div class="concept-section">
<h3>学习目标</h3>
<div class="ai-box ai-box--objectives">
<ul>
<li>能够独立搭建一个功能完整的个人AI助手,整合对话、检索、工具调用和记忆功能</li>
<li>掌握从项目初始化到部署上线的完整开发流程</li>
<li>理解各模块之间的协作关系,具备模块化设计能力</li>
<li>学会使用Gradio快速搭建Web界面,实现用户友好的交互体验</li>
<li>具备根据需求扩展AI助手功能的能力,如多模态、语音、多Agent协作等</li>
</ul>
</div>
</div>
<div class="concept-section">
<h3>前置要求</h3>
<div class="ai-box ai-box--prereq">
<p>在开始本章之前,请确保你已经掌握以下内容:</p>
<ul>
<li>Python编程基础(函数、类、文件操作、虚拟环境)</li>
<li>LLM基本原理(提示工程、Token、温度参数等)</li>
<li>RAG技术(文档加载、Embedding、向量检索)</li>
<li>Agent概念(工具调用、Function Calling、ReAct模式)</li>
<li>基础的前端知识(HTML/CSS概念,有助于理解Gradio界面)</li>
</ul>
</div>
</div>
<figure class="ai-figure">
<img src="https://trae-api-cn.mchost.guru/api/ide/v1/text_to_image?prompt=Personal%20AI%20assistant%20architecture%20diagram%2C%20end-to-end%20development%20workflow%2C%20chat%20RAG%20tools%20memory%20modules%2C%20Gradio%20web%20interface%2C%20clean%20educational%20infographic%20style%2C%20flat%20design%2C%20white%20background&image_size=landscape_4_3" alt="个人AI助手架构与开发流程图" loading="lazy">
<figcaption><strong>图24-1</strong> 个人AI助手的整体架构:整合对话、检索、工具调用与记忆模块</figcaption>
</figure>
<div class="concept-section">
<h3>项目概述</h3>
<h4>项目功能介绍</h4>
<p>本项目将搭建一个个人AI助手,具备以下核心功能:</p>
<ul>
<li><strong>智能问答</strong>:基于大语言模型的自然语言对话能力</li>
<li><strong>文档检索</strong>:上传本地文档后,助手能基于文档内容回答问题(RAG)</li>
<li><strong>工具调用</strong>:支持天气查询、计算器、网页搜索等外部工具</li>
<li><strong>记忆功能</strong>:记住对话历史和重要信息,实现连续交互</li>
</ul>
<h4>技术架构图</h4>
<div class="concept-box info">
<p>系统整体架构流程如下:</p>
<pre><code class="language-bash">用户输入
|
v
[意图识别模块] —— 判断用户意图:闲聊 / 文档问答 / 工具调用
|
v
[路由分发模块]
|—— 闲聊意图 ——→ [LLM对话模块] ——→ 生成回复
|—— 文档意图 ——→ [RAG检索模块] ——→ [LLM生成模块] ——→ 生成回复
|—— 工具意图 ——→ [工具调用模块] ——→ [LLM整合模块] ——→ 生成回复
|
v
[记忆管理模块] —— 保存对话历史,提取重要信息
|
v
[输出模块] —— 流式输出回复内容
|
v
用户看到回复
</code></pre>
</div>
<h4>涉及知识点回顾</h4>
<p>本项目将综合运用前面章节的核心知识:</p>
<table>
<thead>
<tr><th>模块</th><th>涉及章节</th><th>核心知识点</th></tr>
</thead>
<tbody>
<tr><td>智能问答</td><td>第3-5章</td><td>LLM API调用、提示工程、流式输出</td></tr>
<tr><td>文档检索</td><td>第15-17章</td><td>文档加载、文本切分、Embedding、Chroma向量库</td></tr>
<tr><td>工具调用</td><td>第19-21章</td><td>Function Calling、ReAct模式、工具定义与路由</td></tr>
<tr><td>记忆功能</td><td>第22章</td><td>对话历史管理、长期记忆存储与检索</td></tr>
<tr><td>Web界面</td><td>第23章</td><td>Gradio组件、事件处理、界面布局</td></tr>
</tbody>
</table>
</div>
<div class="concept-section">
<h3>步骤一:项目初始化</h3>
<h4>创建项目目录结构</h4>
<p>首先创建项目根目录和必要的子目录:</p>
<pre><code class="language-bash">mkdir -p personal-ai-assistant/{src,data,docs,tests}
cd personal-ai-assistant
touch src/__init__.py
</code></pre>
<p>目录结构说明:</p>
<ul>
<li><code>src/</code>:源代码目录,包含各功能模块</li>
<li><code>data/</code>:数据目录,存放上传的文档和向量数据库</li>
<li><code>docs/</code>:项目文档</li>
<li><code>tests/</code>:测试代码</li>
</ul>
<h4>创建 requirements.txt</h4>
<p>列出项目所需的所有依赖包:</p>
<pre><code class="language-yaml"># LLM 相关
openai>=1.0.0
langchain>=0.1.0
langchain-openai>=0.0.5
langchain-community>=0.0.10
# 向量数据库
chromadb>=0.4.0
# 文档处理
pypdf>=3.0.0
python-docx>=0.8.11
unstructured>=0.11.0
# Embedding
sentence-transformers>=2.2.0
# Web 界面
gradio>=4.0.0
# 工具调用
requests>=2.31.0
# 配置管理
pyyaml>=6.0
python-dotenv>=1.0.0
# 其他工具
numpy>=1.24.0
tiktoken>=0.5.0
</code></pre>
<p>安装依赖:</p>
<pre><code class="language-bash">pip install -r requirements.txt
</code></pre>
<h4>创建 config.yaml 配置文件</h4>
<p>配置文件用于管理非敏感的配置项:</p>
<pre><code class="language-yaml"># 模型配置
model:
provider: "openai" # 可选: openai, ollama
name: "gpt-4o-mini"
temperature: 0.7
max_tokens: 2000
streaming: true
# Ollama 配置(如果使用本地模型)
ollama:
base_url: "http://localhost:11434"
model: "llama3.1"
# RAG 配置
rag:
chunk_size: 500
chunk_overlap: 50
top_k: 5
embedding_model: "sentence-transformers/all-MiniLM-L6-v2"
# 记忆配置
memory:
short_term_limit: 10 # 短期记忆保留最近N轮
long_term_enabled: true
# 工具配置
tools:
weather_api_key: "" # 从环境变量读取,此处仅占位
search_api_key: ""
# 向量数据库
vector_db:
persist_directory: "./data/chroma_db"
</code></pre>
<h4>创建 .env 文件管理敏感信息</h4>
<div class="concept-box warning">
<p><strong>注意:</strong> <code>.env</code> 文件包含敏感信息,<strong>切勿提交到Git仓库</strong>!请在 <code>.gitignore</code> 中添加 <code>.env</code>。</p>
</div>
<pre><code class="language-bash"># OpenAI API Key
OPENAI_API_KEY=sk-your-api-key-here
# 天气API Key(可选,如使用OpenWeatherMap)
WEATHER_API_KEY=your-weather-api-key
# 搜索API Key(可选,如使用SerpAPI或Bing Search)
SEARCH_API_KEY=your-search-api-key
</code></pre>
</div>
<div class="concept-section">
<h3>步骤二:基础对话功能</h3>
<h4>使用 OpenAI API 搭建基础对话</h4>
<p>在 <code>src/chat.py</code> 中创建基础对话模块:</p>
<pre><code class="language-python">import os
from typing import Iterator
from dotenv import load_dotenv
from openai import OpenAI, APIError, RateLimitError
# 加载环境变量
load_dotenv()
class ChatBot:
def __init__(self, model: str = "gpt-4o-mini", temperature: float = 0.7):
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.model = model
self.temperature = temperature
self.messages = [] # 对话历史
def chat(self, user_input: str) -> str:
"""非流式对话"""
self.messages.append({"role": "user", "content": user_input})
try:
response = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
temperature=self.temperature,
)
reply = response.choices[0].message.content
self.messages.append({"role": "assistant", "content": reply})
return reply
except APIError as e:
return f"API错误: {e}"
except RateLimitError:
return "请求过于频繁,请稍后再试。"
except Exception as e:
return f"发生错误: {e}"
def chat_stream(self, user_input: str) -> Iterator[str]:
"""流式对话,逐字返回"""
self.messages.append({"role": "user", "content": user_input})
try:
stream = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
temperature=self.temperature,
stream=True,
)
full_reply = ""
for chunk in stream:
if chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
full_reply += content
yield content
self.messages.append({"role": "assistant", "content": full_reply})
except Exception as e:
yield f"发生错误: {e}"
def clear_history(self):
"""清空对话历史"""
self.messages = []
# 运行测试
if __name__ == "__main__":
bot = ChatBot()
print("=== 基础对话测试 ===")
print("Bot:", bot.chat("你好,请介绍一下你自己。"))
print("-" * 40)
print("流式输出测试:")
for chunk in bot.chat_stream("讲一个简短的笑话"):
print(chunk, end="", flush=True)
print()
</code></pre>
<h4>使用 Ollama 本地模型(可选)</h4>
<p>如果你希望使用本地模型,可以替换为Ollama客户端:</p>
<pre><code class="language-python">from openai import OpenAI
class LocalChatBot:
def __init__(self, model: str = "llama3.1", base_url: str = "http://localhost:11434"):
# Ollama 兼容 OpenAI API 格式
self.client = OpenAI(base_url=f"{base_url}/v1", api_key="ollama")
self.model = model
self.messages = []
def chat(self, user_input: str) -> str:
self.messages.append({"role": "user", "content": user_input})
response = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
)
reply = response.choices[0].message.content
self.messages.append({"role": "assistant", "content": reply})
return reply
</code></pre>
<div class="concept-box success">
<p><strong>测试验证:</strong> 运行 <code>python src/chat.py</code>,确认能正常获取AI回复,流式输出能逐字显示。</p>
</div>
</div>
<div class="concept-section">
<h3>步骤三:添加RAG文档检索</h3>
<h4>创建RAG模块</h4>
<p>在 <code>src/rag.py</code> 中实现文档检索功能:</p>
<pre><code class="language-python">import os
from typing import List
from langchain_community.document_loaders import (
PyPDFLoader, TextLoader, UnstructuredMarkdownLoader
)
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.schema import Document
class RAGSystem:
def __init__(self, persist_dir: str = "./data/chroma_db"):
self.persist_dir = persist_dir
self.embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
self.vector_store = None
self.text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
separators=["\n\n", "\n", "。", ",", " ", ""]
)
def load_document(self, file_path: str) -> List[Document]:
"""加载单个文档"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"文件不存在: {file_path}")
ext = os.path.splitext(file_path)[1].lower()
if ext == ".pdf":
loader = PyPDFLoader(file_path)
elif ext == ".txt":
loader = TextLoader(file_path, encoding="utf-8")
elif ext in [".md", ".markdown"]:
loader = UnstructuredMarkdownLoader(file_path)
else:
raise ValueError(f"不支持的文件格式: {ext}")
return loader.load()
def add_documents(self, file_paths: List[str]):
"""加载并索引多个文档"""
all_docs = []
for fp in file_paths:
docs = self.load_document(fp)
all_docs.extend(docs)
print(f"已加载: {fp} ({len(docs)} 页/段)")
# 文档切分
chunks = self.text_splitter.split_documents(all_docs)
print(f"文档切分后共 {len(chunks)} 个片段")
# 存入向量数据库
self.vector_store = Chroma.from_documents(
documents=chunks,
embedding=self.embeddings,
persist_directory=self.persist_dir
)
self.vector_store.persist()
print("向量数据库已保存。")
def load_existing_db(self):
"""加载已有的向量数据库"""
if os.path.exists(self.persist_dir):
self.vector_store = Chroma(
persist_directory=self.persist_dir,
embedding_function=self.embeddings
)
return True
return False
def search(self, query: str, top_k: int = 5) -> List[Document]:
"""检索相关文档片段"""
if not self.vector_store:
if not self.load_existing_db():
return []
return self.vector_store.similarity_search(query, k=top_k)
def get_context(self, query: str, top_k: int = 5) -> str:
"""获取检索结果拼接的上下文文本"""
docs = self.search(query, top_k)
if not docs:
return ""
contexts = []
for i, doc in enumerate(docs, 1):
source = doc.metadata.get("source", "未知来源")
contexts.append(f"[文档{i}] 来源: {source}\n{doc.page_content}")
return "\n\n".join(contexts)
# 测试代码
if __name__ == "__main__":
rag = RAGSystem()
# 假设 data/ 目录下有测试文档
# rag.add_documents(["data/test.pdf", "data/notes.txt"])
# context = rag.get_context("什么是RAG?")
# print(context)
</code></pre>
<h4>集成RAG到对话中</h4>
<p>修改 <code>src/chat.py</code>,添加RAG支持:</p>
<pre><code class="language-python">from src.rag import RAGSystem
class ChatBot:
def __init__(self, model: str = "gpt-4o-mini", temperature: float = 0.7, use_rag: bool = False):
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.model = model
self.temperature = temperature
self.messages = []
self.use_rag = use_rag
self.rag = RAGSystem() if use_rag else None
def chat(self, user_input: str) -> str:
# 如果启用RAG,先检索相关文档
if self.use_rag and self.rag:
context = self.rag.get_context(user_input)
if context:
# 将检索结果注入系统提示
system_msg = {
"role": "system",
"content": f"你是智能助手。请基于以下参考文档回答问题,如果文档中没有相关信息,请明确说明。\n\n参考文档:\n{context}"
}
messages = [system_msg] + self.messages + [{"role": "user", "content": user_input}]
else:
messages = self.messages + [{"role": "user", "content": user_input}]
else:
messages = self.messages + [{"role": "user", "content": user_input}]
try:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=self.temperature,
)
reply = response.choices[0].message.content
self.messages.append({"role": "user", "content": user_input})
self.messages.append({"role": "assistant", "content": reply})
return reply
except Exception as e:
return f"发生错误: {e}"
</code></pre>
<div class="concept-box success">
<p><strong>测试问答效果:</strong></p>
<ol>
<li>准备一份测试PDF/TXT文档放入 <code>data/</code> 目录</li>
<li>运行 <code>rag.add_documents(["data/你的文档.pdf"])</code> 建立索引</li>
<li>提问与文档相关的问题,验证回答是否引用了文档内容</li>
<li>提问与文档无关的问题,验证助手是否能正确处理</li>
</ol>
</div>
</div>
<div class="concept-section">
<h3>步骤四:添加工具调用</h3>
<h4>定义工具</h4>
<p>在 <code>src/tools.py</code> 中定义可用工具:</p>
<pre><code class="language-python">import os
import json
import requests
from typing import Dict, Any, Callable
from dotenv import load_dotenv
load_dotenv()
class ToolManager:
def __init__(self):
self.tools: Dict[str, Dict[str, Any]] = {}
self._register_default_tools()
def _register_default_tools(self):
"""注册默认工具"""
self.register_tool(
name="weather_query",
description="查询指定城市的当前天气",
parameters={
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如'北京'、'Shanghai'"
}
},
"required": ["city"]
},
func=self._query_weather
)
self.register_tool(
name="calculator",
description="执行数学计算,如加减乘除、平方根等",
parameters={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "数学表达式,如'2+3*4'、'sqrt(16)'"
}
},
"required": ["expression"]
},
func=self._calculate
)
self.register_tool(
name="web_search",
description="搜索互联网获取最新信息",
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索关键词"
}
},
"required": ["query"]
},
func=self._web_search
)
def register_tool(self, name: str, description: str, parameters: dict, func: Callable):
"""注册新工具"""
self.tools[name] = {
"name": name,
"description": description,
"parameters": parameters,
"func": func
}
def get_tool_definitions(self) -> list:
"""获取工具定义列表(用于Function Calling)"""
return [
{
"type": "function",
"function": {
"name": t["name"],
"description": t["description"],
"parameters": t["parameters"]
}
}
for t in self.tools.values()
]
def execute(self, tool_name: str, arguments: dict) -> str:
"""执行指定工具"""
if tool_name not in self.tools:
return f"错误:未找到工具 '{tool_name}'"
try:
result = self.tools[tool_name]["func"](**arguments)
return str(result)
except Exception as e:
return f"工具执行错误: {e}"
# ===== 工具实现 =====
def _query_weather(self, city: str) -> str:
"""查询天气(示例实现,使用OpenWeatherMap API)"""
api_key = os.getenv("WEATHER_API_KEY")
if not api_key:
return "天气API Key未配置,无法查询天气。"
try:
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&lang=zh_cn&units=metric"
resp = requests.get(url, timeout=10)
data = resp.json()
if data.get("cod") != 200:
return f"查询失败: {data.get('message', '未知错误')}"
weather = data["weather"][0]["description"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
return f"{city}当前天气:{weather},温度{temp}°C(体感{feels_like}°C),湿度{humidity}%"
except Exception as e:
return f"天气查询出错: {e}"
def _calculate(self, expression: str) -> str:
"""安全计算器"""
allowed_names = {
"abs": abs, "round": round,
"max": max, "min": min,
"sum": sum, "len": len
}
try:
# 安全求值:只允许数字和基本运算符
result = eval(expression, {"__builtins__": {}}, allowed_names)
return f"计算结果:{result}"
except Exception as e:
return f"计算错误: {e}"
def _web_search(self, query: str) -> str:
"""网页搜索(示例使用DuckDuckGo免费搜索)"""
try:
from duckduckgo_search import DDGS
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=3))
if not results:
return "未找到相关搜索结果。"
output = []
for i, r in enumerate(results, 1):
output.append(f"{i}. {r['title']}\n{r['href']}\n{r['body']}")
return "\n\n".join(output)
except ImportError:
return "未安装 duckduckgo-search,请执行: pip install duckduckgo-search"
except Exception as e:
return f"搜索出错: {e}"
</code></pre>
<h4>工具路由逻辑</h4>
<p>在 <code>src/agent.py</code> 中实现工具调用路由:</p>
<pre><code class="language-python">import json
from typing import Optional
from openai import OpenAI
from src.tools import ToolManager
class Agent:
def __init__(self, model: str = "gpt-4o-mini"):
self.client = OpenAI()
self.model = model
self.tool_manager = ToolManager()
def run(self, user_input: str) -> str:
"""运行Agent:判断是否需要调用工具"""
messages = [
{"role": "system", "content": "你是智能助手,可以使用工具帮助用户。如果需要使用工具,请调用对应函数。"},
{"role": "user", "content": user_input}
]
# 第一次调用:让模型判断是否需要工具
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
tools=self.tool_manager.get_tool_definitions(),
tool_choice="auto",
)
message = response.choices[0].message
# 如果需要调用工具
if message.tool_calls:
# 添加助手消息到历史
messages.append({
"role": "assistant",
"content": message.content or "",
"tool_calls": [tc.model_dump() for tc in message.tool_calls]
})
# 执行每个工具调用
for tool_call in message.tool_calls:
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"[Agent] 调用工具: {tool_name}({arguments})")
result = self.tool_manager.execute(tool_name, arguments)
# 添加工具返回结果
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# 第二次调用:让模型整合工具结果并回复
final_response = self.client.chat.completions.create(
model=self.model,
messages=messages,
)
return final_response.choices[0].message.content
# 不需要工具,直接返回回复
return message.content or ""
# 测试
if __name__ == "__main__":
agent = Agent()
print(agent.run("北京今天天气怎么样?"))
print("-" * 40)
print(agent.run("计算 123 * 456"))
</code></pre>
<div class="concept-box info">
<p><strong>工具调用流程说明:</strong></p>
<ol>
<li>用户输入问题</li>
<li>LLM判断是否需要工具(通过 <code>tools</code> 参数提供工具定义)</li>
<li>如需工具,LLM返回 <code>tool_calls</code> 而非直接回复</li>
<li>Agent执行对应工具函数,获取结果</li>
<li>将工具结果再次传给LLM,生成最终回复</li>
</ol>
</div>
</div>
<div class="concept-section">
<h3>步骤五:添加记忆功能</h3>
<h4>创建记忆管理模块</h4>
<p>在 <code>src/memory.py</code> 中实现短期和长期记忆:</p>
<pre><code class="language-python">import os
import json
from typing import List, Dict
from datetime import datetime
class MemoryManager:
def __init__(self, short_term_limit: int = 10, long_term_file: str = "./data/long_term_memory.json"):
self.short_term_limit = short_term_limit
self.long_term_file = long_term_file
self.short_term: List[Dict] = [] # 短期记忆:最近N轮对话
self.long_term: Dict[str, str] = {} # 长期记忆:关键信息摘要
self._load_long_term()
def add_interaction(self, user_msg: str, assistant_msg: str):
"""添加一轮对话到短期记忆"""
self.short_term.append({
"role": "user",
"content": user_msg,
"timestamp": datetime.now().isoformat()
})
self.short_term.append({
"role": "assistant",
"content": assistant_msg,
"timestamp": datetime.now().isoformat()
})
# 保持短期记忆在限制范围内
while len(self.short_term) > self.short_term_limit * 2:
self.short_term.pop(0)
def get_short_term_messages(self) -> List[Dict]:
"""获取短期记忆(用于传给LLM)"""
return [{"role": m["role"], "content": m["content"]} for m in self.short_term]
def add_long_term(self, key: str, value: str):
"""添加长期记忆"""
self.long_term[key] = value
self._save_long_term()
def get_long_term_context(self) -> str:
"""获取长期记忆文本(用于系统提示)"""
if not self.long_term:
return ""
items = [f"- {k}: {v}" for k, v in self.long_term.items()]
return "已记住的用户信息:\n" + "\n".join(items)
def extract_and_save(self, user_msg: str, assistant_msg: str):
"""从对话中提取重要信息保存到长期记忆(简化版)"""
# 实际项目中可以使用LLM来提取关键信息
# 这里仅作示例:如果用户明确说"记住",则保存
if "记住" in user_msg or "记住" in assistant_msg:
# 简单提取"记住"后面的内容
# 实际应使用LLM进行信息抽取
pass
def _load_long_term(self):
"""从文件加载长期记忆"""
if os.path.exists(self.long_term_file):
with open(self.long_term_file, "r", encoding="utf-8") as f:
self.long_term = json.load(f)
def _save_long_term(self):
"""保存长期记忆到文件"""
os.makedirs(os.path.dirname(self.long_term_file), exist_ok=True)
with open(self.long_term_file, "w", encoding="utf-8") as f:
json.dump(self.long_term, f, ensure_ascii=False, indent=2)
def clear_short_term(self):
"""清空短期记忆"""
self.short_term = []
def clear_long_term(self):
"""清空长期记忆"""
self.long_term = {}
self._save_long_term()
</code></pre>
<h4>集成记忆到对话</h4>
<p>更新 <code>src/chat.py</code> 中的 <code>ChatBot</code> 类:</p>
<pre><code class="language-python">from src.memory import MemoryManager
class ChatBot:
def __init__(self, model: str = "gpt-4o-mini", temperature: float = 0.7,
use_rag: bool = False, use_memory: bool = True):
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.model = model
self.temperature = temperature
self.use_rag = use_rag
self.use_memory = use_memory
self.rag = RAGSystem() if use_rag else None
self.memory = MemoryManager() if use_memory else None
def chat(self, user_input: str) -> str:
# 构建消息列表
messages = []
# 1. 系统提示
system_parts = ["你是智能助手,能够回答问题、检索文档、调用工具。"]
if self.memory:
lt = self.memory.get_long_term_context()
if lt:
system_parts.append(lt)
system_msg = "\n\n".join(system_parts)
messages.append({"role": "system", "content": system_msg})
# 2. 短期记忆
if self.memory:
messages.extend(self.memory.get_short_term_messages())
# 3. RAG上下文(如果是文档相关问题)
user_msg_content = user_input
if self.use_rag and self.rag:
context = self.rag.get_context(user_input)
if context:
user_msg_content = f"基于以下参考文档回答问题:\n{context}\n\n用户问题:{user_input}"
messages.append({"role": "user", "content": user_msg_content})
# 调用LLM
try:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=self.temperature,
)
reply = response.choices[0].message.content
# 保存到记忆
if self.memory:
self.memory.add_interaction(user_input, reply)
return reply
except Exception as e:
return f"发生错误: {e}"
def remember(self, key: str, value: str):
"""手动添加长期记忆"""
if self.memory:
self.memory.add_long_term(key, value)
return f"已记住: {key} = {value}"
return "记忆功能未启用"
def clear_memory(self):
"""清空记忆"""
if self.memory:
self.memory.clear_short_term()
self.memory.clear_long_term()
</code></pre>
<div class="concept-box success">
<p><strong>测试连续对话:</strong></p>
<pre><code class="language-python">bot = ChatBot(use_memory=True)
print(bot.chat("我叫张三,今年28岁。"))
print(bot.chat("我叫什么名字?")) # 应能回答"张三"
print(bot.remember("职业", "软件工程师"))
print(bot.chat("我的职业是什么?")) # 应能回答"软件工程师"
</code></pre>
</div>
</div>
<div class="concept-section">
<h3>步骤六:Web界面</h3>
<h4>使用Gradio搭建Web UI</h4>
<p>在 <code>src/webui.py</code> 中创建Gradio界面:</p>
<pre><code class="language-python">import gradio as gr
from src.chat import ChatBot
from src.rag import RAGSystem
class AIAssistantWebUI:
def __init__(self):
self.bot = ChatBot(use_rag=True, use_memory=True)
self.rag = self.bot.rag
def respond(self, message: str, history: list) -> str:
"""处理用户消息并返回回复"""
if not message.strip():
return ""
# 使用流式输出
full_response = ""
for chunk in self.bot.chat_stream(message):
full_response += chunk
yield full_response
def upload_files(self, files: list) -> str:
"""上传文档并建立索引"""
if not files:
return "未选择文件"
file_paths = [f.name for f in files]
try:
self.rag.add_documents(file_paths)
return f"成功上传并索引 {len(file_paths)} 个文件"
except Exception as e:
return f"上传失败: {e}"
def clear_chat(self):
"""清空对话"""
self.bot.clear_history()
self.bot.clear_memory()
return None