当前位置: 首页 > news >正文

【Basic】【response_synthesizers1】自定义提示词响应合成器案例

本案例演示如何使用LlamaIndex中的自定义提示词和响应合成器,通过TreeSummarize和Refine策略,实现不同风格的文本响应生成。

1. 案例目标

本案例的主要目标是:

  1. 演示如何创建自定义提示词模板,用于控制AI响应的风格和格式
  2. 展示如何使用TreeSummarize和Refine两种不同的响应合成策略
  3. 实现基于Pydantic模型的结构化输出
  4. 通过不同风格的提示词参数(如莎士比亚风格、俳句风格等)生成多样化的响应

2. 技术栈与核心依赖

  • LlamaIndex- 用于文档索引、查询和响应合成
  • OpenAI API- 提供大语言模型能力
  • Pydantic- 用于定义结构化数据模型

核心依赖安装

pip install llama-index

3. 环境配置

在开始之前,需要设置OpenAI API密钥:

import os import openai os.environ["OPENAI_API_KEY"] = "sk-..." openai.api_key = os.environ["OPENAI_API_KEY"]

4. 案例实现

4.1 数据准备

首先,下载并加载Paul Graham的文章作为示例数据:

from llama_index.core import SimpleDirectoryReader # 创建目录并下载数据 !mkdir -p 'data/paul_graham/' !wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt' # 加载数据 reader = SimpleDirectoryReader( input_files=["./data/paul_graham/paul_graham_essay.txt"] ) docs = reader.load_data() text = docs[0].text

4.2 自定义提示词模板

创建自定义的问答提示词和优化提示词模板:

from llama_index.core import PromptTemplate # 问答提示词模板,添加了tone_name变量用于控制风格 qa_prompt_tmpl = ( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information and not prior knowledge, " "answer the query.\n" "Please also write the answer in the style of {tone_name}.\n" "Query: {query_str}\n" "Answer: " ) qa_prompt = PromptTemplate(qa_prompt_tmpl) # 优化提示词模板,用于改进已有答案 refine_prompt_tmpl = ( "The original query is as follows: {query_str}\n" "We have provided an existing answer: {existing_answer}\n" "We have the opportunity to refine the existing answer " "(only if needed) with some more context below.\n" "------------\n" "{context_msg}\n" "------------\n" "Given the new context, refine the original answer to better " "answer the query. " "Please also write the answer in the style of {tone_name}.\n" "If the context isn't useful, return the original answer.\n" "Refined Answer: " ) refine_prompt = PromptTemplate(refine_prompt_tmpl)

4.3 使用TreeSummarize响应合成器

使用TreeSummarize策略生成莎士比亚风格的响应:

from llama_index.core.response_synthesizers import TreeSummarize # 创建TreeSummarize实例,使用自定义提示词 summarizer = TreeSummarize(verbose=True, summary_template=qa_prompt) # 生成响应 response = summarizer.get_response( "who is Paul Graham?", [text], tone_name="a Shakespeare play" ) print(str(response))

4.4 使用Refine响应合成器

使用Refine策略生成俳句风格的响应:

from llama_index.core.response_synthesizers import Refine # 创建Refine实例,使用自定义提示词 summarizer = Refine( verbose=True, text_qa_template=qa_prompt, refine_template=refine_prompt ) # 生成响应 response = summarizer.get_response( "who is Paul Graham?", [text], tone_name="a haiku" ) print(str(response))

4.5 使用Pydantic模型的结构化输出

定义Pydantic模型并生成结构化响应:

from llama_index.core.types import BaseModel from typing import List # 定义Pydantic模型 class Biography(BaseModel): """Data model for a biography.""" name: str best_known_for: List[str] extra_info: str # 创建TreeSummarize实例,指定输出模型 summarizer = TreeSummarize( verbose=True, summary_template=qa_prompt, output_cls=Biography ) # 生成结构化响应 response = summarizer.get_response( "who is Paul Graham?", [text], tone_name="a business memo" ) print(str(response))

5. 案例效果

运行上述代码后,我们可以看到以下效果:

5.1 莎士比亚风格响应

Paul Graham, a noble and esteemed gentleman, is a man of many talents and accomplishments. He hath traversed the realms of art, entrepreneurship, and writing, leaving a lasting impact on each. With his brush, he hath brought life to canvases, capturing the essence of what he saw. In the realm of technology, he hath revolutionized the way we do business, founding Viaweb and bringing the power of the web to entrepreneurs and artists alike. His wisdom and guidance hath shaped the future of technology and entrepreneurship through his co-founding of Y Combinator. But above all, Paul Graham is a visionary, a trailblazer, and a true Renaissance man, whose intellectual curiosity and quest for lasting creation hath inspired generations to come.

5.2 俳句风格响应

Paul Graham, a web pioneer,
Co-founded Y Combinator,
But stepped down to ensure,
Long-term success and more.

5.3 结构化输出

