conda

Conda配置完全指南-CSDN

Conda 是一个开源的跨平台包管理与环境管理工具,广泛应用于数据科学、机器学习及 Python 开发领域。它不仅能帮助用户快速安装、更新和卸载第三方库,还能创建相互隔离的虚拟环境,解决不同项目之间的依赖冲突问题。例如,项目 A 依赖 Python 3.7 和 NumPy 1.0,而项目 B 需要 Python 3.10 和 NumPy 2.0,通过 conda 可分别创建独立环境,避免版本冲突。此外,conda 不仅支持 Python 包,还能管理 R、C/C++ 等非 Python 依赖,极大提升了跨语言开发的便捷性。

Anaconda 和 Miniconda

  • Anaconda 是基于 conda 的完整发行版,预装了超过 250 个科学计算和数据分析的常用工具包(如 NumPy、Pandas、Jupyter),适合新手或需要快速搭建开发环境的用户。但 Anaconda 的安装包体积较大(约 3 GB),对存储空间有限的用户可能不够友好。

  • Miniconda 是 conda 的极简版本,仅包含核心的 conda 工具、Python 基础环境和所依赖的包以及少量其他实用包。(安装包约 50 MB)。用户需手动安装所需依赖,适合熟悉 Python 生态或追求轻量化的开发者。例如,若仅需 TensorFlow 和 PyTorch,可通过 Miniconda 按需安装,避免冗余占用。

添加环境变量

将安装目录下的Scripts目录添加到用户和系统变量的Path中
D:\Development\Miniconda3\Scripts

conda相关命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 指定Python版本创建环境(环境名ai70、python版本3.12)
conda create --name ai70 python=3.12

# 列出所有已创建的 conda 环境(当前激活的环境会以星号 `*` 标记)
conda env list

# 激活环境
conda activate ai70

# 退出环境
# 退出当前激活的环境后,会返回到上一个环境(通常是 `base` 环境,或者如果没有其他环境激活,则返回到系统默认环境)
conda deactivate

# 删除环境
conda env remove -n <环境名称>

# 安装包
conda install <包名称>
pip install <包名称>

# 删除包
conda remove <包名称>
pip uninstall <包名称>

VSCode中切换环境

fastapi

FastAPI文档

安装

1
2
pip install fastapi
pip install uvicorn

基础开发

ai_api.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from fastapi import FastAPI
import ollama

app = FastAPI()

# 装饰器 实现内部功能 黑盒操作
@app.get("/")
async def root():
return {"message": "Hello World"}

# 携带 title 参数, 返回 ai 的 调用接口
@app.get("/question")
async def question(title = ""):
if title == "":
return {"message": "请输入你需要问的问题"}

response = ollama.chat(
model='deepseek-r1:1.5b',
messages=[{'role': 'user', 'content': title}],
)

return {"content": response['message']['content']}

运行服务器

1
uvicorn ai_api:app --port 8500 --host 127.0.0.1 --reload

打开网页:127.0.0.1:8500

显示hello world说明服务启动成功

打开网页:127.0.0.1:8500/question?title=<你想问的问题>

AI聊天项目

实现功能:角色扮演 + 上下文记忆 + 思维链提取 + 前后端交互
网页聊天界面:通过 HTML + JS 实现
自定义 AI 人设:system_prompt 嵌入消息
多轮对话记忆:前端传messa历史
分离思考过程:<think>标签提取
清除对话功能:前端startNewChat()设置消息提示AI

main.py

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
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import ollama
import re

app = FastAPI()

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 存储对话历史(简单版,按会话可扩展为 session)
# 这里我们不持久化,每次新请求从前端传 history

@app.get("/")
async def get_chat_page():
return FileResponse("static/index.html")

