fix: 修复了prompt模板功能的若干bug

This commit is contained in:
tcmofashi
2025-04-13 02:02:52 +08:00
parent 46da415d98
commit e61bcdb435
2 changed files with 15 additions and 19 deletions

View File

@@ -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,14 +137,11 @@ 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)
if expr and expr not in template_args:
template_args.append(expr)
result = re.findall(r"\{(.*?)\}", template)
for expr in result:
if expr and expr not in template_args:
template_args.append(expr)
formatted_args = {}
formatted_kwargs = {}
@@ -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