This commit is contained in:
gongwenxin
2025-06-01 00:38:36 +08:00
parent a4e175bc15
commit b3ac2408be
13 changed files with 5048 additions and 6740 deletions
+61 -3
View File
@@ -5,7 +5,6 @@ import json
import logging
import re
from typing import Optional, Dict, Any, List
import requests
from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
@@ -59,7 +58,7 @@ class LLMService:
self,
messages: List[Dict[str, str]],
max_tokens: int = 1024,
temperature: float = 0.7,
temperature: float = 0.1,
# TODO: Consider adding a parameter like response_format_type: Optional[str] = None
# if the LLM API supports forcing JSON output (e.g., { "type": "json_object" })
) -> Optional[str]:
@@ -114,7 +113,7 @@ class LLMService:
pydantic_model_class: type[BaseModel],
prompt_instruction: Optional[str] = None,
max_tokens: int = 1024,
temperature: float = 0.7
temperature: float = 0.1
) -> Optional[Dict[str, Any]]:
"""
根据给定的Pydantic模型类生成JSON Schema,并调用LLM生成符合该Schema的参数字典。
@@ -178,6 +177,65 @@ class LLMService:
return None
def generate_data_from_schema(
self,
schema_dict: dict,
prompt_instruction: Optional[str] = None,
max_tokens: int = 1024,
temperature: float = 0.1
) -> Optional[Dict[str, Any]]:
"""
根据给定的JSON Schema字典,调用LLM生成符合该Schema的数据对象。
"""
try:
schema_str = json.dumps(schema_dict, indent=2, ensure_ascii=False)
logger.debug(f"LLMService.generate_data_from_schema: 使用的JSON Schema:\n{schema_str}")
system_prompt = (
"你是一个API测试数据生成助手。你的任务是根据用户提供的JSON Schema和额外指令,"
"生成一个符合该Schema的JSON对象。请确保你的输出严格是一个JSON对象,"
"不包含任何额外的解释、注释或Markdown标记。"
)
user_prompt_content = f"请为以下JSON Schema生成一个有效的JSON对象实例:\n\n```json\n{schema_str}\n```\n"
if prompt_instruction:
user_prompt_content += f"\n请遵循以下额外指令:\n{prompt_instruction}"
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt_content}
]
assistant_response_content = self._execute_chat_completion_request(
messages=messages,
max_tokens=max_tokens,
temperature=temperature
)
if assistant_response_content:
# 尝试从返回内容中提取JSON部分
json_match = re.search(r'```json\n(.*?)\n```', assistant_response_content, re.DOTALL)
if json_match:
json_str = json_match.group(1)
else:
first_brace = assistant_response_content.find('{')
last_brace = assistant_response_content.rfind('}')
if first_brace != -1 and last_brace != -1 and last_brace > first_brace:
json_str = assistant_response_content[first_brace : last_brace+1]
else:
json_str = assistant_response_content
try:
generated_data = json.loads(json_str)
logger.info("成功从LLM生成并解析了数据。")
return generated_data
except json.JSONDecodeError as e_json:
logger.error(f"无法将LLM响应解析为JSON: {e_json}\n原始响应片段: '{json_str[:500]}'")
else:
logger.warning("从LLM获取的响应内容为空或请求失败。")
except Exception as e:
logger.error(f"执行LLM数据生成时发生未知错误: {e}", exc_info=True)
return None
# --- 示例用法 (用于模块内测试) ---
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG,