用LangChain构建一个Agent,本质上就是三行核心代码:

  1. 准备工具 tools = load_tools(...)
  2. 创建大脑 llm = OpenAI(...)
  3. 组装成Agent agent = initialize_agent(tools, llm, agent_type)

然后你就可以像对人一样对它下命令:agent.run(“你的问题”)

它最大的魅力在于,你不需要告诉它具体每一步该怎么做,你只需要给它工具目标,它会自己思考出步骤并调用工具去完成。

来个实际例子:让它帮你解决问题

假如,你的Agent已经建好了!让它帮你工作吧。

1
2
# 问一个需要多步推理的问题
agent.run("目前苹果公司的CEO是谁?他今年多少岁了?")

当你运行这段代码,并且打开了 verbose=True,你会在控制台看到类似这样的“内心独白”(这就是ReAct模式的精髓):

思考 (Thought): 用户问的是苹果公司CEO的年龄。我需要先知道谁是苹果公司的CEO,然后再去查他的年龄。
行动 (Action): 我应该使用搜索工具(SerpAPI)来查找“苹果公司现任CEO”。
观察 (Observation): 工具返回结果:蒂姆·库克 (Tim Cook)。
思考 (Thought): 好的,现在我知道CEO是蒂姆·库克了。接下来我需要查他的年龄。继续使用搜索工具。
行动 (Action): 使用搜索工具查找“Tim Cook 年龄”。
观察 (Observation): 工具返回结果:蒂姆·库克出生于1960年11月1日。(假设今年是2024年)
思考 (Thought): 现在我有了出生年份,我可以用数学工具来计算他的年龄。2024减去1960等于64。
行动 (Action): 使用计算器工具:2024 - 1960
观察 (Observation): 工具返回结果:64
最终回答 (Final Answer): 苹果公司的现任CEO是蒂姆·库克,他今年64岁。

大致思路是这样的👇

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
from langchain_ollama import ChatOllama
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain_classic.agents import AgentType, initialize_agent

# llm实例
llm = ChatOllama(
base_url="http://localhost:11434", # Ollama 服务地址
model="qwen2.5:3b" # 模型名称
)

# 1. 加载内置工具 - 使用load_tools函数
tools = load_tools(["llm-math", "wikipedia"], llm=llm)

# 现在你的工具包里有:
# 1. llm-math: 数学计算
# 2. wikipedia: 维基百科搜索

# 2. 组装Agent
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, # 注意是 AgentType 不是 AgentState
verbose=True
)

# 3. 测试
result = agent.invoke("如果我有15个苹果,吃了3个,又买了原数量2倍的苹果,现在一共有多少个?")

但是上面这个用不了,因为大模型每一轮返回的答案不是工具要求的输入(纯数学表达式),不过思想差不多。

系统命令执行工具

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
from langchain_classic.agents import Tool, AgentType, initialize_agent
from langchain_ollama import ChatOllama
import subprocess
import os
import warnings
from langchain_core._api.deprecation import LangChainDeprecationWarning

warnings.filterwarnings("ignore", category=LangChainDeprecationWarning)


def run_terminal_command(command):
"""在终端中执行命令并返回结果"""
try:
# 安全限制:只允许某些命令
allowed_commands = ['ls', 'dir', 'pwd', 'echo', 'date', 'whoami', 'python --version']

# 检查命令是否在允许列表中
cmd_base = command.split()[0] if command.split() else ""
if cmd_base not in ['ls', 'dir', 'pwd', 'echo', 'date', 'whoami', 'python']:
return f"命令 '{command}' 不在允许列表中。允许的命令: {allowed_commands}"

# 执行命令
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)

if result.returncode == 0:
return f"命令执行成功:\n{result.stdout}"
else:
return f"命令执行失败:\n错误: {result.stderr}\n返回码: {result.returncode}"

except subprocess.TimeoutExpired:
return "命令执行超时"
except Exception as e:
return f"执行命令时出错: {e}"


# 创建终端工具
terminal_tool = Tool(
name="Terminal",
func=run_terminal_command,
description="在终端中执行系统命令。允许的命令: ls, dir, pwd, echo, date, whoami, python --version"
)

# 初始化LLM和agent
llm = ChatOllama(temperature=0, model="qwen2.5:3b")
agent = initialize_agent(
[terminal_tool],
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True
)

# 使用agent与终端交互
result = agent.invoke({"input": "请查看当前目录的内容"})
print(result["output"])

