【大模型】Query 改寫常見Prompt 模板

下面對常見的幾種“Query 改寫”Prompt 模板進行中英文對照,并在注釋中給出中文說明,幫助中國用戶快速理解與使用。


根據調研,企業級 Query 改寫模塊需要覆蓋多種常見場景,包括拼寫糾錯、中英混合、省略上下文、多義詞擴展、專業術語替換等,從而在 RAG 應用和大模型問答中都能保持高召回和高精度 。為了驗證您的改寫功能,下面提供 5 個涵蓋這些場景的典型測試 Query。

5 個驗證用 Query

  1. 拼寫錯誤 + 中英混合

    iphon14 pro 價錢
    • 測試拼寫糾錯(“iphon”→“iphone”)和中英混合分詞 。

  2. 省略上下文的代詞查詢

    它昨年營收多少
    • 測試上下文補全,將“它”還原為前文實體(如公司名) 。

  3. 中文行業術語替換

    聯想筆電多少錢
    • 測試本地詞典中“筆電”→“筆記本電腦”的同義詞擴展 。

  4. 多義詞消歧

    apple 更新日志
    • 測試“apple”歧義(品牌 vs. 水果)澄清與實體鏈接 。

  5. 復雜英語專業查詢

    best python web framework 性能 比較
    • 測試英文專有名詞識別+中文關鍵詞補全,以及模板改寫(補全“有哪些?”) 。

以上 5 個 Query 覆蓋了企業級改寫中的核心場景,適合作為流水線測試用例。


常見提示詞工程?


1. 簡潔零樣本重寫(Zero-Shot)

// 英文原版
Rewrite the following query to improve its performance and recall:
// 中文翻譯
將以下查詢重寫,以提高其檢索性能和召回率:
// 用法說明
//   直接提示模型對用戶原始查詢進行端到端重寫,適合零樣本場景。 :contentReference[oaicite:0]{index=0}


2. 前綴式調用(Prefix Prompt)

# 英文原版
prompt_calibrated = "query reformulation: " + user_query
# 中文翻譯
prompt_calibrated = "query 改寫: " + user_query
# 用法說明
#   在 Hugging Face 上的 query-reformulation 模型中常見,直接在查詢前加固定前綴。 :contentReference[oaicite:1]{index=1}

import os
import openai
import json# 環境變量中設置 OPENAI_API_KEY
openai.api_key = os.getenv("OPENAI_API_KEY")# ① 待改寫的查詢列表
queries = ["iphon14 pro 價錢","它昨年營收多少","聯想筆電多少錢","apple 更新日志","best python web framework 性能 比較"
]# ② 將列表拼接為多行 Prompt
#    使用 join + 列表推導,每一項前面加 "- "
queries_block = "\n".join(f"- {q}" for q in queries)# ③ 構造完整 Prompt,示例格式引導模型輸出 JSON 數組
prompt_str1="重寫以下查詢,使其更完整、更易檢索:"
prompt_str="Rewrite the following query to make it more complete and easier to retrieve:"
prompt = f"""
{prompt_str}\n
{queries_block}請**只**返回一個 JSON 數組,格式示例:
["改寫1", "改寫2", "改寫3", "改寫4", "改寫5"]"""if client is None:ensure_client()
# ④ 調用 OpenAI ChatCompletion 接口
response = client.chat.completions.create(model="gpt-4o",  # 或 "gpt-4-turbo-preview" 支持 response_format=json_objectmessages=[{"role": "system", "content": "你是一個只輸出 JSON 數組的助手,不要添加多余文字。"},{"role": "user",   "content": prompt}],temperature=0.0,max_tokens=256
)# ⑤ 解析 JSON 數組并打印
result = json.loads(response.choices[0].message.content)
# print(result)# 輸出改寫結果
print(f"提示詞:{prompt_str}\n")
print("原始查詢:")
print(queries)print("\n改寫后的查詢:")
print(result)

3. 提示增強(Hint-Based)