name='Paul Graham' best_known_for=['Co-founder of Y Combinator', 'Writer', 'Investor'] extra_info="Paul Graham is a renowned entrepreneur, writer, and investor. He is best known as the co-founder of Y Combinator, a highly successful startup accelerator. Graham has played a significant role in shaping the startup ecosystem and has been instrumental in the success of numerous startups. He is also a prolific writer, known for his insightful essays on a wide range of topics, including technology, startups, and entrepreneurship. Graham's writings have been widely read and have had a profound impact on the tech community. In addition to his work with Y Combinator and his writing, Graham is also an active investor, providing seed funding and mentorship to early-stage startups. His contributions to the startup world have earned him a reputation as one of the most influential figures in the industry."

6. 案例实现思路

本案例的核心实现思路包括:

6.1 提示词模板化

通过将提示词模板化,并在其中插入变量(如{tone_name}),实现了动态控制响应风格的能力。这种方法使得同一套代码可以生成不同风格的响应,大大提高了代码的复用性。

6.2 响应合成策略选择

案例展示了两种主要的响应合成策略:

  • TreeSummarize:通过构建树形结构来组织和总结信息,适合处理大量文本数据
  • Refine:通过迭代优化已有答案来生成更准确的响应,适合需要逐步完善答案的场景

6.3 结构化输出

通过使用Pydantic模型定义输出结构,使AI能够生成符合特定格式的结构化数据,这对于需要将AI输出集成到应用程序中的场景非常有用。

7. 扩展建议

  • 多风格提示词库:可以创建一个包含多种风格的提示词库,用户可以通过参数选择不同的响应风格
  • 动态风格切换:根据查询内容自动选择最适合的响应风格,例如技术问题使用专业风格,创意问题使用文学风格
  • 多语言支持:扩展提示词模板以支持多语言输出,满足不同语言用户的需求
  • 响应质量评估:添加自动评估机制,对不同风格生成的响应进行质量评分,帮助用户选择最佳答案
  • 交互式风格调整:开发交互式界面,允许用户实时调整响应风格参数,并即时查看效果
  • 上下文感知风格:根据文档内容的类型自动调整响应风格,例如对文学作品使用文学风格,对技术文档使用技术风格

8. 总结

本案例展示了如何通过自定义提示词和响应合成器实现灵活多样的AI响应生成。通过模板化提示词、选择不同的响应合成策略以及使用结构化输出,我们能够控制AI响应的风格、格式和内容,使其更好地满足特定应用场景的需求。这种方法不仅提高了AI应用的灵活性,也为构建更加智能和个性化的AI系统奠定了基础。

http://www.jsqmd.com/news/396555/

相关文章:

  • 构建AI系统的七步方法论
  • 大润发购物卡回收怕被骗?京顺回收带你避开3大陷阱 - 京顺回收
  • AI元人文:悟空
  • 什么是贝叶斯误差?
  • 从零开始:用Nano-Banana制作专业产品展示图
  • 泳池溺水行为检测数据集(YOLO格式)
  • 江苏省口播文案ai智能体服务公司排行
  • YOLO12 WebUI实战:一键部署高效目标检测服务
  • 基于Qwen2.5-32B-Instruct的RESTful API设计指南
  • mT5中文-base零样本增强模型实战教程:WebUI界面汉化适配与响应延迟优化
  • 研究生必看!标杆级的AI论文写作软件 —— 千笔·专业论文写作工具
  • 基于Thinkphp和Laravel框架的社区居民诊疗健康管理系统设计与实现
  • 强烈安利!用户挚爱的降AI率工具 —— 千笔·降AIGC助手
  • Python爬虫实战:构建SDPose-Wholebody训练数据集
  • Qwen2.5-7B-Instruct Linux系统管理助手:自动化运维脚本生成
  • SPIRAN ART SUMMONER图像生成与MySQL数据库集成方案
  • Python基于Vue的宠物领养系统 django flask pycharm
  • Python基于Vue的高校学生实习综合服务系统的设计与实现 django flask pycharm
  • LeetCode 761.特殊的二进制字符串:分治(左右括号对移动)
  • Qwen3-4B-Instruct-2507与Ollama集成:本地化部署快速入门教程
  • 基于Thinkphp和Laravel框架的旅游景区(门票,酒店,美食,论坛)管理系统的设计与实现
  • cv_unet_image-colorization效果实测:消费级显卡跑出高清上色,对比DeOldify差异详解
  • 国内零门槛首个免费 开源 724小时帮你干活的全场景个人助理 Agent 手把手教程
  • Face3D.ai Pro与Python结合:3D人脸建模自动化处理实战
  • 速看!2026 评价不错的移动房屋民宿品牌排行,成品移动岗亭/移动房屋/岗亭移动厕所/岗亭售货亭,移动房屋定制推荐 - 品牌推荐师
  • DCT-Net模型在嵌入式设备上的轻量化部署
  • 基于Thinkphp和Laravel框架的企业员工出勤打卡签到系统管理设计与实现
  • 基于Thinkphp和Laravel框架的口腔诊所门诊管理系统的设计与实现
  • 探索VCU控制量产模型:开启控制策略学习之旅
  • Pi0机器人控制中心:6-DOF动作预测实战演示