很可爱的输出👇

C:\Users\86158\AppData\Local\Programs\Python\Python312\python.exe D:\course\python代码\lc\test002.py

Entering new AgentExecutor chain…
我需要使用ls命令来查看当前目录的内容
Action: Terminal
Action Input: ls
Observation: 命令执行失败:
错误: ‘ls’ 不是内部或外部命令,也不是可运行的程序
或批处理文件。

返回码: 1
Thought:这可能是因为在当前环境中没有找到 “ls” 命令。在某些系统中,“ls” 是一个 Unix/Linux 系统特有的命令,在 Windows 环境下可能会用到其他命令来查看目录内容,比如 dir

我将尝试使用 dir 来查看当前目录的内容。
Action: Terminal
Action Input: dir
Observation: 命令执行成功:
驱动器 D 中的卷是 Data
卷的序列号是 446E-CA61

D:\course\python代码\lc 的目录

2025/11/28 14:12

.
2025/11/20 17:29 ..
2025/11/27 17:32 .idea
2025/11/20 17:29 .venv
2025/11/28 13:36 194 test.py
2025/11/28 14:12 1,936 test002.py
2025/11/27 17:15 1,125 test003.py
3 个文件 3,255 字节
4 个目录 60,436,148,224 可用字节

Thought:我已成功查看了当前目录的内容。以下是当前目录下的文件和子目录列表:

  • . (当前目录)
  • .. (上一级目录)
  • .idea (.idea 文件夹)
  • .venv (.venv 文件夹)
  • test.py (一个名为test.py的文件)
  • test002.py (一个名为test002.py的文件)
  • test003.py (一个名为test003.py的文件)

Final Answer: 当前目录下的内容如下:

  • . (当前目录)
  • .. (上一级目录)
  • .idea (.idea 文件夹)
  • .venv (.venv 文件夹)
  • test.py (一个名为test.py的文件)
  • test002.py (一个名为test002.py的文件)
  • test003.py (一个名为test003.py的文件)

Finished chain.
当前目录下的内容如下:

  • . (当前目录)
  • .. (上一级目录)
  • .idea (.idea 文件夹)
  • .venv (.venv 文件夹)
  • test.py (一个名为test.py的文件)
  • test002.py (一个名为test002.py的文件)
  • test003.py (一个名为test003.py的文件)

Process finished with exit code 0

工具 + LLM 成语接龙

(笑成大奋了)

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
from langchain_classic.agents import Tool, AgentType, initialize_agent
from langchain_community.llms import Ollama


def get_last_character(idiom):
"""工具:提取成语的最后一个字"""
if not idiom or len(idiom) < 1:
return "请输入有效的成语"

# 提取最后一个字
last_char = idiom[-1]
return f"成语 '{idiom}' 的最后一个字是: '{last_char}'"


def check_idiom_validity(idiom):
"""工具:检查是否是四字成语"""
if len(idiom) == 4 and all('\u4e00' <= char <= '\u9fff' for char in idiom):
return f"'{idiom}' 是有效的四字成语"
else:
return f"'{idiom}' 不是有效的四字成语"


# 创建工具
idiom_tools = [
Tool(
name="GetLastChar",
func=get_last_character,
description="提取成语的最后一个字,输入一个成语"
),
Tool(
name="CheckIdiom",
func=check_idiom_validity,
description="检查是否是有效的四字成语"
)
]

# 使用本地模型
llm = Ollama(model="qwen2.5:3b")

# 创建agent
agent = initialize_agent(
idiom_tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True
)

print("🎮 成语接龙游戏开始!")
print("规则:下一个成语的第一个字要和上一个成语的最后一个字相同")

# 开始游戏
current_idiom = "一帆风顺"
print(f"\n起始成语: {current_idiom}")

for round_num in range(5): # 玩5轮
print(f"\n--- 第{round_num + 1}轮 ---")

# 获取当前成语的最后一个字
last_char_result = get_last_character(current_idiom)
last_char = current_idiom[-1]
print(f"需要接的字: '{last_char}'")

# 让AI接龙
prompt = f"请接一个以'{last_char}'开头的四字成语"
result = agent.invoke({"input": prompt})

# 提取AI回复中的成语
ai_response = result['output']
print(f"AI回复: {ai_response}")

