Skip to content
Open

Main2 #332

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions backend/app/api/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,12 +213,19 @@ def generate_ontology():

# 生成本体
logger.info("调用 LLM 生成本体定义...")
# till this point
generator = OntologyGenerator()
ontology = generator.generate(
document_texts=document_texts,
simulation_requirement=simulation_requirement,
additional_context=additional_context if additional_context else None
)
logger.info("OntologyGenerator....................")
try:
ontology = generator.generate(
document_texts=document_texts,
simulation_requirement=simulation_requirement,
additional_context=additional_context if additional_context else None
)
logger.info("OntologyGenerator try....................")
except Exception as e:
logger.error(f"本体生成失败: {traceback.format_exc()}") # ADD
raise

# 保存本体到项目
entity_count = len(ontology.get("entity_types", []))
Expand Down
11 changes: 6 additions & 5 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ class Config:

# LLM配置(统一使用OpenAI格式)
LLM_API_KEY = os.environ.get('LLM_API_KEY')
LLM_API_KEY_2 = os.environ.get('LLM_API_KEY_2')
LLM_API_KEY_3 = os.environ.get('LLM_API_KEY_3')
LLM_BASE_URL = os.environ.get('LLM_BASE_URL', 'https://api.openai.com/v1')
LLM_MODEL_NAME = os.environ.get('LLM_MODEL_NAME', 'gpt-4o-mini')

Expand All @@ -45,7 +47,7 @@ class Config:
DEFAULT_CHUNK_OVERLAP = 50 # 默认重叠大小

# OASIS模拟配置
OASIS_DEFAULT_MAX_ROUNDS = int(os.environ.get('OASIS_DEFAULT_MAX_ROUNDS', '10'))
OASIS_DEFAULT_MAX_ROUNDS = int(os.environ.get('OASIS_DEFAULT_MAX_ROUNDS', '3'))
OASIS_SIMULATION_DATA_DIR = os.path.join(os.path.dirname(__file__), '../uploads/simulations')

# OASIS平台可用动作配置
Expand All @@ -59,9 +61,9 @@ class Config:
]

# Report Agent配置
REPORT_AGENT_MAX_TOOL_CALLS = int(os.environ.get('REPORT_AGENT_MAX_TOOL_CALLS', '5'))
REPORT_AGENT_MAX_REFLECTION_ROUNDS = int(os.environ.get('REPORT_AGENT_MAX_REFLECTION_ROUNDS', '2'))
REPORT_AGENT_TEMPERATURE = float(os.environ.get('REPORT_AGENT_TEMPERATURE', '0.5'))
REPORT_AGENT_MAX_TOOL_CALLS = int(os.environ.get('REPORT_AGENT_MAX_TOOL_CALLS', '1'))
REPORT_AGENT_MAX_REFLECTION_ROUNDS = int(os.environ.get('REPORT_AGENT_MAX_REFLECTION_ROUNDS', '1'))
REPORT_AGENT_TEMPERATURE = float(os.environ.get('REPORT_AGENT_TEMPERATURE', '0.3'))

@classmethod
def validate(cls):
Expand All @@ -72,4 +74,3 @@ def validate(cls):
if not cls.ZEP_API_KEY:
errors.append("ZEP_API_KEY 未配置")
return errors

1 change: 1 addition & 0 deletions backend/app/services/simulation_config_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ def __init__(
base_url: Optional[str] = None,
model_name: Optional[str] = None
):

self.api_key = api_key or Config.LLM_API_KEY
self.base_url = base_url or Config.LLM_BASE_URL
self.model_name = model_name or Config.LLM_MODEL_NAME
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/simulation_ipc.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def send_command(
self,
command_type: CommandType,
args: Dict[str, Any],
timeout: float = 60.0,
timeout: float = 300.0,
poll_interval: float = 0.5
) -> IPCResponse:
"""
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/zep_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,7 +1380,7 @@ def interview_agents(
simulation_id=simulation_id,
interviews=interviews_request,
platform=None, # 不指定platform,双平台采访
timeout=180.0 # 双平台需要更长超时
timeout=300.0 # 双平台需要更长超时
)

logger.info(f"采访API返回: {api_result.get('interviews_count', 0)} 个结果, success={api_result.get('success')}")
Expand Down
48 changes: 42 additions & 6 deletions backend/app/utils/llm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


class LLMClient:
"""LLM客户端"""
#LLM客户端

def __init__(
self,
Expand All @@ -39,8 +39,9 @@ def chat(
max_tokens: int = 4096,
response_format: Optional[Dict] = None
) -> str:

"""
发送聊天请求
.....发送聊天请求

Args:
messages: 消息列表
Expand All @@ -49,7 +50,7 @@ def chat(
response_format: 响应格式(如JSON模式)

Returns:
模型响应文本
模型响应文本......
"""
kwargs = {
"model": self.model,
Expand All @@ -66,14 +67,15 @@ def chat(
# 部分模型(如MiniMax M2.5)会在content中包含<think>思考内容,需要移除
content = re.sub(r'<think>[\s\S]*?</think>', '', content).strip()
return content

def chat_json(
"""
....def chat_json(
self,
messages: List[Dict[str, str]],
temperature: float = 0.3,
max_tokens: int = 4096
) -> Dict[str, Any]:
"""
"""
发送聊天请求并返回JSON

Args:
Expand All @@ -84,6 +86,7 @@ def chat_json(
Returns:
解析后的JSON对象
"""
"""
response = self.chat(
messages=messages,
temperature=temperature,
Expand All @@ -99,5 +102,38 @@ def chat_json(
try:
return json.loads(cleaned_response)
except json.JSONDecodeError:
raise ValueError(f"LLM返回的JSON格式无效: {cleaned_response}")
raise ValueError(f"LLM返回的JSON格式无效: {cleaned_response}")....."""

def chat_json(
self,
messages: List[Dict[str, str]],
temperature: float = 0.3,
max_tokens: int = 4096
) -> Dict[str, Any]:
# Try with json_object mode first, fall back if unsupported
try:
response = self.chat(
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
response_format={"type": "json_object"}
)
except Exception:
# Model doesn't support response_format, call without it
response = self.chat(
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)

# Clean markdown fences
cleaned_response = response.strip()
cleaned_response = re.sub(r'^```(?:json)?\s*\n?', '', cleaned_response, flags=re.IGNORECASE)
cleaned_response = re.sub(r'\n?```\s*$', '', cleaned_response)
cleaned_response = cleaned_response.strip()

try:
return json.loads(cleaned_response)
except json.JSONDecodeError:
raise ValueError(f"LLM返回的JSON格式无效: {cleaned_response[:500]}")

3 changes: 2 additions & 1 deletion backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "mirofish-backend"
version = "0.1.0"
description = "MiroFish - 简洁通用的群体智能引擎,预测万物"
requires-python = ">=3.11"
requires-python = ">=3.11, <3.12"
license = { text = "AGPL-3.0" }
authors = [
{ name = "MiroFish Team" }
Expand All @@ -22,6 +22,7 @@ dependencies = [
# OASIS 社交媒体模拟
"camel-oasis==0.2.5",
"camel-ai==0.2.78",
"pillow==10.3.0",

# 文件处理
"PyMuPDF>=1.24.0",
Expand Down
Loading