// 英文原版
Here are some hints that you might consider when rewriting the query:
{Hints: a list of rewrite rules, e.g., "Avoid unnecessary JOINs", "Use explicit CTEs"}
Answer:
{Candidate rewrite}
Explanation:
{Which hints were applied}// 中文翻譯
下面是改寫時可參考的提示:
{提示列表,例如:“避免不必要的 JOIN 操作”、“使用顯式的 CTE”}
回答:
{候選重寫語句}
解釋:
{說明使用了哪些提示}// 用法說明
//   在生成式改寫中注入具體規則提示,結合提示工程提高改寫質量。 :contentReference[oaicite:3]{index=3}

import os
import openai
import json# 環境變量中設置 OPENAI_API_KEY
openai.api_key = os.getenv("OPENAI_API_KEY")# ① 待改寫的查詢列表
queries = ["iphon14 pro 價錢","它昨年營收多少","聯想筆電多少錢","apple 更新日志","best python web framework 性能 比較"
]# ② 將列表拼接為多行 Prompt
#    使用 join + 列表推導,每一項前面加 "- "
queries_block = "\n".join(f"- {q}" for q in queries)# ③ 構造完整 Prompt,示例格式引導模型輸出 JSON 數組
prompt_str1="重寫以下查詢,使其更完整、更易檢索:"
prompt_str="""Rewrite the following query to make it more complete and easier to retrieve:Here are some hints that you might consider when rewriting the query:
{Hints: a list of rewrite rules, e.g., "Avoid unnecessary JOINs", "Use explicit CTEs"}
Answer:
{Candidate rewrite}
Explanation:
{Which hints were applied}"""
prompt = f"""
{prompt_str}\n
{queries_block}請**只**返回一個 JSON 數組,格式示例:
["改寫1", "改寫2", "改寫3", "改寫4", "改寫5"]"""if client is None:ensure_client()
# ④ 調用 OpenAI ChatCompletion 接口
response = client.chat.completions.create(model="gpt-4o",  # 或 "gpt-4-turbo-preview" 支持 response_format=json_objectmessages=[{"role": "system", "content": "你是一個只輸出 JSON 數組的助手,不要添加多余文字。"},{"role": "user",   "content": prompt}],temperature=0.0,max_tokens=256
)# ⑤ 解析 JSON 數組并打印
result = json.loads(response.choices[0].message.content)
# print(result)# 輸出改寫結果
print(f"提示詞:{prompt_str}\n")
print("原始查詢:")
print(queries)print("\n改寫后的查詢:")
print(result)

4. 結合 RAG 的生成式改寫

// 英文原版
We use a Generative AI model to rewrite the question… enabling a rewrite-retrieve-read pipeline.
// 中文翻譯
我們使用生成式 AI 模型對用戶問題進行改寫,形成“改寫-檢索-閱讀”流水線。
// 用法說明
//   在 RAG 架構中,先用 LLM 生成改寫候選,再并行檢索并融合答案,可顯著提升覆蓋率與一致性。 :contentReference[oaicite:5]{index=5}

?

import os
import json
import numpy as np
from openai import OpenAI, OpenAIError# —— 初始化客戶端 ——
# client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))QUERIES = ["iphon14 pro 價錢","它昨年營收多少","聯想筆電多少錢","apple 更新日志","best python web framework 性能 比較"
]def generate_candidates(query: str, n: int = 3) -> list[str]:prompt = (f"重寫以下查詢,使其更完整、更易檢索,每條生成{n}個候選:\n"f"1. {query}\n\n只返回 JSON 數組格式:\n""[[\"改寫1\",\"改寫2\",\"改寫3\"]]")resp = client.chat.completions.create(model="gpt-4o",messages=[{"role": "system", "content": "你只輸出 JSON 數組,不要多余說明。"},{"role": "user",   "content": prompt}],temperature=0.0,max_tokens=200,)return json.loads(resp.choices[0].message.content)[0]def get_embedding(text: str, model: str = "text-embedding-3-small") -> np.ndarray:resp = client.embeddings.create(input=[text], model=model)return np.array(resp.data[0].embedding)def main():output = {}for q in QUERIES:# 1. 生成候選candidates = generate_candidates(q, n=3)# 2. 獲取原查詢與候選的嵌入(NumPy 數組)orig_emb = get_embedding(q)                     # shape: (D,)cand_embs = np.stack([get_embedding(c) for c in candidates])  # shape: (3, D)# 3. 向量化計算余弦相似度#    dots: (3,) — 原向量與每個候選的點積dots = cand_embs.dot(orig_emb)#    norms: 標量與向量范數orig_norm = np.linalg.norm(orig_emb)cand_norms = np.linalg.norm(cand_embs, axis=1)scores = dots / (orig_norm * cand_norms + 1e-10)# 4. 排序并保存idxs = np.argsort(scores)[::-1]ranked = [{"rewrite": candidates[i], "score": float(scores[i])} for i in idxs]output[q] = ranked# 輸出最終結果print(json.dumps(output, ensure_ascii=False, indent=2))if __name__ == "__main__":try:main()except OpenAIError as e:print("調用 OpenAI API 出錯:", e)

