SQLTableRetrieverQueryEngine添加动态Few-Shot示例遇模板变量限制的解决方法
解决SQLTableRetrieverQueryEngine动态Few-Shot示例插入问题
方法一:提前将Few-Shot示例转为字符串嵌入模板
直接把few_shot_examples处理成格式化字符串,通过预填充的方式注入模板,绕过原模板的变量限制:
操作步骤
- 先将示例列表转换为规范字符串:
few_shot_str = "\n".join([ f"示例{idx+1}:\n用户问题:{ex['query']}\n生成SQL:{ex['sql']}\n结果解释:{ex['explanation']}" for idx, ex in enumerate(few_shot_examples) ])
- 自定义模板时直接嵌入该字符串,或用
partial_format预填充后传入引擎:
from llama_index.core import PromptTemplate # 自定义带示例的Text-to-SQL模板 text_to_sql_template = PromptTemplate( """ 以下是SQL生成参考示例: {few_shot_str} 请根据用户问题和表结构生成合法SQL: 用户问题:{query_str} 表结构信息:{context_str} 生成的SQL语句: """ ).partial_format(few_shot_str=few_shot_str) # 初始化查询引擎时传入自定义模板 query_engine = SQLTableRetrieverQueryEngine( sql_database=db, text_to_sql_prompt=text_to_sql_template # 其他必要参数... )
方法二:自定义Prompt类绕过变量校验
如果需要动态更新示例,可继承PromptTemplate类,在格式化阶段自动注入示例字符串:
from llama_index.core import PromptTemplate class CustomSQLPrompt(PromptTemplate): def __init__(self, template, few_shot_examples, **kwargs): super().__init__(template, **kwargs) self.few_shot_examples = few_shot_examples def format(self, **kwargs): # 实时转换示例为字符串 few_shot_str = "\n".join([ f"示例{idx+1}:\n用户问题:{ex['query']}\n生成SQL:{ex['sql']}" for idx, ex in enumerate(self.few_shot_examples) ]) # 合并参数并注入示例 updated_kwargs = {**kwargs, "few_shot_str": few_shot_str} return super().format(**updated_kwargs) # 实例化自定义模板 custom_template = CustomSQLPrompt( template=""" 参考以下示例生成SQL: {few_shot_str} 用户问题:{query_str} 表结构:{context_str} SQL语句: """, few_shot_examples=your_few_shot_list ) # 传入查询引擎使用 query_engine = SQLTableRetrieverQueryEngine( sql_database=db, text_to_sql_prompt=custom_template # 其他必要参数... )
方法三:替换响应合成组件
直接替换引擎的响应合成器,使用支持自定义变量的合成逻辑:
from llama_index.core.query_engine import SQLTableRetrieverQueryEngine from llama_index.core.response_synthesizers import get_response_synthesizer # 自定义包含示例的响应合成模板 response_template = PromptTemplate( """ 参考以下示例解释SQL查询结果: {few_shot_str} 用户问题:{query_str} 执行的SQL:{sql_query} 查询结果:{context_str} 自然语言解释: """ ) # 初始化响应合成器 response_synthesizer = get_response_synthesizer( text_qa_template=response_template # 其他必要参数... ) # 初始化查询引擎时传入合成器并预填充示例 query_engine = SQLTableRetrieverQueryEngine( sql_database=db, response_synthesizer=response_synthesizer, response_synthesis_kwargs={"few_shot_str": few_shot_str} # 其他必要参数... )
关键说明
原错误是因为response_synthesis_prompt被引擎强制限制只能使用query_str、sql_query、context_str三个变量,直接添加新变量会触发校验。通过提前将示例转为字符串嵌入模板,或自定义模板类绕过校验,即可解决该问题。
内容的提问来源于stack exchange,提问作者L Xandor
相关产品推荐
相关产品推荐

