Skip to content

文本生成

Gemini 适合生成、总结、改写、分类、抽取和多轮问答。接入时统一使用 Generate Content API:

text
https://xikapi.com/v1beta/models/{model}:generateContent

基础文本生成

bash
curl "https://xikapi.com/v1beta/models/gemini-3.5-flash:generateContent?key=$XIKAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [
          { "text": "Write a product description in fewer than 100 words" }
        ]
      }
    ]
  }'

长文本总结

长文本总结适合合同、会议纪要、报告、客服记录和知识库文档。

json
{
  "systemInstruction": {
    "parts": [
      {
        "text": "You are a document summarization assistant. Preserve key facts, amounts, dates, responsible parties, and risks."
      }
    ]
  },
  "generationConfig": {
    "maxOutputTokens": 1200
  },
  "contents": [
    {
      "parts": [
        { "text": "Summarize the following contract content: ..." }
      ]
    }
  ]
}

改写与润色

改写任务建议明确目标语气、长度和保留信息。

text
Rewrite the following support reply to be more polite and clear. Preserve the refund rules and processing timeline, and do not promise anything not stated.

分类与抽取

分类和抽取适合客服工单、反馈归因、内容审核、订单备注识别等场景。

json
{
  "generationConfig": {
    "temperature": 0,
    "maxOutputTokens": 500
  },
  "contents": [
    {
      "parts": [
        {
          "text": "Classify the text as complaint, inquiry, or praise. Text: I paid, but the order has not arrived."
        }
      ]
    }
  ]
}

多轮问答

多轮问答需要服务端维护必要历史。历史越长,成本越高,也越容易引入无关上下文。

json
{
  "contents": [
    { "role": "user", "parts": [{ "text": "I want to build a document Q&A system" }] },
    { "role": "model", "parts": [{ "text": "Start with document chunking and vector retrieval." }] },
    { "role": "user", "parts": [{ "text": "What should I consider when chunking?" }] }
  ]
}

控制输出长度

可以同时用 maxOutputTokens 和提示词约束输出长度。

text
Answer in no more than five bullet points, each under 30 words.

生产环境建议:

  • 短回复使用较小 maxOutputTokens
  • 总结和分析任务给足输出空间
  • 对必须短输出的场景增加服务端截断或校验

控制语气和格式

把稳定要求放在 systemInstruction 中,把本轮任务放在 contents 中。

json
{
  "systemInstruction": {
    "parts": [
      { "text": "You are an enterprise support assistant. Be polite and concise, and do not invent policies." }
    ]
  },
  "contents": [
    {
      "parts": [
        { "text": "The user says a top-up has not arrived. Draft a support reply." }
      ]
    }
  ]
}

常见 Prompt 模板

文章生成:

text
Write an article about the topic with these requirements:
1. Start with a title
2. Use three sections
3. Keep the tone professional but not exaggerated
4. Do not use unverified data

合同总结:

text
Summarize the contract using this structure:
- Parties
- Scope of services
- Payment terms
- Breach liability
- Risks requiring manual review

字段抽取:

text
Extract name, phone number, order ID, and issue type from the text. Use null for unknown fields.

最佳实践

  • 把稳定角色和边界放入 systemInstruction
  • 对分类、抽取等任务降低 temperature
  • 输出 JSON 时配合服务端解析和校验
  • 长文档先切分,再总结或检索
  • 不要把 API Key 暴露在浏览器前端