github star gitee star atomgit star PyPI Downloads AI编程 AI交流群

大家好,这里是程序员晚枫,正在all in AI编程实战

第14讲:Prompt工程——写出高质量的AI提示词

为什么Prompt这么重要?

同样的AI模型,不同的提示词,效果天差地别。

1、Prompt的5个核心要素

要素说明示例
角色让AI扮演谁你是一位Python教师
任务要AI做什么写一篇入门教程
背景上下文信息面向零基础小白
格式输出要求Markdown格式,含代码块
约束限制条件字数800字,不用专业术语

2、角色设定技巧

1
2
3
4
5
6
7
system_prompt = """你是一位经验丰富的Python编程老师,名叫"程序员晚枫"。

你的教学风格:
- 通俗易懂,用生活比喻解释编程概念
- 循序渐进,从简单到复杂
- 多用代码示例,少用理论
"""

3、Few-shot:给AI举例

1
2
3
4
5
6
7
8
messages = [
{"role": "system", "content": "你是Python老师"},
{"role": "user", "content": "什么是变量?"},
{"role": "assistant", "content": "变量就像一个盒子,可以装东西。"},
{"role": "user", "content": "什么是函数?"},
{"role": "assistant", "content": "函数就像一个菜谱,写好步骤,需要时直接调用。"},
{"role": "user", "content": "什么是循环?"}
]

4、结构化输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
prompt = """请分析以下文本的情感,以JSON格式输出:
{
"sentiment": "positive/negative/neutral",
"confidence": 0.0-1.0,
"keywords": ["关键词1", "关键词2"]
}

文本:这个产品真的太棒了,强烈推荐!"""

response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}],
temperature=0
)

5、思维链(Chain of Thought)

1
2
3
4
5
6
7
8
prompt = """请一步一步思考以下问题:

一个商店,进货价50元,售价80元,每天卖出30件。

请按以下步骤计算:
1. 每天毛利润
2. 每天净利润
"""

6、实战:构建一个文本分析工具

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
from openai import OpenAI
import json

client = OpenAI(api_key="你的Key", base_url="https://api.deepseek.com")

def analyze_text(text):
prompt = f"""分析以下文本,以JSON格式返回:
{{
"sentiment": "positive/negative/neutral",
"confidence": 0.0到1.0,
"keywords": ["关键词1", "关键词2"],
"summary": "一句话总结"
}}
文本:{text}"""

response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
return json.loads(response.choices[0].message.content)

result = analyze_text("Python太好用了,我学了一周就能写自动化脚本!")
print(f"情感:{result['sentiment']}")
print(f"关键词:{result['keywords']}")

7、常见问题

Q:AI总是输出格式不对?
A:在prompt里明确写出格式示例,temperature设为0。

Q:回答太长/太短?
A:明确指定字数或条数。

下讲预告

学会了Prompt工程,下一讲我们学 RAG入门——让AI读取你的文档。

敬请期待!


程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

前3讲可以试听,试听链接:https://www.bilibili.com/cheese/play/ss982042944