LLM智能體類型全景圖譜:從基礎工具到自主決策的進化之路 原創
本文對LLM智能體(也稱“智能體”)進行系統分類,分析各種類型的智能體基于任務處理方式的差異,如推理、工具調用、多智能體協作等。
簡介
每個成功的AI智能體的核心都在于一項基本技能:提示詞(或“提示詞工程”)。這是一種通過精心設計輸入文本來指導LLM執行任務的方法。
提示詞工程是首批文本到文本NLP模型(2018年)輸入的演變。當時,開發人員通常更專注于建模和特征工程。在大型GPT模型(2022年)創建之后,我們開始主要使用預訓練工具,因此重點轉移到了輸入格式上。因此,“提示詞工程”學科應運而生。如今(2025年),隨著NLP逐漸模糊代碼和即時之間的界限,它已發展成為一門藝術與科學的融合。
不同類型的提示詞技巧會創造出不同類型的智能體。每種方法都會增強一項特定的技能:邏輯、計劃、記憶、準確性和工具的整合。讓我們通過一個非常簡單的例子來了解所有這些技巧。
## 模型搭建準備
import ollama
llm = "qwen2.5"
## 提問
q = "What is 30 multiplied by 10?"
主要技術
1.“常規”提示詞——只需提出一個問題,即可獲得直接的答案
也稱為“零樣本”提示詞,具體指模型在沒有任何先前樣本的情況下被賦予任務的情況。這種基本技術專為單步執行任務的智能體設計,尤其是在早期模型中,這類智能體無需中間推理即可執行任務。
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q}
])
print(response['message']['content'])
2.ReAct(Reason+Act)——推理與行動的結合
該模型不僅會思考問題,還會根據推理采取行動。因此,隨著模型在推理步驟和行動之間交替,并不斷迭代改進其方法,其交互性更強。本質上,它是一個“思考-行動-觀察”的循環。它用于更復雜的任務,例如搜索網頁并根據結果做出決策,通常設計用于多步驟智能體,這些智能體執行一系列推理步驟和行動以得出最終結果。它們可以將復雜的任務分解成更小、更易于管理的部分,并逐步構建彼此。
就我個人而言,我非常喜歡ReAct Agents,因為我發現它們更類似于人類,因為它們像我們一樣“四處游蕩并發現新事物”。
prompt = '''
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Action:', and 'Observation:' sequences.
At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use.
Then in the 'Action:' sequence, you shold use one of your tools.
During each intermediate step, you can use 'Observation:' field to save whatever important information you will use as input for the next step.
'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q+" "+prompt}
])
print(response['message']['content'])
3.思維鏈(CoT)
這是一種推理模式,涉及生成得出結論的過程。該模型通過明確列出通向最終答案的邏輯步驟,迫使其“大聲思考”。本質上,它是一個沒有反饋的計劃。CoT最常用于高級任務,例如解決可能需要逐步推理的數學問題,通常為多步驟智能體設計。
prompt = '''Let’s think step by step.'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q+" "+prompt}
])
print(response['message']['content'])
CoT擴展
從上面的技術鏈中又衍生出其他幾種新的提示方法。
4.反思提示
這是在初始CoT推理的基礎上增加一個迭代自我檢查或自我糾正階段,其中模型審查和批評自己的輸出(發現錯誤、識別差距、提出改進建議)。
cot_answer = response['message']['content']
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content': f'''Here was your original answer:\n\n{cot_answer}\n\n
Now reflect on whether it was correct or if it was the best approach.
If not, correct your reasoning and answer.'''}
])
print(response['message']['content'])
5.思想樹(ToT)
通過這種方法,可以將CoT概括為一棵樹,同時還要探索多個推理鏈。
num_branches = 3
prompt = f'''
You will think of multiple reasoning paths (thought branches). For each path, write your reasoning and final answer.
After exploring {num_branches} different thoughts, pick the best final answer and explain why.
'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content': f"Task: {q} \n{prompt}"}
])
print(response['message']['content'])
6.思維圖(GoT)
基于這種方法,可以將CoT概括為一張圖表,同時還要考慮相互連接的分支。
class GoT:
def __init__(self, question):
self.question = question
self.nodes = {} # node_id: text
self.edges = [] # (from_node, to_node, relation)
self.counter = 1
def add_node(self, text):
node_id = f"Thought{self.counter}"
self.nodes[node_id] = text
self.counter += 1
return node_id
def add_edge(self, from_node, to_node, relation):
self.edges.append((from_node, to_node, relation))
def show(self):
print("\n--- Current Thoughts ---")
for node_id, text in self.nodes.items():
print(f"{node_id}: {text}\n")
print("--- Connections ---")
for f, t, r in self.edges:
print(f"{f} --[{r}]--> {t}")
print("\n")
def expand_thought(self, node_id):
prompt = f"""
You are reasoning about the task: {self.question}
Here is a previous thought node ({node_id}):\"\"\"{self.nodes[node_id]}\"\"\"
Please provide a refinement, an alternative viewpoint, or a related thought that connects to this node.
Label your new thought clearly, and explain its relation to the previous one.
"""
response = ollama.chat(model=llm, messages=[{'role':'user', 'content':prompt}])
return response['message']['content']
##開始構建圖
g = GoT(q)
## 獲取初始想法
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q}
])
n1 = g.add_node(response['message']['content'])
##通過一些改進來擴展最初的想法
refinements = 1
for _ in range(refinements):
expansion = g.expand_thought(n1)
n_new = g.add_node(expansion)
g.add_edge(n1, n_new, "expansion")
g.show()
## 最終答案輸出
prompt = f'''
Here are the reasoning thoughts so far:
{chr(10).join([f"{k}: {v}" for k,v in g.nodes.items()])}
Based on these, select the best reasoning and final answer for the task: {q}
Explain your choice.
'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q}
])
print(response['message']['content'])
7.思想程序(PoT)
這種方法專門用于編程領域,其中推理通過可執行代碼片段進行。
import re
def extract_python_code(text):
match = re.search(r"```python(.*?)```", text, re.DOTALL)
if match:
return match.group(1).strip()
return None
def sandbox_exec(code):
## 創建具有安全限制的最小沙盒
allowed_builtins = {'abs', 'min', 'max', 'pow', 'round'}
safe_globals = {k: __builtins__.__dict__[k] for k in allowed_builtins if k in __builtins__.__dict__}
safe_locals = {}
exec(code, safe_globals, safe_locals)
return safe_locals.get('result', None)
prompt = '''
Write a short Python program that calculates the answer and assigns it to a variable named 'result'.
Return only the code enclosed in triple backticks with 'python' (```python ... ```).
'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content': f"Task: {q} \n{prompt}"}
])
print(response['message']['content'])
sandbox_exec(code=extract_python_code(text=response['message']['content']))
結論
本文概述了人工智能智能體的所有主要提示詞技術。然而,并沒有單一的“最佳”提示詞技術,因為這很大程度上取決于任務本身和所需推理的復雜性。
例如,像總結和翻譯這樣的簡單任務,可以通過零次/常規提示詞輕松完成,而CoT模式則非常適合數學和邏輯任務。另一方面,帶有工具的智能體通常是使用ReAct模式創建的。此外,當需要從錯誤或迭代中學習以改進結果時,例如游戲,Reflexion模式最為合適。
就復雜任務的多功能性而言,PoT是真正的贏家,因為它完全基于代碼生成和執行。事實上,PoT智能體在多項辦公任務中正越來越接近取代人類。
我相信,在不久的將來,提示詞將不僅僅是“你對模型說什么”,而是在人類意圖、機器推理和外部動作之間構建一個交互循環。
有關本文中示例程序的完整源代碼,請見??GitHub地址??。?
譯者介紹
朱先忠,51CTO社區編輯,51CTO專家博客、講師,濰坊一所高校計算機教師,自由編程界老兵一枚。
原文標題:??Recap of all types of LLM Agents??,作者:Mauro Di Pietro