5. 多樣化并行改寫

// 英文原版
Generate 3 paraphrases of the query, then pick the best by semantic similarity.
// 中文翻譯
生成該查詢的3條同義改寫,然后按語義相似度選取最優。
// 用法說明
//   結合多候選并行檢索與重排序,平衡召回和精度。 :contentReference[oaicite:7]{index=7}

?

import os
import json
import math
from typing import List, Dict, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
from openai import OpenAI
from requests.exceptions import RequestException# —— 初始化客戶端 ——
# client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))# —— 原始查詢列表 ——
QUERIES = ["iphon14 pro 價錢","它昨年營收多少","聯想筆電多少錢","apple 更新日志","best python web framework 性能 比較"
]# —— 重試裝飾器 ——
def retry_on_exception(max_retries=3):def decorator(func):def wrapper(*args, **kwargs):for attempt in range(1, max_retries + 1):try:return func(*args, **kwargs)except RequestException as e:if attempt == max_retries:raise# should not reach herereturn wrapperreturn decorator# —— 生成改寫候選 ——
@retry_on_exception()
def generate_candidates(queries: List[str], n: int = 3) -> List[List[str]]:prompt = "重寫以下查詢,使其更完整、更易檢索,每條生成 {} 個候選:\n".format(n)prompt += "\n".join(f"{i+1}. {q}" for i, q in enumerate(queries))prompt += "\n\n請只返回 JSON 數組,格式示例:\n" \"[[\"改寫1a\",\"改寫1b\",\"改寫1c\"], ...]"resp = client.chat.completions.create(model="gpt-4o",messages=[{"role": "system", "content": "你是只輸出 JSON 數組的助手,不要多余說明。"},{"role": "user",   "content": prompt}],temperature=0.0,max_tokens=500,timeout=15.0)return json.loads(resp.choices[0].message.content)# —— 批量獲取 Embedding ——
@retry_on_exception()
def batch_embeddings(texts: List[str], model="text-embedding-3-small") -> List[List[float]]:resp = client.embeddings.create(input=texts,model=model,timeout=15.0)return [item.embedding for item in resp.data]# —— 余弦相似度 ——
def cosine_sim(v1: List[float], v2: List[float]) -> float:dot = sum(a*b for a, b in zip(v1, v2))norm1 = math.sqrt(sum(a*a for a in v1))norm2 = math.sqrt(sum(b*b for b in v2))return dot / (norm1 * norm2) if norm1 and norm2 else 0.0# —— 排序任務 ——
def rank_for_query(orig: str, candidates: List[str],orig_emb: List[float], cand_embs: List[List[float]]) -> List[Dict[str, Any]]:scored = [{"rewrite": cand, "score": cosine_sim(orig_emb, emb)}for cand, emb in zip(candidates, cand_embs)]return sorted(scored, key=lambda x: x["score"], reverse=True)def main():# 1. 生成候選candidates = generate_candidates(QUERIES, n=3)# 2. 統一準備所有需要嵌入的文本all_texts = []for q, cands in zip(QUERIES, candidates):all_texts.append(q)all_texts.extend(cands)# 3. 批量請求嵌入embeddings = batch_embeddings(all_texts)# 劃分回原始與候選idx = 0orig_embs, cand_embs_list = [], []for cands in candidates:orig_embs.append(embeddings[idx]); idx += 1group = embeddings[idx: idx + len(cands)]; idx += len(cands)cand_embs_list.append(group)# 4. 并行排序output: Dict[str, Any] = {}with ThreadPoolExecutor() as executor:futures = {executor.submit(rank_for_query, q, cands, oe, ce):q for q, cands, oe, ce in zip(QUERIES, candidates, orig_embs, cand_embs_list)}for fut in as_completed(futures):q = futures[fut]output[q] = fut.result()# 5. 輸出print(json.dumps(output, ensure_ascii=False, indent=2))if __name__ == "__main__":main()

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/86766.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/86766.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/86766.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