def extract_think_content(text):
"""提取 <think>...</think> 内容,并返回 (think, response)"""
pattern = r"<think>(.*?)</think>"
match = re.search(pattern, text, re.DOTALL)
if match:
think = match.group(1).strip()
# 移除原文中的 <think>...</think>
response = re.sub(pattern, "", text, flags=re.DOTALL).strip()
return think, response
return None, text.strip()

@app.post("/api/chat")
async def chat(request: dict):
messages = request.get("messages", [])
persona = request.get("persona", "尖酸刻薄的网友,话语充满攻击性").strip()

if not messages:
raise HTTPException(status_code=400, detail="消息不能为空")

try:
# 构建 prompt,明确角色和人设
system_prompt = f"""
你的人设是:{persona}。请严格保持以该人设身份性格与用户对话。
""".strip()

# 构建上下文
full_messages = [{"role": "system", "content": system_prompt}]
full_messages.extend(messages) # 包含完整的对话历史

response = ollama.chat(
model="deepseek-r1:8b", # 设置模型
messages=full_messages,
)

ai_content = response["message"]["content"]

# 提取思考过程和正式回复
think, response_text = extract_think_content(ai_content)

return {
"response": response_text,
"think": think or "即答"
}

except Exception as e:
print("Ollama error:", e)
raise HTTPException(status_code=500, detail="AI 调用失败")

index.html

前端html代码应放在项目的static文件夹下

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
<!DOCTYPE html>
<html lang="zh">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>本地 AI 聊天</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--primary: #6366f1;
--primary-dark: #4f46e5;
--secondary: #8b5cf6;
--background: #f8fafc;
--surface: #ffffff;
--surface-elevated: #f1f5f9;
--text-primary: #1e293b;
--text-secondary: #64748b;
--border: #e2e8f0;
--user-message: #6366f1;
--ai-message: #f1f5f9;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
--radius: 12px;
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: var(--background);
color: var(--text-primary);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
line-height: 1.6;
}

.container {
width: 100%;
max-width: 900px;
height: 85vh;
max-height: 800px;
display: flex;
flex-direction: column;
border-radius: var(--radius);
overflow: hidden;
box-shadow: var(--shadow-lg);
background: var(--surface);
transition: var(--transition);
}

header {
background: linear-gradient(135deg, var(--primary), var(--secondary));
color: white;
padding: 20px 24px;
display: flex;
align-items: center;
justify-content: space-between;
box-shadow: var(--shadow);
}

header h1 {
font-size: 1.5rem;
font-weight: 700;
display: flex;
align-items: center;
gap: 12px;
}

.theme-toggle {
background: rgba(255, 255, 255, 0.2);
border: none;
color: white;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: var(--transition);
}

.theme-toggle:hover {
background: rgba(255, 255, 255, 0.3);
transform: rotate(15deg);
}

.config-bar {
background: var(--surface-elevated);
padding: 16px 24px;
border-bottom: 1px solid var(--border);
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: center;
}

.config-group {
display: flex;
align-items: center;
gap: 10px;
flex: 1;
min-width: 250px;
}

.config-group label {
font-weight: 600;
color: var(--text-secondary);
font-size: 14px;
white-space: nowrap;
}

.config-group input[type="text"] {
flex: 1;
padding: 10px 16px;
border: 1px solid var(--border);
border-radius: 8px;
font-size: 14px;
background: var(--surface);
color: var(--text-primary);
transition: var(--transition);
}

.config-group input[type="text"]:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.btn {
padding: 10px 20px;
border: none;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}

.btn-primary {
background: var(--primary);
color: white;
}

.btn-primary:hover {
background: var(--primary-dark);
transform: translateY(-2px);
box-shadow: var(--shadow);
}

.btn-secondary {
background: var(--surface-elevated);
color: var(--text-primary);
border: 1px solid var(--border);
}

.btn-secondary:hover {
background: var(--border);
}

.chat-container {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}

.chat-box {
flex: 1;
overflow-y: auto;
padding: 24px;
background: var(--background);
display: flex;
flex-direction: column;
gap: 16px;
}

