第五章: ChatGPT高级技巧与API应用
本章深入探讨API集成、自动化工作流、Prompt优化策略等高级主题,以及10个高级应用案例。
技巧1: API集成与自动化
OpenAI API基础
import openai
openai.api_key = "YOUR_API_KEY"
# 基础调用
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "你是一位专业的Python导师"},
{"role": "user", "content": "解释装饰器"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)
参数详解
| 参数 | 说明 | 推荐值 | 影响 |
|---|---|---|---|
| model | 模型版本 | gpt-4/gpt-3.5-turbo | 质量vs成本 |
| temperature | 随机性 | 0.7 | 创造性vs确定性 |
| max_tokens | 最大输出 | 1000-2000 | 输出长度vs成本 |
| top_p | 核采样 | 0.9 | 多样性控制 |
| frequency_penalty | 重复惩罚 | 0-0.5 | 避免重复 |
| presence_penalty | 主题惩罚 | 0-0.5 | 话题多样性 |
流式输出(Stream)
def stream_chat(prompt):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
stream=True # 启用流式输出
)
for chunk in response:
if chunk.choices[0].delta.get("content"):
print(chunk.choices[0].delta.content, end="")
使用场景: 实时聊天,提升用户体验
Function Calling(函数调用)
# 定义函数
functions = [
{
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如北京"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["city"]
}
}
]
# 调用
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
functions=functions,
function_call="auto"
)
# 处理函数调用
if response.choices[0].message.get("function_call"):
function_name = response.choices[0].message.function_call.name
arguments = json.loads(response.choices[0].message.function_call.arguments)
# 调用实际函数
result = get_weather(arguments["city"])
# 将结果返回给GPT
second_response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": "北京今天天气怎么样?"},
response.choices[0].message,
{"role": "function", "name": function_name, "content": str(result)}
]
)
应用场景:
- 查询数据库
- 调用第三方API
- 执行计算任务
- 操作文件系统
技巧2: Prompt优化策略
A/B测试框架
def ab_test_prompt(prompt_a, prompt_b, test_cases, model="gpt-4"):
"""
对比两个Prompt的效果
"""
results = {"A": [], "B": []}
for case in test_cases:
# 测试Prompt A
response_a = call_gpt(prompt_a.format(**case), model)
results["A"].append({
"input": case,
"output": response_a,
"score": evaluate(response_a, case["expected"])
})
# 测试Prompt B
response_b = call_gpt(prompt_b.format(**case), model)
results["B"].append({
"input": case,
"output": response_b,
"score": evaluate(response_b, case["expected"])
})
# 统计结果
avg_score_a = sum(r["score"] for r in results["A"]) / len(results["A"])
avg_score_b = sum(r["score"] for r in results["B"]) / len(results["B"])
return {
"winner": "A" if avg_score_a > avg_score_b else "B",
"scores": {"A": avg_score_a, "B": avg_score_b},
"details": results
}
# 使用示例
prompt_a = "请总结以下文本: {text}"
prompt_b = """请用3个要点总结以下文本,每个要点不超过30字:
{text}
输出格式:
1. 【要点1】
2. 【要点2】
3. 【要点3】"""
test_cases = [
{"text": "...", "expected": "..."},
{"text": "...", "expected": "..."},
]
result = ab_test_prompt(prompt_a, prompt_b, test_cases)
print(f"Winner: Prompt {result['winner']}")
Prompt版本管理
class PromptTemplate:
def __init__(self, name, version):
self.name = name
self.version = version
self.template = ""
self.variables = []
self.examples = []
self.performance_metrics = {}
def set_template(self, template):
self.template = template
# 自动提取变量
self.variables = re.findall(r'\{(\w+)\}', template)
return self
def add_example(self, input_vars, expected_output):
self.examples.append({
"input": input_vars,
"expected": expected_output
})
return self
def render(self, **kwargs):
# 验证所有必需变量都提供了
missing = set(self.variables) - set(kwargs.keys())
if missing:
raise ValueError(f"Missing variables: {missing}")
return self.template.format(**kwargs)
def test(self, model="gpt-4"):
"""使用示例测试Prompt"""
results = []
for example in self.examples:
prompt = self.render(**example["input"])
output = call_gpt(prompt, model)
score = evaluate(output, example["expected"])
results.append(score)
self.performance_metrics = {
"avg_score": sum(results) / len(results),
"tested_at": datetime.now(),
"model": model
}
return self.performance_metrics
def save(self, path):
"""保存Prompt模板"""
with open(path, 'w') as f:
json.dump(self.__dict__, f, indent=2, default=str)
@classmethod
def load(cls, path):
"""加载Prompt模板"""
with open(path) as f:
data = json.load(f)
template = cls(data["name"], data["version"])
template.__dict__.update(data)
return template
# 使用示例
template = PromptTemplate("文章总结", "v1.0")
template.set_template("""
请总结以下{type}文章,字数控制在{word_count}字:
{content}
要求:
- 提炼{num_points}个核心观点
- 保留关键数据和案例
""")
template.add_example(
input_vars={"type": "科技", "word_count": 200, "content": "...", "num_points": 3},
expected_output="..."
)
# 测试
metrics = template.test()
print(f"平均得分: {metrics['avg_score']}")
# 保存
template.save("prompts/article_summary_v1.json")
技巧3: Token管理与成本优化
Token计算
import tiktoken
def count_tokens(text, model="gpt-4"):
"""准确计算Token数"""
encoding = tiktoken.encoding_for_model(model)
tokens = encoding.encode(text)
return len(tokens)
# 中文大约1个汉字=1.5-2个tokens
text = "ChatGPT是一个强大的AI助手"
tokens = count_tokens(text)
print(f"文本: {text}")
print(f"Token数: {tokens}") # 约15-20个tokens
成本估算
# 2024年OpenAI价格(示例)
PRICING = {
"gpt-4": {
"input": 0.03 / 1000, # $0.03 per 1K tokens
"output": 0.06 / 1000 # $0.06 per 1K tokens
},
"gpt-3.5-turbo": {
"input": 0.0015 / 1000,
"output": 0.002 / 1000
}
}
def estimate_cost(prompt, expected_output_tokens, model="gpt-4"):
"""估算单次调用成本"""
input_tokens = count_tokens(prompt, model)
output_tokens = expected_output_tokens
cost = (
input_tokens * PRICING[model]["input"] +
output_tokens * PRICING[model]["output"]
)
return {
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"total_tokens": input_tokens + output_tokens,
"cost_usd": cost,
"cost_cny": cost * 7.2 # 假设汇率7.2
}
# 使用示例
prompt = "请写一篇2000字的文章..."
cost = estimate_cost(prompt, expected_output_tokens=1500, model="gpt-4")
print(f"预估成本: ¥{cost['cost_cny']:.4f}")
成本优化技巧
1. Prompt压缩
def compress_prompt(prompt):
"""压缩Prompt,减少Token"""
# 移除多余空格和换行
prompt = re.sub(r'\s+', ' ', prompt).strip()
# 使用缩写
abbreviations = {
"你是一位": "你是",
"请帮我": "请",
"以下内容": "下文",
}
for old, new in abbreviations.items():
prompt = prompt.replace(old, new)
return prompt
2. 分段处理
def process_long_text(text, chunk_size=2000):
"""将长文本分段处理"""
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
results = []
for chunk in chunks:
result = call_gpt(f"总结: {chunk}", model="gpt-3.5-turbo")
results.append(result)
# 最后汇总
summary = call_gpt(f"综合以下总结:\n\n" + "\n".join(results))
return summary
3. 缓存机制
import hashlib
import json
from functools import lru_cache
class GPTCache:
def __init__(self, cache_file="gpt_cache.json"):
self.cache_file = cache_file
self.cache = self.load_cache()
def load_cache(self):
try:
with open(self.cache_file) as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_cache(self):
with open(self.cache_file, 'w') as f:
json.dump(self.cache, f)
def get_cache_key(self, prompt, model, temperature):
"""生成缓存key"""
data = f"{prompt}{model}{temperature}"
return hashlib.md5(data.encode()).hexdigest()
def get(self, prompt, model, temperature):
key = self.get_cache_key(prompt, model, temperature)
return self.cache.get(key)
def set(self, prompt, model, temperature, response):
key = self.get_cache_key(prompt, model, temperature)
self.cache[key] = {
"response": response,
"cached_at": datetime.now().isoformat()
}
self.save_cache()
# 使用
cache = GPTCache()
def call_gpt_with_cache(prompt, model="gpt-4", temperature=0.7):
# 先查缓存
cached = cache.get(prompt, model, temperature)
if cached:
print("从缓存返回")
return cached["response"]
# 调用API
response = openai.ChatCompletion.create(...)
result = response.choices[0].message.content
# 缓存结果
cache.set(prompt, model, temperature, result)
return result
技巧4: 批量处理与并发
批量处理框架
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def batch_process(prompts, model="gpt-4", max_workers=5):
"""异步批量处理"""
async def process_one(prompt):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: call_gpt(prompt, model)
)
tasks = [process_one(p) for p in prompts]
results = await asyncio.gather(*tasks)
return results
# 使用
prompts = [
"总结: 文章1",
"总结: 文章2",
"总结: 文章3",
]
results = asyncio.run(batch_process(prompts))
进度追踪
from tqdm import tqdm
def batch_process_with_progress(items, process_func, desc="Processing"):
"""带进度条的批处理"""
results = []
failed = []
for item in tqdm(items, desc=desc):
try:
result = process_func(item)
results.append({"item": item, "result": result, "status": "success"})
except Exception as e:
failed.append({"item": item, "error": str(e)})
print(f" 失败: {item[:50]}... 错误: {e}")
return {
"results": results,
"failed": failed,
"success_rate": len(results) / len(items) * 100
}
# 使用
def process_article(text):
return call_gpt(f"总结: {text}")
articles = [...] # 100篇文章
output = batch_process_with_progress(articles, process_article, "总结文章")
print(f"成功率: {output['success_rate']:.2f}%")
技巧5: Prompt调试技巧
调试框架
class PromptDebugger:
def __init__(self):
self.history = []
def debug(self, prompt, model="gpt-4", verbose=True):
"""调试Prompt"""
if verbose:
print("="*50)
print(" Prompt:")
print(prompt)
print("\n" + "="*50)
# Token统计
tokens = count_tokens(prompt, model)
if verbose:
print(f" Token数: {tokens}")
if tokens > 3000:
print("⚠️ Warning: Token数较多,可能影响性能和成本")
# 调用API
start_time = time.time()
response = call_gpt(prompt, model)
elapsed = time.time() - start_time
if verbose:
print(f"⏱️ 耗时: {elapsed:.2f}秒")
print("\n" + "="*50)
print("💬 Response:")
print(response)
print("="*50 + "\n")
# 记录历史
self.history.append({
"prompt": prompt,
"response": response,
"tokens": tokens,
"elapsed": elapsed,
"timestamp": datetime.now()
})
return response
def show_stats(self):
"""显示统计信息"""
total_tokens = sum(h["tokens"] for h in self.history)
total_time = sum(h["elapsed"] for h in self.history)
avg_tokens = total_tokens / len(self.history)
avg_time = total_time / len(self.history)
print(f"""
调试统计:
- 总调用次数: {len(self.history)}
- 总Token数: {total_tokens}
- 总耗时: {total_time:.2f}秒
- 平均Token数: {avg_tokens:.0f}
- 平均耗时: {avg_time:.2f}秒
""")
# 使用
debugger = PromptDebugger()
result = debugger.debug("请解释量子计算")
debugger.show_stats()
10个高级应用案例
案例1: 自动化内容审核系统
def content_moderation(text):
prompt = f"""
请审核以下内容是否违规:
内容: {text}
审核维度:
1. 政治敏感 (0-10分)
2. 色情低俗 (0-10分)
3. 暴力血腥 (0-10分)
4. 谣言虚假 (0-10分)
5. 广告营销 (0-10分)
输出JSON:
{{
"scores": {{"政治": X, "色情": Y, ...}},
"overall_risk": "低/中/高",
"is_违规": true/false,
"reason": "具体原因"
}}
只输出JSON,不要其他文字。
"""
response = call_gpt(prompt, temperature=0.2) # 低温度保证稳定性
return json.loads(response)
案例2: 智能客服机器人
class CustomerServiceBot:
def __init__(self):
self.conversation_history = []
self.knowledge_base = load_kb()
def chat(self, user_message):
# 添加到历史
self.conversation_history.append({
"role": "user",
"content": user_message
})
# 检索知识库
relevant_docs = self.knowledge_base.search(user_message, top_k=3)
context = "\n".join([doc["content"] for doc in relevant_docs])
# 构建Prompt
system_prompt = f"""
你是专业客服,根据以下知识库回答用户问题:
【知识库】
{context}
回答要求:
1. 准确引用知识库内容
2. 如果知识库没有,诚实说"需要转人工"
3. 语气友好,逻辑清晰
4. 给出具体解决方案
"""
messages = [{"role": "system", "content": system_prompt}] + \
self.conversation_history[-10:] # 保留最近10轮对话
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages
)
answer = response.choices[0].message.content
# 添加到历史
self.conversation_history.append({
"role": "assistant",
"content": answer
})
return answer
案例3-10简要列举
3. 代码审查自动化: 自动检测代码问题,生成审查报告 4. 文档自动生成: 根据代码生成API文档,注释 5. 数据分析助手: 自动分析数据,生成可视化建议 6. 邮件自动回复: 根据邮件内容智能生成回复 7. 知识图谱构建: 从文本提取实体关系 8. 多语言翻译: 批量翻译,保持格式 9. SEO优化工具: 生成标题,关键词,描述 10. 个性化推荐: 根据用户画像生成推荐内容
最佳实践总结
DO(应该做的)
- 明确目标: 每个Prompt都有清晰的目标
- 结构化输入: 使用明确的格式和分隔符
- 版本管理: 记录Prompt版本和性能
- A/B测试: 对比不同Prompt的效果
- 错误处理: 完善的异常捕获和重试机制
- 成本监控: 实时追踪Token消耗和费用
- 缓存机制: 避免重复调用相同内容
- 批量处理: 提高处理效率
- 日志记录: 记录所有调用用于审计
- 用户反馈: 收集真实用户反馈优化
DON'T(不应该做的)
- 过度复杂: Prompt不是越长越好
- 忽略成本: 不计成本地使用GPT-4
- 缺乏测试: 直接上线未经测试的Prompt
- 硬编码: 将Prompt写死在代码里
- 忽略安全: 直接传递用户输入,可能被注入攻击
- 同步阻塞: 批量任务用同步方式处理
- 无监控: 不监控API调用情况
- 重复造轮子: 不复用已验证的Prompt
学习资源
官方资源
- OpenAI API文档: https://platform.openai.com/docs
- Prompt Engineering Guide: https://platform.openai.com/docs/guides/prompt-engineering
- OpenAI Cookbook: https://github.com/openai/openai-cookbook
社区资源
- Awesome ChatGPT Prompts: https://github.com/f/awesome-chatgpt-prompts
- LangChain: https://python.langchain.com
- Prompt Hub: https://prompthero.com
工具推荐
- Token计算器: https://platform.openai.com/tokenizer
- Prompt测试平台: OpenAI Playground
- 成本计算器: OpenAI Pricing Calculator
课程总结
恭喜你完成ChatGPT提示词工程完全指南!
你已经掌握:
- Prompt Engineering核心概念(第1章)
- 20个基础技巧和模板(第2章)
- 30个进阶技巧和Few-Shot/CoT(第3章)
- 40个实战场景应用(第4章)
- API集成和高级优化(第5章)
总计学习内容:
- 100+ 可复制的Prompt模板
- 10+ 高级应用案例
- 5大核心技巧
- 40+ 实战场景
下一步建议:
实践路径:
- 选择5个与工作最相关的模板
- 实际使用1周,记录效果
- 根据反馈优化调整
- 建立个人Prompt模板库
- 分享给团队,建立团队标准
进阶方向:
- 学习LangChain框架
- 探索Agent开发
- 研究RAG(检索增强生成)
- 尝试Fine-tuning微调
- 开发AI应用
结语
Prompt Engineering不是一门"背模板"的技术,而是一种与AI对话的思维方式。
核心理念:
- 明确性: 清晰表达你的需求
- 🔄 迭代性: 不断优化改进
- 数据驱动: 用测试验证效果
- 🤝 协作性: AI是助手,不是替代
记住: 最好的Prompt是在实战中不断打磨出来的!
开始行动吧,用AI提升10倍生产力!
感谢学习!如有问题,欢迎交流!
📧 联系方式: [你的邮箱] GitHub: [项目地址] 💬 社群: [交流群]