fix: 修复了prompt模板功能的若干bug
This commit is contained in:
@@ -195,7 +195,7 @@ class PromptBuilder:
|
||||
prompt = await global_prompt_manager.format_prompt(
|
||||
"reasoning_prompt_main",
|
||||
relation_prompt_all=await global_prompt_manager.get_prompt_async("relationship_prompt"),
|
||||
replation_prompt=relation_prompt,
|
||||
relation_prompt=relation_prompt,
|
||||
sender_name=sender_name,
|
||||
memory_prompt=memory_prompt,
|
||||
prompt_info=prompt_info,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# import re
|
||||
import ast
|
||||
from typing import Dict, Any, Optional, List, Union
|
||||
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
|
||||
@@ -98,13 +96,11 @@ class Prompt(str):
|
||||
args = list(args)
|
||||
|
||||
# 解析模板
|
||||
tree = ast.parse(f"f'''{fstr}'''", mode="eval")
|
||||
template_args = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FormattedValue):
|
||||
expr = ast.get_source_segment(fstr, node.value)
|
||||
if expr:
|
||||
template_args.add(expr)
|
||||
template_args = []
|
||||
result = re.findall(r"\{(.*?)\}", fstr)
|
||||
for expr in result:
|
||||
if expr and expr not in template_args:
|
||||
template_args.append(expr)
|
||||
|
||||
# 如果提供了初始参数,立即格式化
|
||||
if kwargs or args:
|
||||
@@ -141,12 +137,9 @@ class Prompt(str):
|
||||
|
||||
@classmethod
|
||||
def _format_template(cls, template: str, args: List[Any] = None, kwargs: Dict[str, Any] = None) -> str:
|
||||
fmt_str = f"f'''{template}'''"
|
||||
tree = ast.parse(fmt_str, mode="eval")
|
||||
template_args = []
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FormattedValue):
|
||||
expr = ast.get_source_segment(fmt_str, node.value)
|
||||
result = re.findall(r"\{(.*?)\}", template)
|
||||
for expr in result:
|
||||
if expr and expr not in template_args:
|
||||
template_args.append(expr)
|
||||
formatted_args = {}
|
||||
@@ -180,13 +173,16 @@ class Prompt(str):
|
||||
template = template.format(**formatted_kwargs)
|
||||
return template
|
||||
except (IndexError, KeyError) as e:
|
||||
raise ValueError(f"格式化模板失败: {template}, args={formatted_args}, kwargs={formatted_kwargs}") from e
|
||||
raise ValueError(
|
||||
f"格式化模板失败: {template}, args={formatted_args}, kwargs={formatted_kwargs} {str(e)}"
|
||||
) from e
|
||||
|
||||
def format(self, *args, **kwargs) -> "Prompt":
|
||||
"""支持位置参数和关键字参数的格式化,使用"""
|
||||
ret = type(self)(
|
||||
self.template, self.name, args=list(args) if args else self._args, **kwargs if kwargs else self._kwargs
|
||||
)
|
||||
ret.template = str(ret)
|
||||
# print(f"prompt build result: {ret} name: {ret.name} ")
|
||||
return ret
|
||||
|
||||
|
||||
Reference in New Issue
Block a user