.chat-box::-webkit-scrollbar {
width: 6px;
}

.chat-box::-webkit-scrollbar-track {
background: transparent;
}

.chat-box::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}

.chat-box::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}

.message {
max-width: 75%;
padding: 16px 20px;
border-radius: var(--radius);
box-shadow: var(--shadow-sm);
animation: fadeInUp 0.3s ease-out;
position: relative;
}

@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(10px);
}

to {
opacity: 1;
transform: translateY(0);
}
}

.user {
align-self: flex-end;
background: var(--user-message);
color: white;
border-bottom-right-radius: 4px;
}

.ai {
align-self: flex-start;
background: var(--ai-message);
color: var(--text-primary);
border-bottom-left-radius: 4px;
}

.think-block {
font-size: 14px;
color: var(--text-secondary);
background: var(--surface);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
margin-bottom: 12px;
cursor: pointer;
transition: var(--transition);
}

.think-block:hover {
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.think-block summary {
font-weight: 600;
color: var(--primary);
list-style: none;
display: flex;
align-items: center;
gap: 8px;
}

.think-block summary::-webkit-details-marker {
display: none;
}

.think-block[open] summary i {
transform: rotate(90deg);
}

.think-block summary i {
transition: var(--transition);
}

.think-block-content {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
font-style: italic;
color: var(--text-secondary);
}

.input-area {
padding: 20px 24px;
background: var(--surface);
border-top: 1px solid var(--border);
display: flex;
gap: 12px;
}

#user-input {
flex: 1;
padding: 14px 20px;
border: 1px solid var(--border);
border-radius: 30px;
font-size: 15px;
background: var(--surface);
color: var(--text-primary);
transition: var(--transition);
}

#user-input:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.send-btn {
width: 50px;
height: 50px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}

.send-btn:active {
transform: scale(0.95);
}

/* 深色模式 */
body.dark-mode {
--background: #0f172a;
--surface: #1e293b;
--surface-elevated: #334155;
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--border: #334155;
--ai-message: #334155;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
.container {
height: 95vh;
max-height: none;
border-radius: 0;
}

header h1 {
font-size: 1.25rem;
}

.config-bar {
padding: 12px 16px;
}

.config-group {
min-width: 100%;
}

.chat-box {
padding: 16px;
}

.message {
max-width: 85%;
}

.input-area {
padding: 16px;
}
}

/* 加载动画 */
.typing-indicator {
display: flex;
align-items: center;
gap: 4px;
padding: 16px 20px;
background: var(--ai-message);
border-radius: var(--radius);
border-bottom-left-radius: 4px;
width: fit-content;
}

.typing-indicator span {
height: 8px;
width: 8px;
background: var(--text-secondary);
border-radius: 50%;
display: inline-block;
animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
animation-delay: 0.4s;
}

@keyframes typing {

0%,
60%,
100% {
transform: translateY(0);
opacity: 0.7;
}

30% {
transform: translateY(-10px);
opacity: 1;
}
}
</style>
</head>

