笔记:面向开发者的提示工程课程(ChatGPT Prompt Engineering for Developers)

发布时间:2026/10/17 22:17:43

笔记:面向开发者的提示工程课程(ChatGPT Prompt Engineering for Developers) 提示工程关键原则提示词关键1.写清楚具体的说明2.给模型充足的思考时间3.清楚模型的限制以下样例均基于deepseek需要配置deepseek api key1.写清楚具体的说明1使用分隔符清楚地指示输入的不同部分import os import sys from pathlib import Path from dotenv import load_dotenv from openai import OpenAI if sys.platform win32: sys.stdout.reconfigure(encodingutf-8) # 从本文件所在目录读取 .env load_dotenv(Path(__file__).resolve().parent / .env) api_key os.getenv(DEEPSEEK_API_KEY) if not api_key: raise SystemExit( 未检测到 DEEPSEEK_API_KEY。请在同目录的 .env 里填入\n DEEPSEEK_API_KEY你的DeepSeek密钥 ) # DeepSeek 兼容 OpenAI SDK只需改 base_url 和模型名 client OpenAI( api_keyapi_key, base_urlhttps://api.deepseek.com, ) def get_completion(prompt, modeldeepseek-chat): messages [{role: user, content: prompt}] response client.chat.completions.create( modelmodel, messagesmessages, temperature0, # this is the degree of randomness of the models output ) return response.choices[0].message.content text f You should express what you want a model to do by \ providing instructions that are as clear and \ specific as you can possibly make them. \ This will guide the model towards the desired output, \ and reduce the chances of receiving irrelevant \ or incorrect responses. Dont confuse writing a \ clear prompt with writing a short prompt. \ In many cases, longer prompts provide more clarity \ and context for the model, which can lead to \ more detailed and relevant outputs. prompt f Summarize the text delimited by triple backticks \ into a single sentence. {text} response get_completion(prompt) print(response)得到输出Clear and specific instructions, even if longer, are essential for guiding a model to produce relevant and accurate outputs, as they provide the necessary context and reduce errors.2要求结构化的输出text f prompt f 输出三本书的名称和它的作者以及类型\ 用JSON格式四个关键词书籍号书名作者类型。 {text} response get_completion(prompt) print(response)得到输出json [ { 书籍号: 978-7-5334-1234-5, 书名: 百年孤独, 作者: 加西亚·马尔克斯, 类型: 魔幻现实主义文学 }, { 书籍号: 978-7-5447-5678-9, 书名: 三体, 作者: 刘慈欣, 类型: 科幻小说 }, { 书籍号: 978-7-5063-9012-3, 书名: 活着, 作者: 余华, 类型: 长篇小说 } ] 3要求模型先对条件进行检查当模型做出了假设要求模型先对假设做出校验。你还可以通过考虑边缘的潜在情况要求模型做出特殊化处理。4在要求模型完成任务之前提供已经完成的任务实例。2.给模型充足的思考时间1规定模型完成任务的步骤。text f In a charming village, siblings Jack and Jill set out on a quest to fetch water from a hilltop \ well. As they climbed, singing joyfully, misfortune struck-Jack tripped on a stone and tumbled \ down the hill, with Jill following suit. \ Though slightly battered, the pair returned home to \ comforting embraces. Despite the mishap, their adventurous spirits remained undimmed, and they continued exploring with delight. #example 1 prompt_1 f Perform the following actions: 1 - Summarize the following text delimited by triple \ backticks with 1 sentence. 2 - Translate the summary into French. 3 - List each name in the French summary. Output a json object that contains the following keys: french_summary, num_names. Separate your answers with line breaks. Text: {text} response get_completion(prompt_1) print(Completion for prompt 1:) print(response)输出Completion for prompt 1: 1 - In a charming village, siblings Jack and Jill set out to fetch water from a hilltop well, but after Jack tripped and tumbled down the hill with Jill following, they returned home battered yet undimmed in their adventurous spirits. 2 - Dans un charmant village, les frère et sœur Jack et Jill sont partis chercher de l’eau à un puits au sommet d’une colline, mais après que Jack a trébuché et dévalé la colline suivi de Jill, ils sont rentrés chez eux meurtris mais avec un esprit aventureux intact. 3 - Jack, Jill. json { french_summary: Dans un charmant village, les frère et sœur Jack et Jill sont partis chercher de l’eau à un puits au sommet d’une colline, mais après que Jack a trébuché et dévalé la colline suivi de Jill, ils sont rentrés chez eux meurtris mais avec un esprit aventureux intact., num_names: 2 } 2要求模型在得出结论前先得出自己的解决方案。3.了解模型限制1模型并不了解自己知识的边界因此它可能会捏造一些信息来进行回答这种现象被称之为“幻觉”。较为有效的解决方案1.要求模型用输入文本中的相关内容进行回答2.要求模型追溯到自己回答的源文件提示工程需要迭代迭代过程需要找出为什么指令不够清晰或者为什么它没有给模型足够的时间去思考让你改进想法改进提示。并且多次循环最后得到完美的结果。迭代过程1尝试一些方法2分析结果未提供你想要的内容的地方3澄清指令给予更多思考时间4使用一批示例优化提示词总结类应用#example prod_review Got this panda plush toy for my daughters birthday, \ who loves it and takes it everywhere. Its soft and \ super cute, and its face has a friendly look. Its \ a bit small for what I paid though. I think there \ might be other options that are bigger for the \ same price. It arrived a day earlier than expected, \ so I got to play with it myself before I gave it \ to her. prompt f Your task is to generate a short summary of a product \ review from an ecommerce site. Summarize the review below, delimited by triple backticks, in at most 30 words. Review: {prod_review} response get_completion(prompt) print(response) #resultThe panda plush is soft, cute, and loved \ #by the daughter, but its small for the price. \ #It arrived early, which was a bonus.1.可以使用模型生成简洁明了的总结2.可以针对特定对象生成业务中更适用于某个群体的摘要3.还可以摘出重要信息而不是仅仅进行总结推理类应用类似于提取标签提取名字理解文本感情诸如此类的事情。大语言模型很擅长提取特定的文本减轻了传统机器学习中“提炼数据集→进行机器学习→训练出特殊模型”的负担。只需要对模型进行特定的提示词处理。转换类应用1.翻译2.转换格式3.纠正翻译错误校准原文本和模型生成文本的差异扩展类应用1.让模型扮演助理并生成ai文本时让用户知道对话是由ai生成的非常重要2.使用temperature模型的探索程度或随机性变量temperat0时模型的可靠性越高构建一个自定义聊天机器人import os import sys from pathlib import Path from dotenv import load_dotenv from openai import OpenAI if sys.platform win32: sys.stdout.reconfigure(encodingutf-8) # 与 prompt_test 一致先读本目录 .env再读上级目录 .env _script_dir Path(__file__).resolve().parent load_dotenv(_script_dir / .env) load_dotenv(_script_dir.parent / .env) api_key os.getenv(DEEPSEEK_API_KEY) if not api_key: raise SystemExit( 未检测到 DEEPSEEK_API_KEY。请在 .env 里填入\n DEEPSEEK_API_KEY你的DeepSeek密钥 ) # DeepSeek 兼容 OpenAI SDK client OpenAI( api_keyapi_key, base_urlhttps://api.deepseek.com, ) DEFAULT_MODEL deepseek-chat def get_completion(prompt, modelDEFAULT_MODEL): 单条用户 prompt对应图片里的 get_completion。 messages [{role: user, content: prompt}] response client.chat.completions.create( modelmodel, messagesmessages, temperature0, # this is the degree of randomness of the models output ) return response.choices[0].message.content def get_completion_from_messages(messages, modelDEFAULT_MODEL, temperature0): response client.chat.completions.create( modelmodel, messagesmessages, temperaturetemperature, ) return response.choices[0].message.content def chat_loop( system_prompt: str You are a helpful assistant., model: str DEFAULT_MODEL, temperature: float 0.7, ): 交互式聊天维护 messages 历史循环读取用户输入。 messages [{role: system, content: system_prompt}] print(DeepSeek 聊天机器人已启动。输入 quit / exit / q 退出。) print(- * 40) while True: user_input input(你: ).strip() if not user_input: continue if user_input.lower() in {quit, exit, q}: print(再见) break messages.append({role: user, content: user_input}) response get_completion_from_messages( messages, modelmodel, temperaturetemperature ) messages.append({role: assistant, content: response}) print(fAI: {response}\n) if __name__ __main__: chat_loop()
延伸阅读