# 简单提取可能的成语(实际可以更智能)
for i in range(len(ai_response) - 3):
candidate = ai_response[i:i + 4]
if check_idiom_validity(candidate) == f"'{candidate}' 是有效的四字成语" and candidate[0] == last_char:
current_idiom = candidate
print(f"✅ 接龙成功: {current_idiom}")
break
else:
print("❌ AI没有给出有效的接龙成语")
break

print(f"\n游戏结束!最终成语: {current_idiom}")

hhh

C:\Users\86158\AppData\Local\Programs\Python\Python312\python.exe D:\course\python代码\lc\test002.py
D:\course\python代码\lc\test002.py:38: LangChainDeprecationWarning: The class Ollama was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the langchain-ollama package and should be used instead. To use it run pip install -U langchain-ollama and import as from langchain_ollama import OllamaLLM``.
llm = Ollama(model=”qwen2.5:3b”)
D:\course\python代码\lc\test002.py:41: LangChainDeprecationWarning: LangChain agents will continue to be supported, but it is recommended for new use cases to be built with LangGraph. LangGraph offers a more flexible and full-featured framework for building agents, including support for tool-calling, persistence of state, and human-in-the-loop workflows. For details, refer to the LangGraph documentation as well as guides for Migrating from AgentExecutor and LangGraph’s Pre-built ReAct agent.
agent = initialize_agent(
🎮 成语接龙游戏开始!
规则:下一个成语的第一个字要和上一个成语的最后一个字相同

起始成语: 一帆风顺

— 第1轮 —
需要接的字: ‘顺’

Entering new AgentExecutor chain…
我需要找到一个以“顺”字开头的有效四字成语。
Action: CheckIdiom
Action Input: 顺
Observation: ‘顺’ 不是有效的四字成语
Thought:看来我找不到以”顺”字开头的有效四字成语。可能是因为输入的“顺”本身就是不完整的成语,或者是其本身没有以”顺”字开头的有效成语。接下来我会尝试其他方法来找到答案。
Action: GetLastChar
Action Input: 顺
Observation: 成语 ‘顺’ 的最后一个字是: ‘顺’
Thought:现在我意识到获取最后一个字的函数并不能直接帮我找出符合条件的成语,因此我需要使用不同的策略来寻找一个以“顺”字开头的有效四字成语。我会从已知的一些固定结构和具有普遍认知性的成语着手。
Action: CheckIdiom
Action Input: 顺风
Observation: ‘顺风’ 不是有效的四字成语
Thought:我继续尝试其他可能的以“顺”字开头的有效成语组合,可能会有其他的正确答案。接下来我会测试一些不同的组合。
Action: CheckIdiom
Action Input: 一顺
Observation: ‘一顺’ 不是有效的四字成语
Thought:经过多次尝试和检查无效的四字成语,我发现了一个符合条件的答案——“顺其自然”(其实这个成语是“顺”的最后一个字)。这是一个以“顺”字开头的有效四字成语。
Final Answer: 一个以“顺”字开头的有效四字成语是“顺其自然”。

Finished chain.
AI回复: 一个以“顺”字开头的有效四字成语是“顺其自然”。
✅ 接龙成功: 顺其自然

— 第2轮 —
需要接的字: ‘然’

Entering new AgentExecutor chain…
我需要找一个以“然”字开头的有效四字成语。
Action: CheckIdom
Action Input: 然
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:我需要使用CheckIdiom来确认是否存在一个以“然”字开头的有效四字成语。
Action: CheckIdom
Action Input: 然
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:看来我之前使用的工具名称可能输入有误。实际上,CheckIdiom应该用来检查一个四字成语是否有效,并不是找以某字开头的有效成语。我们需要用不同的方法来找这样的成语。

我会尝试查找”然”字开头的四字成语。
Action: CheckIdom
Action Input: 然
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:我需要使用CheckIdom来确认是否存在一个以“然”字开头的有效四字成语。
Action: GetLastChar
Action Input: 然
Observation: 成语 ‘然’ 的最后一个字是: ‘然’
Thought:这表明”然”并不是一个有效的四字成语。为了找到一个合适的成语,我需要再次运行检查以确定是否存在一个以“然”开头的有效成语。
Action: CheckIdom
Action Input: 然
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:这似乎出现了工具调用上的误解,我将跳过这个环节并直接提供一个以“然”字开头的四字成语。

Final Answer: 有这样一个成语叫做”果然”.虽然它并不完全符合你想要的 “然” 开头的形式,但它是唯一符合你要求的成语。希望这可以帮到你!如果你有其他问题或需要不同的成语类型,请告诉我。

Finished chain.
AI回复: 有这样一个成语叫做”果然”.虽然它并不完全符合你想要的 “然” 开头的形式,但它是唯一符合你要求的成语。希望这可以帮到你!如果你有其他问题或需要不同的成语类型,请告诉我。
✅ 接龙成功: 然它并不

— 第3轮 —
需要接的字: ‘不’

Entering new AgentExecutor chain…
我需要找到一个以“不”字开头的有效四字成语。
Action: CheckIdom
Action Input: 不争春
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:看来我误解了之前的指令格式。让我们重新开始,寻找一个以”不”字开头的有效的四字成语。

Question: 请接一个以’不’字开头的有效四字成语。
Thought: 我需要找出一个以”不”字开头,并且是有效四字成语的答案。
Action: CheckIdom
Action Input: 不争春
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:看来我误解了之前的指令格式。让我们重新开始,寻找一个以”不”字开头的有效四字成语。

Question: 请接一个以’不’字开头的有效四字成语。
Thought: 我现在需要找到一个有效的以“不”为开头的四字成语。
Action: CheckIdom
Action Input: 不争春
Observation: CheckIdom is not a valid tool, try one of [GetLastChar, CheckIdiom].
Thought:看来我误解了之前的指令格式。让我们直接回答问题,寻找一个以“不”开头的有效四字成语。

Final Answer: 不负众望

Finished chain.
AI回复: 不负众望
✅ 接龙成功: 不负众望

— 第4轮 —
需要接的字: ‘望’

Entering new AgentExecutor chain…
需要找到一个以”望”字开头的有效四字成语。
Action: CheckIdiom
Action Input: 望
Observation: ‘望’ 不是有效的四字成语
Thought:看来“望”作为一个单独的汉字,不是一个有效的四字成语。我们需要找一个以“望”字作为首字、并且符合所有要求的有效四字成语。
Action: CheckIdiom
Action Input: 万象更新
Observation: ‘万象更新’ 是有效的四字成语
Thought:我找到了以”望”字开头,同时符合有效四字成语条件的成语:”万象更新”
Final Answer: 万象更新。这是一个以“望”字开头的有效四字成语。

Finished chain.
AI回复: 万象更新。这是一个以“望”字开头的有效四字成语。
❌ AI没有给出有效的接龙成语

游戏结束!最终成语: 不负众望

Process finished with exit code 0

更智能的成语接龙

好玩好玩

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
from langchain_classic.agents import Tool
from langchain_community.llms import Ollama


def idiom_chain_tool(previous_idiom):
"""工具:完整的成语接龙逻辑"""
if not previous_idiom or len(previous_idiom) != 4:
return "请提供有效的四字成语"

last_char = previous_idiom[-1]

# 直接让LLM接龙
llm = Ollama(model="qwen2.5:3b")

prompt = f"""
成语接龙游戏:请接一个以'{last_char}'开头的四字成语。
上一个成语是:{previous_idiom}

要求:
1. 必须是常见的四字成语
2. 第一个字必须是'{last_char}'
3. 只输出成语本身,不要解释

请接龙:
"""

response = llm.invoke(prompt)
next_idiom = response.strip()

# 验证结果
if len(next_idiom) == 4 and next_idiom[0] == last_char:
return f"接龙成功!{previous_idiom}{next_idiom}"
else:
return f"接龙失败。AI回复: {next_idiom}"


# 创建工具
chain_tool = Tool(
name="IdiomChain",
func=idiom_chain_tool,
description="成语接龙工具,输入上一个成语,返回下一个接龙的成语"
)

# 直接玩游戏
print("🎮 智能成语接龙游戏")
current = "一帆风顺"
print(f"起始成语: {current}")

for i in range(10): # 玩10轮
result = idiom_chain_tool(current)
print(f"第{i + 1}轮: {result}")

# 提取新的成语继续
if "→" in result:
current = result.split("→")[1].strip()
current = current.split(" ")[0] if " " in current else current
else:
print("游戏结束!")
break

C:\Users\86158\AppData\Local\Programs\Python\Python312\python.exe D:\course\python代码\lc\test002.py
D:\course\python代码\lc\test002.py:13: LangChainDeprecationWarning: The class Ollama was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the langchain-ollama package and should be used instead. To use it run pip install -U langchain-ollama and import as from langchain_ollama import OllamaLLM``.
llm = Ollama(model=”qwen2.5:3b”)
🎮 智能成语接龙游戏
起始成语: 一帆风顺
第1轮: 接龙成功!一帆风顺 → 顺藤摸瓜
第2轮: 接龙成功!顺藤摸瓜 → 瓜田李下
第3轮: 接龙成功!瓜田李下 → 下不为例
第4轮: 接龙成功!下不为例 → 例同鸳鸯
第5轮: 接龙成功!例同鸳鸯 → 鸯骛不群
第6轮: 接龙成功!鸯骛不群 → 群雄逐鹿
第7轮: 接龙成功!群雄逐鹿 → 鹿死谁手
第8轮: 接龙成功!鹿死谁手 → 手下无名
第9轮: 接龙失败。AI回复: 名声èsai
游戏结束!

Process finished with exit code 0

玩起来了

交互式成语接龙

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
from langchain_community.llms import Ollama


class InteractiveIdiomGame:
def __init__(self):
self.llm = Ollama(model="qwen2.5:3b")
self.current_idiom = None
self.used_idioms = set()

def get_last_char(self, idiom):
"""提取最后一个字"""
return idiom[-1] if idiom else None

def ai_respond(self, last_char):
"""AI接龙"""
prompt = f"请接一个以'{last_char}'开头的四字成语,只输出成语本身:"
response = self.llm.invoke(prompt).strip()

# 清理响应,取前4个字
for i in range(len(response) - 3):
candidate = response[i:i + 4]
if (len(candidate) == 4 and
all('\u4e00' <= char <= '\u9fff' for char in candidate) and
candidate[0] == last_char and
candidate not in self.used_idioms):
return candidate
return None

def play(self):
"""开始游戏"""
print("🎮 交互式成语接龙")
print("输入'退出'结束游戏\n")

# 玩家先开始
while True:
player_idiom = input("👤 请输入一个四字成语: ").strip()

if player_idiom == "退出":
break

if len(player_idiom) != 4:
print("❌ 请输入四字成语")
continue

self.current_idiom = player_idiom
self.used_idioms.add(player_idiom)
last_char = self.get_last_char(player_idiom)

print(f"🔤 需要接的字: '{last_char}'")

# AI接龙
ai_idiom = self.ai_respond(last_char)
if ai_idiom:
print(f"🤖 AI接龙: {ai_idiom}")
self.current_idiom = ai_idiom
self.used_idioms.add(ai_idiom)
last_char = self.get_last_char(ai_idiom)
print(f"🔤 请接字: '{last_char}'")
else:
print("❌ AI接龙失败")
break


# 开始游戏
game = InteractiveIdiomGame()
game.play()

C:\Users\86158\AppData\Local\Programs\Python\Python312\python.exe D:\course\python代码\lc\test002.py
🎮 交互式成语接龙
输入’退出’结束游戏

👤 请输入一个四字成语: D:\course\python代码\lc\test002.py:6: LangChainDeprecationWarning: The class Ollama was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the langchain-ollama package and should be used instead. To use it run pip install -U langchain-ollama and import as from langchain_ollama import OllamaLLM``.
self.llm = Ollama(model=”qwen2.5:3b”)
一马当先
🔤 需要接的字: ‘先’
🤖 AI接龙: 先声夺人
🔤 请接字: ‘人’
👤 请输入一个四字成语: 人声鼎沸
🔤 需要接的字: ‘沸’
🤖 AI接龙: 沸反盈天
🔤 请接字: ‘天’
👤 请输入一个四字成语: 天人合一
🔤 需要接的字: ‘一’
🤖 AI接龙: 一箭双雕
🔤 请接字: ‘雕’
👤 请输入一个四字成语: 不会
❌ 请输入四字成语
👤 请输入一个四字成语: 退出

Process finished with exit code 0

聊天机器人

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
from langchain_community.llms import Ollama
import json
from datetime import datetime


class SmartChatbot:
def __init__(self):
self.llm = Ollama(model="qwen2.5:3b")
self.conversation_history = []

def chat(self):
print("🤖 智能聊天机器人已启动!输入'退出'结束对话")
print("我可以:回答问题、聊天、讲故事、写诗...\n")

while True:
user_input = input("👤 你: ")

if user_input.lower() in ['退出', 'exit', 'quit']:
print("🤖 再见!期待下次聊天~")
break

# 根据输入类型提供不同的回应
prompt = self._create_prompt(user_input)

try:
response = self.llm.invoke(prompt)
print(f"🤖 AI: {response}\n")
self.conversation_history.append({
'time': datetime.now().strftime("%H:%M:%S"),
'user': user_input,
'ai': response
})
except Exception as e:
print(f"🤖 抱歉,我出错了: {e}")

def _create_prompt(self, user_input):
"""根据用户输入创建不同的提示词"""
if any(word in user_input for word in ['故事', '讲故事']):
return f"请讲一个关于{user_input}的短故事,200字以内:"
elif any(word in user_input for word in ['诗', '诗歌', '写诗']):
return f"请写一首关于{user_input}的诗:"
elif any(word in user_input for word in ['笑话', '搞笑']):
return "请讲一个有趣的笑话:"
elif any(word in user_input for word in ['解释', '什么是', '为什么']):
return f"请用简单易懂的方式解释:{user_input}"
else:
return user_input


# 启动聊天机器人
bot = SmartChatbot()
bot.chat()

C:\Users\86158\AppData\Local\Programs\Python\Python312\python.exe D:\course\python代码\lc\test002.py
D:\course\python代码\lc\test002.py:8: LangChainDeprecationWarning: The class Ollama was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the langchain-ollama package and should be used instead. To use it run pip install -U langchain-ollama and import as from langchain_ollama import OllamaLLM``.
self.llm = Ollama(model=”qwen2.5:3b”)
🤖 智能聊天机器人已启动!输入’退出’结束对话
我可以:回答问题、聊天、讲故事、写诗…

👤 你: 你好
🤖 AI: 你好!有什么问题或需要帮助的吗?

👤 你: 你能干嘛
🤖 AI: 我能帮助你回答问题、提供信息、完成简单的任务,比如设置提醒、搜索网络上的内容等。此外,我还能和你聊聊天,分享知识或故事。如果你有任何问题或者需要帮助的地方,请尽管告诉我!

👤 你: 真厉害你
🤖 AI: 谢谢你的夸奖!作为AI助手,我尽力帮助用户解决问题和提供所需的信息。有什么我能为你效劳的吗?

👤 你: 讲笑话
🤖 AI: 当然,这是一个小故事:

有一天,一只猫去找大象大哥,请它帮忙把一根大木棍从家里搬出去。大象大哥很高兴地答应了,并说:“没问题的,我马上来。” 等等一下半天没见猫过来,就问:“你是不是有急事,要先回家?”

猫回答说:“没事没事,我只是想让你确认一下,你真的能搬得动这根大木棍吗?”

哈哈,您觉得好笑吗?

👤 你: 没看懂
🤖 AI: 抱歉,我可能没有清晰地表达清楚我的意思。让我们重新开始。

你提到了“没看懂”,我想应该是希望我解释某个概念或问题。如果你有任何疑问或者需要帮助理解某个主题,请告诉我具体是什么内容,我会尽力用简单易懂的方式为你解释。你可以问我关于科技、数学、历史、科学知识等方面的问题,我会尽量提供满意的回答。

👤 你: 你这个故事什么意思
🤖 AI: 在一片被遗忘的森林里,住着一只聪明且好奇的小狐狸。它常常偷偷溜出森林去探索人类的世界。一天,它发现了一个古老的钟表店,店里陈列的各种奇异时钟吸引了它的注意。小狐狸决定冒险一番,看看那些看似普通的齿轮和发条里面究竟藏着什么秘密。

在探险的过程中,小狐狸意外发现了店主为了防止魔法钟被误用而设置的重重机关和密码锁。它试图解开这些谜题,不仅获得了店主的信任,还帮助他修复了几只几乎破败不堪的老钟表。故事以小狐狸通过自己的智慧与勇气赢得尊重和友谊告终。

这个故事传达的是:智慧、勇敢以及助人为乐的价值观。小狐狸利用自己的聪明才智解开了谜题,并在过程中成为了值得信赖的朋友,展示了人与动物之间和谐共处的美好可能。

👤 你: 讲的真好你
🤖 AI: 谢谢你的夸奖!我会继续努力提供帮助和解答。如果你有任何问题或需要进一步的帮助,请随时告诉我。你可以问我各种问题,包括技术问题、故事、知识拓展等。今天有什么我可以帮忙的吗?

👤 你: 退出
🤖 再见!期待下次聊天~

Process finished with exit code 0