Skip to content

Commit 848dfdd

Browse files
Merge pull request #148 from vamplabAI/cursor-rules
Updating Cursor Rules
2 parents 582c14e + c31fad4 commit 848dfdd

File tree

7 files changed

+1135
-42
lines changed

7 files changed

+1135
-42
lines changed

.cursor/rules/architecture.mdc

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
---
2+
description: Architectural rules and boundaries for SGR Agent Core
3+
globs: sgr_agent_core/**/*.py
4+
alwaysApply: true
5+
---
6+
7+
# Architectural Rules for SGR Agent Core
8+
9+
## General Architecture
10+
11+
The project uses **modular architecture with clear separation of concerns**. The framework implements Schema-Guided Reasoning (SGR) for building intelligent research agents.
12+
13+
## Core Architecture Layers
14+
15+
### Layer 1: Base Classes (No Dependencies)
16+
- `BaseAgent` - Base class for all agents
17+
- `BaseTool` - Base class for all tools (Pydantic models)
18+
- `MCPBaseTool` - Base class for MCP-integrated tools
19+
- `models.py` - Core data models (AgentContext, AgentStatesEnum, etc.)
20+
21+
### Layer 2: Configuration and Registry
22+
- `agent_config.py` - GlobalConfig singleton
23+
- `agent_definition.py` - AgentDefinition, AgentConfig, LLMConfig, etc.
24+
- `services/registry.py` - AgentRegistry, ToolRegistry
25+
- `services/prompt_loader.py` - PromptLoader service
26+
27+
### Layer 3: Factory and Services
28+
- `agent_factory.py` - AgentFactory for creating agents
29+
- `services/mcp_service.py` - MCP2ToolConverter
30+
- `services/tavily_search.py` - Tavily search service
31+
- `next_step_tool.py` - NextStepToolsBuilder, NextStepToolStub
32+
33+
### Layer 4: Agent Implementations
34+
- `agents/sgr_agent.py` - SGRAgent (Structured Output)
35+
- `agents/tool_calling_agent.py` - ToolCallingAgent (Function Calling)
36+
- `agents/sgr_tool_calling_agent.py` - SGRToolCallingAgent (Hybrid)
37+
38+
### Layer 5: Tools
39+
- `tools/reasoning_tool.py` - ReasoningTool
40+
- `tools/clarification_tool.py` - ClarificationTool
41+
- `tools/web_search_tool.py` - WebSearchTool
42+
- `tools/extract_page_content_tool.py` - ExtractPageContentTool
43+
- `tools/generate_plan_tool.py` - GeneratePlanTool
44+
- `tools/adapt_plan_tool.py` - AdaptPlanTool
45+
- `tools/create_report_tool.py` - CreateReportTool
46+
- `tools/final_answer_tool.py` - FinalAnswerTool
47+
48+
### Layer 6: Server and API
49+
- `server/app.py` - FastAPI application
50+
- `server/endpoints.py` - API endpoints
51+
- `server/models.py` - API request/response models
52+
- `server/settings.py` - Server settings
53+
- `stream.py` - OpenAIStreamingGenerator
54+
55+
## Agent Execution Cycle
56+
57+
All agents follow a two-phase cycle:
58+
59+
```python
60+
while agent.state not in FINISH_STATES:
61+
reasoning = await agent._reasoning_phase()
62+
action_tool = await agent._select_action_phase(reasoning)
63+
await agent._action_phase(action_tool)
64+
```
65+
66+
### Phase 1: Reasoning Phase
67+
- Agent analyzes current context
68+
- Decides on next action
69+
- Implementation varies by agent type (SO, FC, or Hybrid)
70+
71+
### Phase 2: Select Action Phase
72+
- Selects appropriate tool based on reasoning
73+
- Returns tool instance ready for execution
74+
75+
### Phase 3: Action Phase
76+
- Executes selected tool
77+
- Updates conversation history
78+
- Updates agent context
79+
80+
## Module Rules
81+
82+
### Agents (`sgr_agent_core/agents/`)
83+
- Must inherit from `BaseAgent`
84+
- Must implement `_reasoning_phase()`, `_select_action_phase()`, `_action_phase()`
85+
- Automatically registered in `AgentRegistry` via `AgentRegistryMixin`
86+
- Can override `_prepare_context()` and `_prepare_tools()` for customization
87+
88+
### Tools (`sgr_agent_core/tools/`)
89+
- Must inherit from `BaseTool` or `MCPBaseTool`
90+
- Must be Pydantic models
91+
- Must implement `__call__()` method
92+
- Automatically registered in `ToolRegistry` via `ToolRegistryMixin`
93+
- Return string or JSON string from `__call__()`
94+
95+
### Services (`sgr_agent_core/services/`)
96+
- Stateless utility classes
97+
- Provide shared functionality (prompts, MCP, search)
98+
- No direct dependencies on agents or tools
99+
100+
### Configuration (`agent_config.py`, `agent_definition.py`)
101+
- Hierarchical configuration: GlobalConfig → AgentDefinition → AgentConfig
102+
- Supports YAML loading
103+
- Automatic inheritance and override of settings
104+
105+
## Design Principles
106+
107+
1. **One class at a time**: When implementing new functionality, create one class at a time, starting from lower layers
108+
2. **Minimal dependencies**: Each module should depend only on lower layer modules
109+
3. **Type hints**: Use type hints for all functions and methods
110+
4. **Async-first**: All I/O operations must be async
111+
5. **Registry pattern**: Use registries for automatic discovery of agents and tools
112+
6. **Configuration over code**: Prefer YAML configuration over hardcoded values
113+
114+
## References
115+
116+
@docs/en/framework/main-concepts.md
117+
@docs/en/framework/agents.md
118+
@README.md

