You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制OpenAI API仅响应软件/技术类查询?

限制OpenAI API仅响应软件技术类查询的可靠实现方案

原基于text-davinci-002的prompt方案偶尔出现不符合预期的响应,可通过以下几种更可靠的方式实现需求:

1. 优化Prompt指令并添加明确规则

通过更清晰、无歧义的指令约束模型行为,同时补充领域范围示例,提升判断准确性:

const query = `
请严格遵守以下规则处理用户查询:
1. 判定标准:仅将编程语言(如Node.js、Python)、软件开发、算法、数据库、前后端技术、DevOps、云计算、软件工具使用等归为软件与技术领域。
2. 非领域查询:直接返回"Not related to software and tech",不得添加任何额外内容。
3. 领域内查询:正常回答用户问题。

用户查询:${sugg}
`;

const data = {
  model: "text-davinci-002",
  prompt: query,
  temperature: 0.2, // 降低温度提升响应一致性
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
  max_tokens: 500,
  n: 1,
};

2. 切换至Chat Completions API(推荐)

Chat模型(如gpt-3.5-turbo、gpt-4)对系统指令的遵循度远高于传统Completion模型,通过system角色明确规则:

const data = {
  model: "gpt-3.5-turbo",
  messages: [
    {
      role: "system",
      content: `请严格执行以下规则:
1. 判断用户查询是否属于软件与技术领域,范围包括但不限于编程语言、软件开发、算法、数据库、前后端技术、DevOps、云计算、软件工具使用。
2. 非相关查询直接返回"Not related to software and tech",无额外内容。
3. 相关查询正常作答。`
    },
    {
      role: "user",
      content: sugg
    }
  ],
  temperature: 0.2,
  max_tokens: 500
};

3. 添加前置分类校验

先用轻量模型做领域预分类,再决定是否调用主API回答,双重保障准确性且降低成本:

// 第一步:调用轻量模型做领域分类
const classifyPayload = {
  model: "text-babbage-001",
  prompt: `判断以下查询是否属于软件与技术领域,仅返回"是"或"否":${sugg}`,
  temperature: 0, // 温度设为0确保分类结果绝对确定
  max_tokens: 1
};

// 发送分类请求后处理结果
async function handleUserQuery(sugg) {
  const classifyRes = await fetch("https://api.openai.com/v1/completions", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" },
    body: JSON.stringify(classifyPayload)
  });
  const classifyData = await classifyRes.json();
  const classification = classifyData.choices[0].text.trim();

  if (classification === "是") {
    // 第二步:调用主API回答技术问题
    const answerPayload = {
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: sugg }],
      max_tokens: 500
    };
    const answerRes = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" },
      body: JSON.stringify(answerPayload)
    });
    const answerData = await answerRes.json();
    return answerData.choices[0].message.content;
  } else {
    return "Not related to software and tech";
  }
}

4. 参数调优提升一致性

  • 将temperature设置为0-0.3:降低模型输出随机性,提升规则遵循度。
  • 对Completion模型,可添加stop参数:避免模型输出额外无关内容。

内容的提问来源于stack exchange,提问作者gopinath krm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:23:14