更多相关文章

2026/10/16 22:12:50

【python】条件语句

if语法单分支语法if 条件:条件成立执行的代码1条件成立执行的代码2......要点说明a)if后面跟条件表达式,末尾必须加冒号 : ,冒号代表代码块开始。b)冒号下方的代码,必须缩进(一般 4 个空格)&…

2026/10/17 22:16:34

线性代数教材实战指南:从矩阵消元到SVD的MATLAB避坑路线

简介:这份资源是《Linear Algebra with Applications》第十版的全球版电子书,由 Steven J. Leon 与 Lisette de Pillis 合著,Pearson 出版,面向高校数学、工程、计算机等专业修读线性代数课程的学生与教师,也适合需要系…

2026/10/17 22:16:34

RETOUCH数据集排行榜深度解析:OCT视网膜液体分割技术指南

1. 从一张排行榜说起:RETOUCH数据集到底在比什么第一次接触RETOUCH数据集排行榜的人,多半会有点懵——榜单上密密麻麻的指标、各种缩写、不同赛道的排名,看起来像是某个小众圈子的内部游戏。但如果你做过眼底OCT图像的层分割,或者…

2026/10/17 22:16:34

自制编程语言环境搭建实战:工具链安装与排错指南

简介:面向编程语言爱好者与入门学习者,这份 PDF 资料系统梳理自制编程语言的核心概念,涵盖语言设计原则、语法语义定义、编译器与解释器实现,以及基于 yacc/lex、bison/flex 和 MinGW 的构建方法。书中结合 Crowbar、Diksam 两个实…

