ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

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

笔记:面向开发者的提示工程课程(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()
返回列表