提示工程关键原则:

提示词关键:1.写清楚具体的说明;2.给模型充足的思考时间;3.清楚模型的限制

以下样例均基于deepseek(需要配置deepseek api key)

1.写清楚具体的说明:

(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(encoding="utf-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_key=api_key,
    base_url="https://api.deepseek.com",
)


def get_completion(prompt, model="deepseek-chat"):
    messages = [{"role": "user", "content": prompt}]
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0,  # this is the degree of randomness of the model's 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. Don't 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 daughter's birthday, \
who loves it and takes it everywhere. It's soft and \
super cute, and its face has a friendly look. It's \
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)

#result:The panda plush is soft, cute, and loved \
#by the daughter, but it's small for the price. \
#It arrived early, which was a bonus.

1.可以使用模型生成简洁明了的总结;

2.可以针对特定对象生成业务中更适用于某个群体的摘要;

3.还可以摘出重要信息,而不是仅仅进行总结;

推理类应用:

类似于:提取标签,提取名字,理解文本感情,诸如此类的事情。

大语言模型很擅长提取特定的文本,减轻了传统机器学习中,“提炼数据集→进行机器学习→训练出特殊模型”的负担。只需要对模型进行特定的提示词处理。

转换类应用:

1.翻译

2.转换格式

3.纠正翻译错误,校准原文本和模型生成文本的差异

扩展类应用:

1.让模型扮演助理并生成ai文本时,让用户知道对话是由ai生成的,非常重要

2.使用temperature(模型的探索程度或随机性)变量,temperat=0时,模型的可靠性越高

构建一个自定义聊天机器人:

import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-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_key=api_key,
    base_url="https://api.deepseek.com",
)

DEFAULT_MODEL = "deepseek-chat"


def get_completion(prompt, model=DEFAULT_MODEL):
  """单条用户 prompt,对应图片里的 get_completion。"""
  messages = [{"role": "user", "content": prompt}]
  response = client.chat.completions.create(
      model=model,
      messages=messages,
      temperature=0,  # this is the degree of randomness of the model's output
  )
  return response.choices[0].message.content


def get_completion_from_messages(messages, model=DEFAULT_MODEL, temperature=0):
  response = client.chat.completions.create(
      model=model,
      messages=messages,
      temperature=temperature,
  )
  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, model=model, temperature=temperature
      )
      messages.append({"role": "assistant", "content": response})
      print(f"AI: {response}\n")


if __name__ == "__main__":
  chat_loop()

Logo

AtomGit AI 社区提供模型库、数据集、Agent、Token等资源

更多推荐