.cursor/rules/code-style.mdc

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
description: Code style and formatting rules for SGR Agent Core
3+
globs: **/*.py
4+
alwaysApply: true
5+
---
6+
7+
# Code Style Rules
8+
9+
## General Rules
10+
11+
1. **Comments**: Write all code comments **ONLY in English**
12+
2. **User responses**: Respond in Russian unless user requests otherwise
13+
3. **Empty line at end of file**: Always add an empty line at the end of new files
14+
4. **Virtual environment**: Virtual environment is located in `.venv` directory
15+
16+
## Code Formatting
17+
18+
### Ruff and Black
19+
- Use `ruff` for linting and formatting
20+
- Line length: **120 characters** (configured in `pyproject.toml`)
21+
- Follow rules from `pyproject.toml` and `.ruff.toml` if present
22+
23+
### Imports
24+
- Use `isort` for import sorting
25+
- Group imports: standard library → third-party → local
26+
- One import per line for long lists
27+
28+
### Type Hints
29+
- **Mandatory**: Use type hints for all functions and methods
30+
- Prefer `T | None` over `Optional[T]` (Python 3.10+)
31+
- Use `Union[A, B]` for complex types when needed
32+
- Use `dict[str, Any]` instead of `Dict[str, Any]` (Python 3.9+)
33+
34+
### Docstrings
35+
- Use docstrings in Google style format
36+
- All docstrings in **English**
37+
- Must document:
38+
- Public classes and methods
39+
- Complex business logic
40+
- Parameters and return values
41+
42+
Example:
43+
```python
44+
def create_agent(self, agent_def: AgentDefinition, task_messages: list[dict]) -> BaseAgent:
45+
"""
46+
Create an agent instance from a definition.
47+
48+
Args:
49+
agent_def: Agent definition with configuration
50+
task_messages: Task messages in OpenAI format
51+
52+
Returns:
53+
Created agent instance
54+
"""
55+
```
56+
57+
## File Structure
58+
59+
### Element Order in File
60+
1. Module docstring
61+
2. Imports (standard library → third-party → local)
62+
3. Constants
63+
4. Types and exceptions
64+
5. Classes and functions
65+
66+
### Naming
67+
- **Classes**: PascalCase (`SGRAgent`, `BaseTool`)
68+
- **Functions and methods**: snake_case (`create_agent`, `_prepare_context`)
69+
- **Constants**: UPPER_SNAKE_CASE (`MAX_ITERATIONS`)
70+
- **Private methods**: start with `_` (`_reasoning_phase`, `_log_reasoning`)
71+
- **Types**: PascalCase (`AgentContext`, `AgentDefinition`)
72+
73+
## Error Handling
74+
75+
- Use specific exceptions, not generic `Exception`
76+
- Create custom exceptions for business logic when needed
77+
- Always include informative error messages
78+
- Use `Optional` or `| None` for values that may be missing
79+
80+
## Async/Await
81+
82+
- Use `async def` for all asynchronous operations
83+
- Use `await` for all async calls
84+
- Don't use blocking I/O in async code
85+
- Use `httpx` instead of `requests` for async HTTP calls
86+
87+
## FastAPI-Specific Guidelines
88+
89+
- Avoid global scope variables, use application state
90+
- Use functional components and Pydantic models for validation
91+
- Use declarative route definitions with clear return type annotations
92+
- Use `async def` for asynchronous endpoints
93+
- Use Pydantic's `BaseModel` for input/output validation
94+
- Use `HTTPException` for expected errors
95+
96+
## References
97+
98+
@pyproject.toml
99+
@pytest.ini

.cursor/rules/core-modules.mdc

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
---
2+
description: Rules for core modules of SGR Agent Core
3+
globs: sgr_agent_core/**/*.py
4+
alwaysApply: true
5+
---
6+
7+
# Rules for Core Modules
8+
9+
## Base Classes
10+
11+
### BaseAgent (`sgr_agent_core/base_agent.py`)
12+
- Parent class for all agents
13+
- Implements two-phase execution cycle: Reasoning → Action
14+
- Manages agent context, conversation history, and streaming
15+
- Must be subclassed to implement `_reasoning_phase()`, `_select_action_phase()`, `_action_phase()`
16+
- Automatically registered in `AgentRegistry` via `AgentRegistryMixin`
17+
18+
### BaseTool (`sgr_agent_core/base_tool.py`)
19+
- Parent class for all tools
20+
- Must be a Pydantic model
21+
- Must implement `__call__(context, config)` method
22+
- Returns string or JSON string
23+
- Automatically registered in `ToolRegistry` via `ToolRegistryMixin`
24+
25+
### MCPBaseTool (`sgr_agent_core/base_tool.py`)
26+
- Base class for MCP-integrated tools
27+
- Handles MCP client calls
28+
- Converts MCP responses to tool format
29+
30+
## Configuration Modules
31+
32+
### GlobalConfig (`sgr_agent_core/agent_config.py`)
33+
- Singleton pattern for global configuration
34+
- Loads from YAML files (`config.yaml`, `agents.yaml`)
35+
- Provides default values for all agent settings
36+
37+
### AgentDefinition (`sgr_agent_core/agent_definition.py`)
38+
- Definition template for creating agents
39+
- Contains: name, base_class, tools, llm, prompts, execution, search, mcp configs
40+
- Supports YAML loading
41+
- Validates required fields
42+
43+
### AgentConfig (`sgr_agent_core/agent_definition.py`)
44+
- Runtime configuration for agent instance
45+
- Combines: LLMConfig, SearchConfig, ExecutionConfig, PromptsConfig, MCPConfig
46+
- Supports hierarchical inheritance from GlobalConfig
47+
48+
## Factory and Services
49+
50+
### AgentFactory (`sgr_agent_core/agent_factory.py`)
51+
- Creates agent instances from AgentDefinition
52+
- Resolves agent classes from AgentRegistry
53+
- Resolves tools from ToolRegistry
54+
- Builds MCP tools via MCP2ToolConverter
55+
- Creates OpenAI client with proxy support
56+
57+
### AgentRegistry (`sgr_agent_core/services/registry.py`)
58+
- Centralized registry for agent classes
59+
- Automatic registration via `AgentRegistryMixin`
60+
- Supports lookup by name (case-insensitive)
61+
62+
### ToolRegistry (`sgr_agent_core/services/registry.py`)
63+
- Centralized registry for tool classes
64+
- Automatic registration via `ToolRegistryMixin`
65+
- Supports lookup by name (case-insensitive)
66+
67+
### PromptLoader (`sgr_agent_core/services/prompt_loader.py`)
68+
- Loads and formats prompts from files or strings
69+
- Generates system prompts with tool descriptions
70+
- Formats initial user requests and clarification responses
71+
72+
### MCP2ToolConverter (`sgr_agent_core/services/mcp_service.py`)
73+
- Converts MCP server tools to BaseTool instances
74+
- Handles MCP client initialization
75+
- Builds tools from MCP configuration
76+
77+
## Agent Implementations
78+
79+
### SGRAgent (`sgr_agent_core/agents/sgr_agent.py`)
80+
- Uses Structured Output approach
81+
- Creates dynamic JSON schema for tools
82+
- LLM returns reasoning + tool schema in one call
83+
- Extracts tool directly from reasoning result
84+
85+
### ToolCallingAgent (`sgr_agent_core/agents/tool_calling_agent.py`)
86+
- Uses native Function Calling
87+
- No explicit reasoning phase
88+
- Uses `tool_choice="required"` for tool selection
89+
- Best for advanced LLM models
90+
91+
### SGRToolCallingAgent (`sgr_agent_core/agents/sgr_tool_calling_agent.py`)
92+
- Hybrid approach: SGR + Function Calling
93+
- Uses ReasoningTool for explicit reasoning
94+
- Uses Function Calling for tool selection
95+
- Best balance for most tasks
96+
97+
## Tools
98+
99+
### ReasoningTool (`sgr_agent_core/tools/reasoning_tool.py`)
100+
- Provides structured reasoning output
101+
- Contains: reasoning_steps, current_situation, plan_status, enough_data, remaining_steps, task_completed
102+
103+
### ClarificationTool (`sgr_agent_core/tools/clarification_tool.py`)
104+
- Requests clarification from user
105+
- Pauses agent execution
106+
- Waits for user input via `provide_clarification()`
107+
108+
### WebSearchTool (`sgr_agent_core/tools/web_search_tool.py`)
109+
- Performs web search via Tavily API
110+
- Returns search results with sources
111+
- Respects max_searches limit
112+
113+
### ExtractPageContentTool (`sgr_agent_core/tools/extract_page_content_tool.py`)
114+
- Extracts content from web pages
115+
- Uses Tavily API for content extraction
116+
- Respects content_limit
117+
118+
### GeneratePlanTool (`sgr_agent_core/tools/generate_plan_tool.py`)
119+
- Generates research plan
120+
- Defines research goal and steps
121+
- Provides search strategies
122+
123+
### AdaptPlanTool (`sgr_agent_core/tools/adapt_plan_tool.py`)
124+
- Adapts existing plan based on new information
125+
- Updates research goal and steps
126+
- Modifies search strategies
127+
128+
### CreateReportTool (`sgr_agent_core/tools/create_report_tool.py`)
129+
- Creates final research report
130+
- Saves report to file
131+
- Formats report with sources
132+
133+
### FinalAnswerTool (`sgr_agent_core/tools/final_answer_tool.py`)
134+
- Provides final answer to user
135+
- Completes agent execution
136+
- Sets agent state to COMPLETED
137+
138+
## Server and API
139+
140+
### FastAPI Application (`sgr_agent_core/server/app.py`)
141+
- Main FastAPI application
142+
- Configures CORS, middleware
143+
- Registers endpoints
144+
145+
### API Endpoints (`sgr_agent_core/server/endpoints.py`)
146+
- `/v1/chat/completions` - OpenAI-compatible chat endpoint
147+
- `/v1/agents/{agent_id}/state` - Get agent state
148+
- `/v1/agents/{agent_id}/clarification` - Provide clarification
149+
- `/v1/agents` - List available agents
150+
151+
### Streaming (`sgr_agent_core/stream.py`)
152+
- OpenAIStreamingGenerator for streaming responses
153+
- Formats events in OpenAI-compatible format
154+
- Handles tool calls and content chunks
155+
156+
## General Rules for All Modules
157+
158+
1. **Type hints**: Use type hints everywhere
159+
2. **Async**: All I/O operations must be async
160+
3. **Documentation**: Document public methods in English
161+
4. **Error handling**: Use specific exceptions
162+
5. **Registry**: Use registry pattern for discovery
163+
6. **Configuration**: Prefer YAML over hardcoded values
164+
165+
## References
166+
167+
@architecture.mdc
168+
@code-style.mdc
169+
@docs/en/framework/main-concepts.md

0 commit comments

Comments
 (0)