西門子S7-200 SMART PLC:小型自動化領域的高效之選

在工業自動化領域,小型PLC作為設備控制的核心組件,其性能、靈活性和性價比始終是用戶關注的重點。西門子推出的S7-200 SMART可編程控制器,憑借對中國市場需求的精準把握,成為了小型自動化解決方案的標桿產品。本文將從產品亮點、技…

使用iperf3測試網絡的方法

深入掌握網絡性能測試:iperf3全指南 在網絡優化、故障排查和帶寬驗證中,iperf 是工程師必備的利器。這款開源工具通過模擬數據流,精準測量??帶寬、抖動、丟包率??等核心指標。本文將結合實戰經驗,詳解iperf的安裝、參數配置和…

Level2.11繼承

一、繼承 #動物# #老虎、獅子、大象 #動物有共性 ##定義一個動物:1.有4條腿;2.陸地上跑;3.需要進食(屬性能力) ##貓:同上(繼承了動物的屬性和能力) ##老鼠:同上#Python…

Class3Softmax回歸

Class3Softmax回歸 回歸VS分類 回歸是估計一個連續值 分類是預測一個離散類別 回歸分類單連續值輸出通常為多個輸出自然區間R輸出i是預測為第i類的置信度跟真實值的區別作為損失 生活中的分類問題 1.垃圾分類 類別: 可回收物 濕垃圾(廚余垃圾&#xff0…

day042-負載均衡與web集群搭建

文章目錄 0. 老男孩思想-面試官問:你對加班的看法?1. 負載均衡2. 搭建負載均衡的WordPress集群2.1 負載均衡服務器2.2 配置web服務器2.3 測試 踩坑記錄1. /var/cache/nginx權限問題 0. 老男孩思想-面試官問:你對加班的看法? 互聯網公司沒有不加班的&a…

40歲技術人用AI尋找突破路線

年近40,坐標重慶,從事醫療器械行業多年,遇到發展瓶頸。剛好遇到AI技術浪潮。最近一年在不斷嘗試把AI應用于工作生活的方方面面。 總結一下我是如何利用AI來做職業規劃的: 整理好自己的簡歷,越詳細越好。這個可以利用…

kde截圖工具報錯

An error occurred while taking a screenshot. KWin screenshot request failed: The process is not authorized to take a screenshot Potentially relevant information: - Method: CaptureScreen - Method specific arguments: "eDP-2"好的,感謝您提…

有理函數積分——分式分解時設分解式的規則

目錄 一、設前處理 1. 假式化真式 2. 分母因式分解 3. 判斷可約不可約 二、一次分母 1. 多項一次分母? 2. 單項一次重復分母? 三、二次分母(當然是分母不可約的,如果可約就因式分解然后對應一次分母) 1. 多項二次分母? 2. 單項二次重復分母? 四、混…

從 AJAX 到 axios:前端與服務器通信實戰指南

直到現在我們小寧已經更新了44作品了,其中和大家介紹了Python入門基礎、Fast API框架、SQLite數據庫,以及前端的知識都已經學習完了,總的來說現在前端、后端、數據庫已經都學習了,那大家是否有這樣的疑問,前端后端到底…

Pycatia二次開發基礎代碼解析:面屬性控制、視圖定向與特征統計的工業級實現

本文將以專業視角深入解析CATIA二次開發中的三個核心類方法,通過詳細分析代碼實現揭示其在工業設計中的實際應用價值。全文將嚴格圍繞提供的代碼展開,不做任何修改或補充。 一、面屬性控制:精確可視化表達技術 方法功能解析 color_and_laye…

bmc TrueSight 監控 Oracle 11g 配置

bmc TrueSight 監控 Oracle配置 文章目錄 bmc TrueSight 監控 Oracle配置1.將pat加入oinstall和dba組2.創建監控的表空間和臨時表空間并告知表空間名稱3.將oracle相關系統環境變量加入到監控pat賬戶的.profile或.bash_profile文件4.登陸Apollo監控web頁面,設置基礎架…

css實現高度可變、上下邊框是漸變色、左右邊框是純色的div容器

效果圖&#xff1a; div容器&#xff1a; <div className{styles.container}><div className{styles.content}><div className{styles.inner}><!-- 內容部分 --></div></div> </div> css&#xff1a; .container {float: left;w…

python二維碼識別

pyzbar 識別QR二維碼 from PIL import Image from pyzbar.pyzbar import decode# 打開圖像文件 image_path qr01.jpg # 替換為你的圖像路徑 image Image.open(image_path)# 解碼圖像中的二維碼 decoded_objects decode(image)# 輸出識別結果 for obj in decoded_objects:p…

ZYNQ EMMC/FLASH/SD卡深度性能評測與創新實踐

深入探索ZYNQ存儲子系統性能,揭示硬件加速下的存儲優化之道 一、存儲性能為何如此重要? 在基于Xilinx ZYNQ SoC的嵌入式系統中,EMMC、QSPI FLASH和SD卡作為核心存儲介質,直接影響系統啟動時間、數據吞吐量和用戶體驗。傳統測試方法往往局限于簡單讀寫速度測試,缺乏對真實…

html制作一個簡單的表單

<!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><title>表單輸入練習</title><style></style> </head><body style"background-color: pink;"><div><h2>…

差分對的等長等距

差分對的等長等距: 差分對中兩個單端信號的延時差會導致接收端信號的錯位&#xff0c;引起差分信號的畸變&#xff0c;同時會產生共模噪聲導致接收端差分信號抖動增加。因此差分對設計的一個基本要求就是要盡量保持差分對兩條單端線延時相等。 圖8-27顯示了差分對中兩條單端線…

SQL 子查詢全位置解析:可編寫子查詢的 7 大子句

&#x1f50d; SQL 子查詢全位置解析&#xff1a;可編寫子查詢的 7 大子句 子查詢可以出現在 SQL 語句的多個關鍵位置&#xff0c;不同位置的子查詢具有獨特的行為和限制。以下是系統化總結&#xff1a; &#x1f4cc; 1. WHERE 子句&#xff08;最常用&#xff09; SELECT 列…

C#高級:Winform桌面開發中DataGridView的詳解(新)

一、數據填充&#xff08;反射&#xff09; 1.封裝 /// <summary> /// 渲染DataGridView /// </summary> /// <param name"dataGridView">被渲染控件</param> /// <param name"list">數據集</param> /// <param …

人臉活體識別2:Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集)

人臉活體識別2&#xff1a;Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集) 目錄 人臉活體識別2&#xff1a;Pytorch實現人臉眨眼 張嘴 點頭 搖頭識別(含訓練代碼和數據集) 1. 前言 2.人臉活體識別方法 &#xff08;1&#xff09;基于人臉動作的檢測?? &a…

Webpack 自定義插件開發指南:構建流程詳解與實戰開發全攻略

一. webpack打包流程 開發 Webpack 插件的第一步&#xff0c;就是明確&#xff1a;我的插件要接入 Webpack 構建流程的哪個階段&#xff0c;解決什么問題。 了解流程之前首先要了解插件的兩個核心概念&#xff1a;compiler&#xff0c;compilation 1. compiler&#xff1a;全局…