
譯者 | 朱先忠
審校 | 重樓
簡(jiǎn)介
每個(gè)成功的AI智能體的核心都在于一項(xiàng)基本技能:提示詞(或“提示詞工程”)。這是一種通過(guò)精心設(shè)計(jì)輸入文本來(lái)指導(dǎo)LLM執(zhí)行任務(wù)的方法。
提示詞工程是首批文本到文本NLP模型(2018年)輸入的演變。當(dāng)時(shí),開發(fā)人員通常更專注于建模和特征工程。在大型GPT模型(2022年)創(chuàng)建之后,我們開始主要使用預(yù)訓(xùn)練工具,因此重點(diǎn)轉(zhuǎn)移到了輸入格式上。因此,“提示詞工程”學(xué)科應(yīng)運(yùn)而生。如今(2025年),隨著NLP逐漸模糊代碼和即時(shí)之間的界限,它已發(fā)展成為一門藝術(shù)與科學(xué)的融合。
不同類型的提示詞技巧會(huì)創(chuàng)造出不同類型的智能體。每種方法都會(huì)增強(qiáng)一項(xiàng)特定的技能:邏輯、計(jì)劃、記憶、準(zhǔn)確性和工具的整合。讓我們通過(guò)一個(gè)非常簡(jiǎn)單的例子來(lái)了解所有這些技巧。
## 模型搭建準(zhǔn)備
import ollama
llm = "qwen2.5"
## 提問(wèn)
q = "What is 30 multiplied by 10?"主要技術(shù)
1.“常規(guī)”提示詞——只需提出一個(gè)問(wèn)題,即可獲得直接的答案
也稱為“零樣本”提示詞,具體指模型在沒有任何先前樣本的情況下被賦予任務(wù)的情況。這種基本技術(shù)專為單步執(zhí)行任務(wù)的智能體設(shè)計(jì),尤其是在早期模型中,這類智能體無(wú)需中間推理即可執(zhí)行任務(wù)。

response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q}
])
print(response['message']['content'])
2.ReAct(Reason+Act)——推理與行動(dòng)的結(jié)合
該模型不僅會(huì)思考問(wèn)題,還會(huì)根據(jù)推理采取行動(dòng)。因此,隨著模型在推理步驟和行動(dòng)之間交替,并不斷迭代改進(jìn)其方法,其交互性更強(qiáng)。本質(zhì)上,它是一個(gè)“思考-行動(dòng)-觀察”的循環(huán)。它用于更復(fù)雜的任務(wù),例如搜索網(wǎng)頁(yè)并根據(jù)結(jié)果做出決策,通常設(shè)計(jì)用于多步驟智能體,這些智能體執(zhí)行一系列推理步驟和行動(dòng)以得出最終結(jié)果。它們可以將復(fù)雜的任務(wù)分解成更小、更易于管理的部分,并逐步構(gòu)建彼此。
就我個(gè)人而言,我非常喜歡ReAct Agents,因?yàn)槲野l(fā)現(xiàn)它們更類似于人類,因?yàn)樗鼈兿裎覀円粯印八奶幱问幉l(fā)現(xiàn)新事物”。

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)
這是一種推理模式,涉及生成得出結(jié)論的過(guò)程。該模型通過(guò)明確列出通向最終答案的邏輯步驟,迫使其“大聲思考”。本質(zhì)上,它是一個(gè)沒有反饋的計(jì)劃。CoT最常用于高級(jí)任務(wù),例如解決可能需要逐步推理的數(shù)學(xué)問(wèn)題,通常為多步驟智能體設(shè)計(jì)。

prompt = '''Let’s think step by step.'''
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q+" "+prompt}
])
print(response['message']['content'])
CoT擴(kuò)展
從上面的技術(shù)鏈中又衍生出其他幾種新的提示方法。
4.反思提示
這是在初始CoT推理的基礎(chǔ)上增加一個(gè)迭代自我檢查或自我糾正階段,其中模型審查和批評(píng)自己的輸出(發(fā)現(xiàn)錯(cuò)誤、識(shí)別差距、提出改進(jìn)建議)。
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)
通過(guò)這種方法,可以將CoT概括為一棵樹,同時(shí)還要探索多個(gè)推理鏈。
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概括為一張圖表,同時(shí)還要考慮相互連接的分支。
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òu)建圖
g = GoT(q)
## 獲取初始想法
response = ollama.chat(model=llm, messages=[
{'role':'user', 'content':q}
])
n1 = g.add_node(response['message']['content'])
##通過(guò)一些改進(jìn)來(lái)擴(kuò)展最初的想法
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)
這種方法專門用于編程領(lǐng)域,其中推理通過(guò)可執(zhí)行代碼片段進(jìn)行。
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):
## 創(chuàng)建具有安全限制的最小沙盒
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']))結(jié)論
本文概述了人工智能智能體的所有主要提示詞技術(shù)。然而,并沒有單一的“最佳”提示詞技術(shù),因?yàn)檫@很大程度上取決于任務(wù)本身和所需推理的復(fù)雜性。
例如,像總結(jié)和翻譯這樣的簡(jiǎn)單任務(wù),可以通過(guò)零次/常規(guī)提示詞輕松完成,而CoT模式則非常適合數(shù)學(xué)和邏輯任務(wù)。另一方面,帶有工具的智能體通常是使用ReAct模式創(chuàng)建的。此外,當(dāng)需要從錯(cuò)誤或迭代中學(xué)習(xí)以改進(jìn)結(jié)果時(shí),例如游戲,Reflexion模式最為合適。
就復(fù)雜任務(wù)的多功能性而言,PoT是真正的贏家,因?yàn)樗耆诖a生成和執(zhí)行。事實(shí)上,PoT智能體在多項(xiàng)辦公任務(wù)中正越來(lái)越接近取代人類。
我相信,在不久的將來(lái),提示詞將不僅僅是“你對(duì)模型說(shuō)什么”,而是在人類意圖、機(jī)器推理和外部動(dòng)作之間構(gòu)建一個(gè)交互循環(huán)。
有關(guān)本文中示例程序的完整源代碼,請(qǐng)見GitHub地址。
譯者介紹
朱先忠,51CTO社區(qū)編輯,51CTO專家博客、講師,濰坊一所高校計(jì)算機(jī)教師,自由編程界老兵一枚。
原文標(biāo)題:Recap of all types of LLM Agents,作者:Mauro Di Pietro



































