ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,349 @@
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic.fields import FieldInfo
|
||||
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.logs.util import Color
|
||||
from aworld.models.llm import call_llm_model, get_llm_model
|
||||
from examples.gaia.mcp_collections.base import ActionArguments, ActionCollection, ActionResponse
|
||||
|
||||
|
||||
class CodeGenerationMetadata(BaseModel):
|
||||
"""Metadata for code generation results."""
|
||||
|
||||
model_name: str | None = None
|
||||
code_style: str | None = None
|
||||
code_length: int | None = None
|
||||
line_count: int | None = None
|
||||
processing_time_seconds: float | None = None
|
||||
temperature: float | None = None
|
||||
has_requirements: bool | None = None
|
||||
has_context: bool | None = None
|
||||
saved_file_path: str | None = None
|
||||
file_save_error: str | None = None
|
||||
error_type: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class CodeCollection(ActionCollection):
|
||||
"""MCP service for generating executable Python code snippets using LLM.
|
||||
|
||||
Supports code generation for:
|
||||
- Data processing and analysis tasks
|
||||
- Algorithm implementations
|
||||
- Utility functions and scripts
|
||||
- Problem-solving code snippets
|
||||
- Educational programming examples
|
||||
"""
|
||||
|
||||
def __init__(self, arguments: ActionArguments) -> None:
|
||||
super().__init__(arguments)
|
||||
|
||||
# Initialize code generation model configuration
|
||||
self._llm_config = AgentConfig(
|
||||
llm_provider="openai",
|
||||
llm_model_name=os.getenv("CODE_LLM_MODEL_NAME", "anthropic/claude-sonnet-4"),
|
||||
llm_api_key=os.getenv("CODE_LLM_API_KEY"),
|
||||
llm_base_url=os.getenv("CODE_LLM_BASE_URL"),
|
||||
)
|
||||
|
||||
self._color_log("Code Generation Service initialized", Color.green, "debug")
|
||||
self._color_log(f"Using model: {self._llm_config.llm_model_name}", Color.blue, "debug")
|
||||
|
||||
def _prepare_code_prompt(self, task_description: str, requirements: str = "", context: str = "") -> str:
|
||||
"""Prepare the code generation prompt with task description and optional requirements.
|
||||
|
||||
Args:
|
||||
task_description: The main task for code generation
|
||||
requirements: Optional specific requirements or constraints
|
||||
context: Optional additional context or background information
|
||||
|
||||
Returns:
|
||||
Formatted prompt string
|
||||
"""
|
||||
prompt_parts = [f"Task: {task_description}"]
|
||||
|
||||
if requirements:
|
||||
prompt_parts.append(f"Requirements: {requirements}")
|
||||
|
||||
if context:
|
||||
prompt_parts.append(f"Context: {context}")
|
||||
|
||||
return "\n\n".join(prompt_parts)
|
||||
|
||||
def _call_code_model(self, prompt: str, temperature: float = 0.1) -> str:
|
||||
"""Call the code generation model with the prepared prompt.
|
||||
|
||||
Args:
|
||||
prompt: The formatted prompt for code generation
|
||||
temperature: Model temperature for response variability
|
||||
|
||||
Returns:
|
||||
Generated code from the model
|
||||
|
||||
Raises:
|
||||
Exception: If model call fails
|
||||
"""
|
||||
response = call_llm_model(
|
||||
llm_model=get_llm_model(conf=self._llm_config),
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You are an expert Python programmer. Generate clean, efficient, and "
|
||||
"well-documented Python code that solves the given task. "
|
||||
"Include proper error handling and follow Python best practices. "
|
||||
"Return only executable Python code with minimal explanatory comments."
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
return response.content
|
||||
|
||||
def _extract_python_code(self, response: str) -> str:
|
||||
"""Extract Python code from the model response.
|
||||
|
||||
Args:
|
||||
response: Raw response from the model
|
||||
|
||||
Returns:
|
||||
Extracted Python code
|
||||
"""
|
||||
# Remove markdown code blocks if present
|
||||
lines = response.strip().split("\n")
|
||||
|
||||
# Find code block boundaries
|
||||
start_idx = 0
|
||||
end_idx = len(lines)
|
||||
|
||||
for i, line in enumerate(lines):
|
||||
if line.strip().startswith("```python") or line.strip().startswith("```"):
|
||||
start_idx = i + 1
|
||||
break
|
||||
|
||||
for i in range(len(lines) - 1, -1, -1):
|
||||
if lines[i].strip() == "```":
|
||||
end_idx = i
|
||||
break
|
||||
|
||||
# Extract the code
|
||||
code_lines = lines[start_idx:end_idx]
|
||||
return "\n".join(code_lines).strip()
|
||||
|
||||
def mcp_generate_python_code(
|
||||
self,
|
||||
task_description: str = Field(description="Description of the programming task or problem to solve"),
|
||||
requirements: str = Field(
|
||||
default="", description="Specific requirements, constraints, or specifications for the code"
|
||||
),
|
||||
context: str = Field(default="", description="Additional context or background information"),
|
||||
temperature: float = Field(
|
||||
default=0.1,
|
||||
description="Model temperature for code generation (0.0-1.0, lower = more deterministic)",
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
),
|
||||
code_style: Literal["minimal", "documented", "verbose"] = Field(
|
||||
default="documented",
|
||||
description="Style of generated code: minimal (concise), documented (with comments), verbose (detailed)",
|
||||
),
|
||||
save_to_file_path: str | None = Field(
|
||||
default=None,
|
||||
description="Optional. Path to save the generated Python snippet. e.g., 'output/generated_script.py'",
|
||||
),
|
||||
) -> ActionResponse:
|
||||
"""Generate executable Python code snippets based on task description.
|
||||
|
||||
This tool provides comprehensive code generation capabilities for:
|
||||
- Solve simple math tasks and validations
|
||||
- Data processing and analysis tasks
|
||||
- Algorithm implementations and optimizations
|
||||
- Utility functions and helper scripts
|
||||
- Problem-solving code snippets
|
||||
- Educational programming examples
|
||||
- API integrations and automation scripts
|
||||
|
||||
Strengths:
|
||||
- Generates clean, executable Python code
|
||||
- Follows modern Python best practices (>=3.11)
|
||||
- Includes proper error handling
|
||||
- Supports various coding styles and complexity levels
|
||||
|
||||
Limitations:
|
||||
- Cannot execute or test the generated code
|
||||
- May require manual adjustments for specific environments
|
||||
- Limited to Python programming language
|
||||
|
||||
Args:
|
||||
task_description: Clear description of the programming task
|
||||
requirements: Specific requirements or constraints
|
||||
context: Additional context or background information
|
||||
temperature: Model temperature controlling randomness
|
||||
code_style: Style preference for the generated code
|
||||
save_to_file_path: Optional. If provided, saves the generated code to this path within the workspace.
|
||||
|
||||
Returns:
|
||||
ActionResponse with generated Python code and metadata
|
||||
"""
|
||||
try:
|
||||
# Handle FieldInfo objects
|
||||
if isinstance(task_description, FieldInfo):
|
||||
task_description = task_description.default
|
||||
if isinstance(requirements, FieldInfo):
|
||||
requirements = requirements.default
|
||||
if isinstance(context, FieldInfo):
|
||||
context = context.default
|
||||
if isinstance(temperature, FieldInfo):
|
||||
temperature = temperature.default
|
||||
if isinstance(code_style, FieldInfo):
|
||||
code_style = code_style.default
|
||||
if isinstance(save_to_file_path, FieldInfo):
|
||||
save_to_file_path = save_to_file_path.default
|
||||
|
||||
# Validate input
|
||||
if not task_description or not task_description.strip():
|
||||
raise ValueError("Task description is required for code generation")
|
||||
|
||||
self._color_log(f"Generating code for: {task_description[:100]}...", Color.cyan)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# Prepare the code generation prompt
|
||||
prompt = self._prepare_code_prompt(task_description, requirements, context)
|
||||
|
||||
# Enhance prompt based on code style
|
||||
if code_style == "minimal":
|
||||
prompt += "\n\nGenerate concise, minimal code without extensive comments."
|
||||
elif code_style == "verbose":
|
||||
prompt += "\n\nGenerate detailed code with comprehensive comments and explanations."
|
||||
elif code_style == "documented":
|
||||
prompt += "\n\nGenerate well-documented code with clear comments and docstrings."
|
||||
|
||||
# Call the code generation model
|
||||
raw_response = self._call_code_model(prompt, temperature)
|
||||
|
||||
# Extract clean Python code
|
||||
generated_code = self._extract_python_code(raw_response)
|
||||
|
||||
processing_time = time.time() - start_time
|
||||
|
||||
# Populate metadata fields
|
||||
metadata = CodeGenerationMetadata(
|
||||
model_name=self._llm_config.llm_model_name,
|
||||
code_style=code_style,
|
||||
code_length=len(generated_code),
|
||||
line_count=len(generated_code.split("\n")),
|
||||
processing_time_seconds=round(processing_time, 2),
|
||||
temperature=temperature,
|
||||
has_requirements=bool(requirements.strip()),
|
||||
has_context=bool(context.strip()),
|
||||
)
|
||||
|
||||
# Save the generated code to a file if path is provided
|
||||
if save_to_file_path:
|
||||
try:
|
||||
# Use _validate_file_path to ensure path is within workspace and get absolute path
|
||||
# The check_existence=False allows creating a new file.
|
||||
output_file_path_obj = Path(self._validate_file_path(save_to_file_path))
|
||||
|
||||
# Ensure parent directories exist
|
||||
output_file_path_obj.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_file_path_obj, "w", encoding="utf-8") as f:
|
||||
f.write(generated_code)
|
||||
|
||||
metadata.saved_file_path = str(output_file_path_obj)
|
||||
self._color_log(f"Generated code also saved to: {output_file_path_obj}", Color.blue)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to save code to file '{save_to_file_path}': {str(e)}")
|
||||
metadata.file_save_error = str(e)
|
||||
|
||||
self._color_log(
|
||||
f"Successfully generated code ({metadata.code_length} characters, "
|
||||
f"{metadata.processing_time_seconds:.2f}s)",
|
||||
Color.green,
|
||||
)
|
||||
|
||||
return ActionResponse(success=True, message=generated_code, metadata=metadata.model_dump(exclude_none=True))
|
||||
|
||||
except ValueError as e:
|
||||
self.logger.error(f"Invalid input: {str(e)}")
|
||||
metadata.error_type = "invalid_input"
|
||||
metadata.error_message = str(e)
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Invalid input: {str(e)}",
|
||||
metadata=metadata.model_dump(exclude_none=True),
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Code generation failed: {str(e)}: {traceback.format_exc()}")
|
||||
metadata.error_type = "generation_error"
|
||||
metadata.error_message = str(e)
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Code generation failed: {str(e)}",
|
||||
metadata=metadata.model_dump(exclude_none=True),
|
||||
)
|
||||
|
||||
def mcp_get_code_capabilities(self) -> ActionResponse:
|
||||
"""Get information about the code generation service capabilities.
|
||||
|
||||
Returns:
|
||||
ActionResponse with service capabilities and configuration
|
||||
"""
|
||||
capabilities = {
|
||||
"Data Processing": "Generate code for data manipulation, analysis, and visualization",
|
||||
"Algorithm Implementation": "Create efficient algorithms and data structures",
|
||||
"Utility Functions": "Build helper functions and reusable code components",
|
||||
"Problem Solving": "Generate solutions for programming challenges and tasks",
|
||||
"API Integration": "Create code for working with APIs and web services",
|
||||
"Automation Scripts": "Build scripts for task automation and workflow optimization",
|
||||
}
|
||||
|
||||
capability_list = "\n".join(
|
||||
[f"**{capability}**: {description}" for capability, description in capabilities.items()]
|
||||
)
|
||||
|
||||
metadata = {
|
||||
"model_name": self._llm_config.llm_model_name,
|
||||
"provider": self._llm_config.llm_provider,
|
||||
"supported_capabilities": list(capabilities.keys()),
|
||||
"total_capabilities": len(capabilities),
|
||||
"code_styles": ["minimal", "documented", "verbose"],
|
||||
"python_version": ">=3.11",
|
||||
"supported_language": "Python",
|
||||
}
|
||||
|
||||
return ActionResponse(
|
||||
success=True,
|
||||
message=f"Code Generation Service Capabilities:\n\n{capability_list}",
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
# Example usage and entry point
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
|
||||
# Default arguments for testing
|
||||
args = ActionArguments(
|
||||
name="code_generation_service",
|
||||
transport="stdio",
|
||||
workspace=os.getenv("AWORLD_WORKSPACE", "~"),
|
||||
)
|
||||
|
||||
# Initialize and run the code generation service
|
||||
try:
|
||||
service = CodeCollection(args)
|
||||
service.run()
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}: {traceback.format_exc()}")
|
||||
@@ -0,0 +1,260 @@
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from typing import Literal
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
from pydantic.fields import FieldInfo
|
||||
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.logs.util import Color
|
||||
from aworld.models.llm import call_llm_model, get_llm_model
|
||||
from examples.gaia.mcp_collections.base import ActionArguments, ActionCollection, ActionResponse
|
||||
|
||||
|
||||
class GuardCollection(ActionCollection):
|
||||
"""MCP service for diagnosing and correcting (if necessary) the reasoning/thinking process already existed in the currect context, or avoid the potential loopholes in the future, towards solving the complex problem correctly, through powerful guarding model with sophisticated experience.
|
||||
The MUST Choice for the Thinking Process Reviewing phase, good at diagnosing the reasoning process in the context or giving valuable suggestions in advance.
|
||||
|
||||
Supports advanced guarding for reasoning process:
|
||||
- Identify potential loopholes or oversights in the reasoning process already existed in the currect context, while solving the complex problem.
|
||||
- If necessary, provide the corresponding supplements or guidance to the reasoning process in advance, to maneuver the reasoning/thinking process towards solving the complex problem in a proper direction.
|
||||
"""
|
||||
|
||||
def __init__(self, arguments: ActionArguments) -> None:
|
||||
super().__init__(arguments)
|
||||
env_path = "/Users/zhitianxie/PycharmProjects/AWorld_gaia_July/AWorld/examples/gaia/cmd/agent_deploy/gaia_agent/.env"
|
||||
load_dotenv(env_path, override=True, verbose=True)
|
||||
|
||||
# Initialize guarding model configuration
|
||||
self._llm_config = AgentConfig(
|
||||
llm_provider="openai",
|
||||
# llm_model_name="google/gemini-2.5-flash-preview-05-20:thinking",
|
||||
llm_model_name=os.getenv("GUARD_LLM_MODEL_NAME", "deepseek/deepseek-r1-0528:free"),
|
||||
llm_api_key=os.getenv("GUARD_LLM_API_KEY"),
|
||||
llm_base_url=os.getenv("GUARD_LLM_BASE_URL"),
|
||||
)
|
||||
|
||||
self._color_log("Intelligence Guard Service initialized", Color.green, "debug")
|
||||
self._color_log(f"Using model: {self._llm_config.llm_model_name}", Color.blue, "debug")
|
||||
|
||||
def _prepare_guarding_prompt(self, question: str, original_task: str = "") -> str:
|
||||
"""Prepare the guarding prompt with question and optional context.
|
||||
|
||||
Args:
|
||||
question: The main question for guarding the reasoning process, such as 'is there any potential loopholes or oversights in the reasoning process?'
|
||||
original_task: Optional original task description for context
|
||||
|
||||
Returns:
|
||||
Formatted prompt string
|
||||
"""
|
||||
if original_task:
|
||||
return f"Original Task: {original_task}\n\nQuestion: {question}"
|
||||
return f"Question: {question}"
|
||||
|
||||
def _call_guarding_model(self, prompt: str, temperature: float = 0.1) -> str:
|
||||
"""Call the guarding model with the prepared prompt.
|
||||
|
||||
Args:
|
||||
prompt: The formatted prompt for guarding the reasoning process
|
||||
temperature: Model temperature for response variability
|
||||
|
||||
Returns:
|
||||
guarding result from the model
|
||||
|
||||
Raises:
|
||||
Exception: If model call fails
|
||||
"""
|
||||
response = call_llm_model(
|
||||
llm_model=get_llm_model(conf=self._llm_config),
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"## Your Role\n"
|
||||
"You are an expert at identifying the potential loopholes or oversights"
|
||||
"of the current reasoning process while solving the complex problem.\n\n "
|
||||
"## Your Task: \n"
|
||||
"Based on the gathered information retrieved from the internet, and the reasoning process already"
|
||||
"generated towards solving a complex task, you need to do the following 1 or 2 things, to guarntee the quality of the reasoning process, and a clear final answer: \n"
|
||||
" 1. Provide your diagnosing result on the generated reasoning process and the corresponding the correction if necessary;\n"
|
||||
" 2. Provide your insight and supplements in advance to avoid the potential loopholes or oversights in the future;\n\n"
|
||||
"## Requirements: \n"
|
||||
" 1. If the reasoning process already generated is complete and correct in your opinion, just say 'No loopholes or oversights found'. \n"
|
||||
" 2. If the reasoning process already generated contains the materials that may lead to the potential logic mistake or lack of some important guardrails in your opinion, you may give a hint to the current reasoning process, with the necessary supplements.\n"
|
||||
" 3. If the reasoning process already generated is seriously incorrect in your opinion, you may give the turn signal to the reasoning process, to maneuver the reasoning process towards solving the complex problem correctly. \n\n"
|
||||
"## Restriction: \n"
|
||||
" 1. Please do not make judgments about the authenticity of externally sourced information obtained through searches, as this is not part of your job responsibilities;\n"
|
||||
" 2. Do not make additional inferences or assumptions about the content of such information itself.\n"
|
||||
" 3. If the question lacks necessary details/data/clues in your opinion, you may ask for more details.\n\n"
|
||||
"## Example 1:\n"
|
||||
" Question: Is my reasoning process correct?\n"
|
||||
" Reasoning Process: (nothing specified)\n"
|
||||
" Your Identification Result: Your question lacks some information, please provide me more details so I can help you.\n\n"
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
return response.content
|
||||
|
||||
def mcp_guarding_reasoning_process(
|
||||
self,
|
||||
question: str = Field(
|
||||
description="The input question for diagnosing the completeness/correctness of the reasoning process.\n"
|
||||
"For example: based on the staged/phased information/data concluded as 1.xxxx 2. xxxx 3. xxxx...., is there any faults in the current reasoning process aaaaaa"
|
||||
"that should be corrected? Or is there any loopholes or oversights that should be emphized in advance, towards solving the bbbbb problem?\n"
|
||||
"Requirement: This input question should include a clear question with the necessary details/data/clues from the previous context"
|
||||
"(such as the key information/data retrieved from the internet), to present more clues to help the diagnosing process."
|
||||
"The more exact details/data contained in this input question, the better the diagnosing result will be."
|
||||
),
|
||||
original_task: str = Field(default="", description="The original task. This field is required and cannot be simplied, has to be true to the original task."),
|
||||
temperature: float = Field(
|
||||
default=0.1,
|
||||
description="Model temperature for response variability (0.0-1.0)",
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
),
|
||||
guarding_style: Literal["detailed", "concise", "step-by-step"] = Field(
|
||||
default="detailed",
|
||||
description="Style of guarding output: detailed analysis, concise summary, or step-by-step breakdown",
|
||||
),
|
||||
) -> ActionResponse:
|
||||
"""This tool provides advanced logic diagonsing and correcting ability, to improve the quality of the reasoning process that already exists in the current context, while solving the complex question:
|
||||
- Identify potential loopholes or oversights in the current reasoning process while solving the complex problem.
|
||||
- Providing the guidance, suggestions to the reasoning process, to correct the loopholes or oversights if identified in this shot.
|
||||
|
||||
Invoke Timing: During Thinking Process Reviewing, while diagnosing the reasoning process in the context or give valuable suggestions in advance, this tool is a reliable selection.
|
||||
|
||||
Strengths:
|
||||
- Be relatively sensitive to common logical traps in some mathematics or logic problems.
|
||||
|
||||
Weakness:
|
||||
- Inability to process media types: image, audio, or video.
|
||||
- Inability to check the correctness of the retrieved information from the internet.
|
||||
- Require precise description of problem context and settings, including the reasoning process, retrieved data and the complex task itself.
|
||||
|
||||
Args:
|
||||
question: The input question that invokes this tool to diagnose and/or correct the suspected reasoning process in the context
|
||||
original_task: Optional original task description for additional context
|
||||
temperature: Model temperature controlling response variability
|
||||
guarding_style: Style of guarding output format
|
||||
|
||||
Returns:
|
||||
ActionResponse with guarding result and processing metadata
|
||||
"""
|
||||
try:
|
||||
# Handle FieldInfo objects
|
||||
if isinstance(question, FieldInfo):
|
||||
question = question.default
|
||||
if isinstance(original_task, FieldInfo):
|
||||
original_task = original_task.default
|
||||
if isinstance(temperature, FieldInfo):
|
||||
temperature = temperature.default
|
||||
if isinstance(guarding_style, FieldInfo):
|
||||
guarding_style = guarding_style.default
|
||||
|
||||
# Validate input
|
||||
if not question or not question.strip():
|
||||
raise ValueError("Question is required for guarding the complex problem reasoning process")
|
||||
|
||||
self._color_log(f"Processing guarding request: {question[:100]}...", Color.cyan)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# Prepare the guarding prompt
|
||||
prompt = self._prepare_guarding_prompt(question, original_task) ## 简单的原始问题+分配给mcp server的问题
|
||||
|
||||
# Enhance prompt based on guarding style
|
||||
if guarding_style == "step-by-step":
|
||||
prompt += "\n\nPlease provide a clear step-by-step breakdown of your reviewing process of the reasoning process."
|
||||
elif guarding_style == "concise":
|
||||
prompt += "\n\nPlease provide a concise and final guarding answer."
|
||||
elif guarding_style == "detailed":
|
||||
prompt += "\n\nPlease provide detailed reviewing analysis with comprehensive guarding."
|
||||
|
||||
# Call the guarding model
|
||||
guarding_result = self._call_guarding_model(prompt, temperature)
|
||||
|
||||
processing_time = time.time() - start_time
|
||||
|
||||
# Prepare metadata
|
||||
metadata = {
|
||||
"model_name": self._llm_config.llm_model_name,
|
||||
"guarding_style": guarding_style,
|
||||
"response_length": len(guarding_result),
|
||||
}
|
||||
|
||||
self._color_log(
|
||||
f"Successfully completed guarding ({len(guarding_result)} characters, {processing_time:.2f}s)",
|
||||
Color.green,
|
||||
)
|
||||
|
||||
return ActionResponse(success=True, message=guarding_result, metadata=metadata)
|
||||
|
||||
except ValueError as e:
|
||||
self.logger.error(f"Invalid input: {str(e)}")
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Invalid input: {str(e)}",
|
||||
metadata={"error_type": "invalid_input", "error_message": str(e)},
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Guarding failed: {str(e)}: {traceback.format_exc()}")
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Guarding failed: {str(e)}",
|
||||
metadata={"error_type": "guarding_error", "error_message": str(e)},
|
||||
)
|
||||
|
||||
def mcp_get_guarding_capabilities(self) -> ActionResponse:
|
||||
"""Get information about the guarding reasoning process service capabilities.
|
||||
|
||||
Returns:
|
||||
ActionResponse with service capabilities and configuration
|
||||
"""
|
||||
capabilities = {
|
||||
"Logic Loopholes Detecting": "Identifying the logic loopholes in the reasoning process already generated previsouly",
|
||||
"Detected Loopholes Correcting": "Correcting the logic loopholes identified in the reasoning process already generated previously",
|
||||
"Oversights Prevention": "Providing necessary supplements as hints to the currect reasoning process, to prevent the possible oversights in the future",
|
||||
}
|
||||
|
||||
capability_list = "\n".join(
|
||||
[f"**{capability}**: {description}" for capability, description in capabilities.items()]
|
||||
)
|
||||
|
||||
metadata = {
|
||||
"model_name": self._llm_config.llm_model_name,
|
||||
"provider": self._llm_config.llm_provider,
|
||||
"supported_capabilities": list(capabilities.keys()),
|
||||
"total_capabilities": len(capabilities),
|
||||
"guarding_styles": ["detailed", "concise", "step-by-step"],
|
||||
}
|
||||
|
||||
return ActionResponse(
|
||||
success=True,
|
||||
message=f"Intelligence guarding Service Capabilities:\n\n{capability_list}",
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
# Example usage and entry point
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
|
||||
# Default arguments for testing
|
||||
args = ActionArguments(
|
||||
name="intelligence_guarding_service",
|
||||
transport="stdio",
|
||||
workspace=os.getenv("AWORLD_WORKSPACE", "~"),
|
||||
)
|
||||
|
||||
# Initialize and run the intelligence guarding service
|
||||
try:
|
||||
service = GuardCollection(args)
|
||||
service.run()
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}: {traceback.format_exc()}")
|
||||
@@ -0,0 +1,237 @@
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from typing import Literal
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import Field
|
||||
from pydantic.fields import FieldInfo
|
||||
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.logs.util import Color
|
||||
from aworld.models.llm import call_llm_model, get_llm_model
|
||||
from examples.gaia.mcp_collections.base import ActionArguments, ActionCollection, ActionResponse
|
||||
|
||||
|
||||
class ThinkCollection(ActionCollection):
|
||||
"""MCP service for complex problem reasoning using powerful reasoning models.
|
||||
|
||||
Supports advanced reasoning for:
|
||||
- Mathematical problems and proofs
|
||||
- Code contest and programming challenges
|
||||
- Logic puzzles and riddles
|
||||
- Competition-level STEM problems
|
||||
- Multi-step analytical reasoning
|
||||
"""
|
||||
|
||||
def __init__(self, arguments: ActionArguments) -> None:
|
||||
super().__init__(arguments)
|
||||
|
||||
# Initialize reasoning model configuration
|
||||
self._llm_config = AgentConfig(
|
||||
llm_provider="openai",
|
||||
# llm_model_name="google/gemini-2.5-flash-preview-05-20:thinking",
|
||||
llm_model_name=os.getenv("THINK_LLM_MODEL_NAME", "deepseek/deepseek-r1-0528:free"),
|
||||
llm_api_key=os.getenv("THINK_LLM_API_KEY"),
|
||||
llm_base_url=os.getenv("THINK_LLM_BASE_URL"),
|
||||
)
|
||||
|
||||
self._color_log("Intelligence Reasoning Service initialized", Color.green, "debug")
|
||||
self._color_log(f"Using model: {self._llm_config.llm_model_name}", Color.blue, "debug")
|
||||
|
||||
def _prepare_reasoning_prompt(self, question: str, original_task: str = "") -> str:
|
||||
"""Prepare the reasoning prompt with question and optional context.
|
||||
|
||||
Args:
|
||||
question: The main question for reasoning
|
||||
original_task: Optional original task description for context
|
||||
|
||||
Returns:
|
||||
Formatted prompt string
|
||||
"""
|
||||
if original_task:
|
||||
return f"Original Task: {original_task}\n\nQuestion: {question}"
|
||||
return f"Question: {question}"
|
||||
|
||||
def _call_reasoning_model(self, prompt: str, temperature: float = 0.3) -> str:
|
||||
"""Call the reasoning model with the prepared prompt.
|
||||
|
||||
Args:
|
||||
prompt: The formatted prompt for reasoning
|
||||
temperature: Model temperature for response variability
|
||||
|
||||
Returns:
|
||||
Reasoning result from the model
|
||||
|
||||
Raises:
|
||||
Exception: If model call fails
|
||||
"""
|
||||
response = call_llm_model(
|
||||
llm_model=get_llm_model(conf=self._llm_config),
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You are an expert at solving complex problems including math, "
|
||||
"code contests, riddles, and puzzles. "
|
||||
"Provide detailed step-by-step reasoning and a clear final answer."
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
return response.content
|
||||
|
||||
def mcp_complex_problem_reasoning(
|
||||
self,
|
||||
question: str = Field(
|
||||
description="The input question for complex problem reasoning, such as math and code contest problems"
|
||||
),
|
||||
original_task: str = Field(default="", description="The original task description."),
|
||||
temperature: float = Field(
|
||||
default=0.3,
|
||||
description="Model temperature for response variability (0.0-1.0)",
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
),
|
||||
reasoning_style: Literal["detailed", "concise", "step-by-step"] = Field(
|
||||
default="detailed",
|
||||
description="Style of reasoning output: detailed analysis, concise summary, or step-by-step breakdown",
|
||||
),
|
||||
) -> ActionResponse:
|
||||
"""This tool provides comprehensive reasoning capabilities for:
|
||||
- Mathematical problems and proofs
|
||||
- Programming and algorithm challenges
|
||||
- Logic puzzles, brain teasers, and fun riddles
|
||||
- Competition-level STEM problems
|
||||
- Multi-step analytical reasoning tasks
|
||||
|
||||
Weakness:
|
||||
- Inability to process media types: image, audio, or video
|
||||
- Require precise description of problem context and settings
|
||||
|
||||
Args:
|
||||
question: The input question requiring complex reasoning
|
||||
original_task: Optional original task description for additional context
|
||||
temperature: Model temperature controlling response variability
|
||||
reasoning_style: Style of reasoning output format
|
||||
|
||||
Returns:
|
||||
ActionResponse with reasoning result and processing metadata
|
||||
"""
|
||||
try:
|
||||
# Handle FieldInfo objects
|
||||
if isinstance(question, FieldInfo):
|
||||
question = question.default
|
||||
if isinstance(original_task, FieldInfo):
|
||||
original_task = original_task.default
|
||||
if isinstance(temperature, FieldInfo):
|
||||
temperature = temperature.default
|
||||
if isinstance(reasoning_style, FieldInfo):
|
||||
reasoning_style = reasoning_style.default
|
||||
|
||||
# Validate input
|
||||
if not question or not question.strip():
|
||||
raise ValueError("Question is required for complex problem reasoning")
|
||||
|
||||
self._color_log(f"Processing reasoning request: {question[:100]}...", Color.cyan)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# Prepare the reasoning prompt
|
||||
prompt = self._prepare_reasoning_prompt(question, original_task)
|
||||
|
||||
# Enhance prompt based on reasoning style
|
||||
if reasoning_style == "step-by-step":
|
||||
prompt += "\n\nPlease provide a clear step-by-step breakdown of your reasoning process."
|
||||
elif reasoning_style == "concise":
|
||||
prompt += "\n\nPlease provide a concise but complete reasoning and final answer."
|
||||
elif reasoning_style == "detailed":
|
||||
prompt += "\n\nPlease provide detailed analysis with comprehensive reasoning."
|
||||
|
||||
# Call the reasoning model
|
||||
reasoning_result = self._call_reasoning_model(prompt, temperature)
|
||||
|
||||
processing_time = time.time() - start_time
|
||||
|
||||
# Prepare metadata
|
||||
metadata = {
|
||||
"model_name": self._llm_config.llm_model_name,
|
||||
"reasoning_style": reasoning_style,
|
||||
"response_length": len(reasoning_result),
|
||||
}
|
||||
|
||||
self._color_log(
|
||||
f"Successfully completed reasoning ({len(reasoning_result)} characters, {processing_time:.2f}s)",
|
||||
Color.green,
|
||||
)
|
||||
|
||||
return ActionResponse(success=True, message=reasoning_result, metadata=metadata)
|
||||
|
||||
except ValueError as e:
|
||||
self.logger.error(f"Invalid input: {str(e)}")
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Invalid input: {str(e)}",
|
||||
metadata={"error_type": "invalid_input", "error_message": str(e)},
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Reasoning failed: {str(e)}: {traceback.format_exc()}")
|
||||
return ActionResponse(
|
||||
success=False,
|
||||
message=f"Reasoning failed: {str(e)}",
|
||||
metadata={"error_type": "reasoning_error", "error_message": str(e)},
|
||||
)
|
||||
|
||||
def mcp_get_reasoning_capabilities(self) -> ActionResponse:
|
||||
"""Get information about the reasoning service capabilities.
|
||||
|
||||
Returns:
|
||||
ActionResponse with service capabilities and configuration
|
||||
"""
|
||||
capabilities = {
|
||||
"Mathematical Problems": "Advanced mathematical reasoning, proofs, and calculations",
|
||||
"Code Contests": "Programming challenges, algorithm design, and optimization",
|
||||
"Logic Puzzles": "Brain teasers, riddles, and logical reasoning problems",
|
||||
"STEM Problems": "Competition-level science, technology, engineering, and math",
|
||||
"Multi-step Analysis": "Complex analytical reasoning with multiple interconnected steps",
|
||||
}
|
||||
|
||||
capability_list = "\n".join(
|
||||
[f"**{capability}**: {description}" for capability, description in capabilities.items()]
|
||||
)
|
||||
|
||||
metadata = {
|
||||
"model_name": self._llm_config.llm_model_name,
|
||||
"provider": self._llm_config.llm_provider,
|
||||
"supported_capabilities": list(capabilities.keys()),
|
||||
"total_capabilities": len(capabilities),
|
||||
"reasoning_styles": ["detailed", "concise", "step-by-step"],
|
||||
}
|
||||
|
||||
return ActionResponse(
|
||||
success=True,
|
||||
message=f"Intelligence Reasoning Service Capabilities:\n\n{capability_list}",
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
# Example usage and entry point
|
||||
if __name__ == "__main__":
|
||||
load_dotenv()
|
||||
|
||||
# Default arguments for testing
|
||||
args = ActionArguments(
|
||||
name="intelligence_reasoning_service",
|
||||
transport="stdio",
|
||||
workspace=os.getenv("AWORLD_WORKSPACE", "~"),
|
||||
)
|
||||
|
||||
# Initialize and run the intelligence reasoning service
|
||||
try:
|
||||
service = ThinkCollection(args)
|
||||
service.run()
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}: {traceback.format_exc()}")
|
||||
Reference in New Issue
Block a user