<body>
<div class="container">
<header>
<h1>
<i class="fas fa-robot"></i>
本地 AI 聊天助手
</h1>
<button class="theme-toggle" onclick="toggleTheme()" title="切换主题">
<i class="fas fa-moon"></i>
</button>
</header>
<div class="config-bar">
<div class="config-group">
<label for="persona">
<i class="fas fa-user-cog"></i> AI 人设:
</label>
<input type="text" id="persona" placeholder="例如:友善的助手、专业的顾问..." value="知识渊博且乐于助人的AI助手" />
</div>
<button class="btn btn-secondary" onclick="startNewChat()">
<i class="fas fa-plus-circle"></i> 新对话
</button>
</div>
<div class="chat-container">
<div class="chat-box" id="chat-box">
<div class="message ai">
<div class="think-block">
<summary>
<i class="fas fa-brain"></i> AI 思考过程
</summary>
<div class="think-block-content">
欢迎新用户!我将以当前设定的人设开始为您提供帮助。
</div>
</div>
你好!我是你的AI助手,很高兴为你服务。你可以随时修改我的人设,让我以不同的方式与你交流。有什么我可以帮助你的吗?
</div>
</div>
<div class="input-area">
<input type="text" id="user-input" placeholder="输入你的问题..." autofocus />
<button class="btn btn-primary send-btn" onclick="sendMessage()">
<i class="fas fa-paper-plane"></i>
</button>
</div>
</div>
</div>
<script>
const chatBox = document.getElementById("chat-box");
const userInput = document.getElementById("user-input");
const themeToggle = document.querySelector(".theme-toggle i");
let chatHistory = [];
let isDarkMode = localStorage.getItem("darkMode") === "true";
// 初始化主题
if (isDarkMode) {
document.body.classList.add("dark-mode");
themeToggle.classList.remove("fa-moon");
themeToggle.classList.add("fa-sun");
}
async function sendMessage() {
const message = userInput.value.trim();
const persona = document.getElementById("persona").value.trim() || "知识伙伴";
if (!message) return;
addMessage(message, "user");
chatHistory.push({ role: "user", content: message });
userInput.value = "";
// 显示输入指示器
showTypingIndicator();
try {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: chatHistory, persona }),
});
const data = await res.json();
// 移除输入指示器
removeTypingIndicator();
addAIMessage(data.response, data.think);
chatHistory.push({ role: "assistant", content: data.response });
} catch (err) {
removeTypingIndicator();
addMessage("❌ 请求失败,请检查后端是否运行。", "ai");
}
}
function showTypingIndicator() {
const indicator = document.createElement("div");
indicator.className = "typing-indicator";
indicator.id = "typing-indicator";
indicator.innerHTML = `
<span></span>
<span></span>
<span></span>
`;
chatBox.appendChild(indicator);
chatBox.scrollTop = chatBox.scrollHeight;
}
function removeTypingIndicator() {
const indicator = document.getElementById("typing-indicator");
if (indicator) {
indicator.remove();
}
}
function addMessage(text, sender) {
const msg = document.createElement("div");
msg.className = `message ${sender}`;
msg.textContent = text;
chatBox.appendChild(msg);
chatBox.scrollTop = chatBox.scrollHeight;
}
function addAIMessage(response, think) {
const msg = document.createElement("div");
msg.className = "message ai";
const thinkBlock = document.createElement("div");
thinkBlock.className = "think-block";
thinkBlock.innerHTML = `
<summary>
<i class="fas fa-brain"></i> AI 思考过程
</summary>
<div class="think-block-content">${think}</div>
`;
const responseText = document.createElement("div");
responseText.textContent = response;
msg.appendChild(thinkBlock);
msg.appendChild(responseText);
chatBox.appendChild(msg);
chatBox.scrollTop = chatBox.scrollHeight;
}
function startNewChat() {
chatBox.innerHTML = `
<div class="message ai">
<div class="think-block">
<summary>
<i class="fas fa-brain"></i> AI 思考过程
</summary>
<div class="think-block-content">
开始新的对话,重置上下文。
</div>
</div>
对话已重置!我们可以开始新的话题了。有什么我可以帮助你的吗?
</div>
`;
chatHistory = [];
}
function toggleTheme() {
isDarkMode = !isDarkMode;
document.body.classList.toggle("dark-mode");
localStorage.setItem("darkMode", isDarkMode);
if (isDarkMode) {
themeToggle.classList.remove("fa-moon");
themeToggle.classList.add("fa-sun");
} else {
themeToggle.classList.remove("fa-sun");
themeToggle.classList.add("fa-moon");
}
}
userInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") sendMessage();
});
// 自动调整高度
function autoResize() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 120) + 'px';
}
userInput.addEventListener('input', autoResize);
</script>
</body>

</html>

完成效果