2026/10/17 22:16:34

图像旋转与畸变矫正:双线性与双三次插值原理及C++实现

1. 从像素到几何:图像扭曲旋转的底层逻辑图像旋转这件事,表面上看就是把一张图转个角度,但真正动手写过的人都知道,这里面藏着一堆让人头疼的细节。最直观的问题就是:旋转之后的像素点,坐标往往落在原图两个…

2026/10/17 22:16:34

Java解密报错BadPaddingException:原因、解决与排查指南

“Given final block not properly padded”,看到这行报错,做过Java加解密的同行一定不陌生。这个异常属于javax.crypto.BadPaddingException,几乎九成出现在DES或AES的对称解密环节,剩下的一成出现在你尝试去解别人的密文时。我第…

2026/10/17 22:11:33

数据中心智能化运维:从监控指标采集到告警降噪的落地实践

简介:一份围绕数据中心智能化运维的DOCX文档,面向数据中心运维工程师、IT管理人员及系统学习者,系统梳理智能化运维的核心策略。内容涵盖智能化设备管理、资源调度、任务分配、监控报警四类关键手段,既说明借助传感器、物联网与人…

2026/10/16 5:33:43

Python调用Gemini Structured Outputs实现工单路由门禁

客服工单最怕的不是模型“答错一句话”,而是它给出一段看起来合理的说明,程序却从中猜错优先级。通俗做法是:要求模型只交 JSON(JavaScript Object Notation,轻量数据格式),再让代码验证它。Gem…

2026/10/16 4:03:48

Spring Boot超市进销存系统毕设实战:从需求拆解到答辩通关

最近带的一个学生项目组里,有A同学跑来问我:选什么毕设题目最稳妥,既能让评审老师觉得工作量够,又不会在答辩时被问到语无伦次。我第一反应就是推荐基于Spring Boot的超市仓库管理系统——也就是超市进销存系统。这个题目乍一看平…

2026/10/17 14:20:58

Flutter StatefulWidget 生命周期核心解析

很多刚开始接触 Flutter 的朋友,在看完一堆“Hello World”和基础组件之后,大概率都会撞上同一堵墙:StatefulWidget 里那堆 initState、build、dispose 方法,到底什么时候被调用?为什么顺序是那样?在里面到…

2026/10/17 0:04:32

PlanarSLAM:面向曼哈顿世界的点线面联合SLAM系统

简介:本资源是面向机器人视觉与SLAM研究者的C开源RGB-D SLAM系统实现,专为结构化室内场景(如办公室、走廊)设计,通过融合点、线、平面三类几何特征并引入“曼哈顿世界”假设,显著提升位姿跟踪鲁棒性与稠密地…

2026/10/17 0:04:32

TDH Workflow调度实战:从DAG依赖驱动到任务编排与故障排查

1. 从一个调度脚本说起:TDH Workflow到底在解决什么问题第一次接触TDH的Workflow,是在一个数据清洗项目里。当时团队每天要跑几十个ETL任务,任务之间有严格的先后依赖——A表清洗完才能跑B表的关联,B表跑完才能触发C表的聚合。最开…

还想了解更多?直接咨询顾问

免费诊断 + 免费方案 + 透明报价。

全国咨询热线400-8866-253
免费获取方案
☎咨询二维码 ☎ ↑