Skip to content

Commit e321148

Browse files
authored
Merge pull request #48 from jongalloway/copilot/fix-37
🛠️ Implement Advanced Tool System with Search, Details, Compare, Ensemble, and Recipe Tools
2 parents de0a86b + 789346f commit e321148

14 files changed

+1576
-3
lines changed

.github/custom-instructions.md

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,38 +29,44 @@ This document provides guidance for AI assistants working with the NLWebNet code
2929
## Architecture Patterns
3030

3131
### 1. Minimal API Approach
32+
3233
- **Primary approach**: Uses **Minimal APIs** for modern, lightweight endpoints
3334
- **Legacy support**: Traditional controllers still present but being phased out
3435
- Endpoints are organized in static classes: `AskEndpoints`, `McpEndpoints`
3536
- Extension methods provide clean endpoint mapping: `app.MapNLWebNet()`
3637
- Both `app.MapNLWebNet()` (minimal APIs) and `app.MapNLWebNetControllers()` (legacy) available
3738

3839
### 2. Dependency Injection
40+
3941
- Follows standard .NET DI patterns
4042
- Extension methods for service registration: `services.AddNLWebNet()`
4143
- Interface-based design with clear service contracts
4244
- Supports custom backend implementations via generics
4345

4446
### 3. Service Layer Architecture
45-
```
47+
48+
```text
4649
Controllers/Endpoints → Services → Data Backends
4750
↘ MCP Integration
4851
```
4952

5053
Key interfaces:
54+
5155
- `INLWebService` - Main orchestration service
5256
- `IDataBackend` - Data retrieval abstraction
5357
- `IQueryProcessor` - Query processing logic
5458
- `IResultGenerator` - Response generation
5559
- `IMcpService` - Model Context Protocol integration
5660

5761
### 4. Configuration Pattern
62+
5863
- Uses `NLWebOptions` for strongly-typed configuration
5964
- Supports configuration binding from `appsettings.json`
6065
- User secrets for sensitive data (API keys)
6166
- Environment-specific configurations
6267

6368
### 5. Architectural Migration
69+
6470
**Important**: The project is transitioning from traditional MVC controllers to Minimal APIs.
6571

6672
- **Preferred**: Use `Endpoints/` classes with static mapping methods
@@ -71,6 +77,7 @@ Key interfaces:
7177
## Code Conventions
7278

7379
### Naming and Structure
80+
7481
- **Namespace**: All code under `NLWebNet` namespace
7582
- **Models**: Request/response DTOs with JSON serialization attributes
7683
- **Services**: Interface + implementation pattern (`IService``Service`)
@@ -79,14 +86,16 @@ Key interfaces:
7986
- **Controllers**: Traditional MVC controllers (legacy, being phased out)
8087

8188
### C# Style Guidelines
89+
8290
- **Nullable reference types** enabled (`<Nullable>enable</Nullable>`)
8391
- **Implicit usings** enabled for common namespaces
8492
- **XML documentation** for all public APIs
8593
- **Data annotations** for request validation
8694
- **JSON property names** in snake_case for protocol compliance
8795

8896
### File Organization
89-
```
97+
98+
```text
9099
src/NLWebNet/
91100
├── Models/ # Request/response DTOs
92101
├── Services/ # Business logic interfaces/implementations
@@ -100,58 +109,72 @@ src/NLWebNet/
100109
## NLWeb Protocol Implementation
101110

102111
### Core Concepts
112+
103113
- **Three query modes**: `List`, `Summarize`, `Generate`
104114
- **Streaming support**: Real-time response delivery
105115
- **Query context**: Previous queries and decontextualization
106116
- **Site filtering**: Subset targeting within data backends
107117

108118
### Request/Response Flow
119+
109120
1. Validate incoming `NLWebRequest`
110121
2. Process query through `IQueryProcessor`
111122
3. Retrieve data via `IDataBackend`
112123
4. Generate response using `IResultGenerator`
113124
5. Return `NLWebResponse` with results
114125

115126
### MCP Integration
127+
116128
- Supports core MCP methods: `list_tools`, `list_prompts`, `call_tool`, `get_prompt`
117129
- Parallel endpoint structure: `/ask` and `/mcp` with shared logic
118130
- Tool and prompt template management
119131

120132
## Testing Approach
121133

122134
### Unit Testing
135+
123136
- **39 unit tests** with 100% pass rate (current standard)
124137
- **NSubstitute** for mocking dependencies
125138
- **MSTest** framework with `[TestMethod]` attributes
126139
- Focus on service layer and business logic testing
127140

128141
### Integration Testing
142+
129143
- **Manual testing** preferred over automated integration tests
130144
- **Comprehensive guides** in `/doc/manual-testing-guide.md`
131145
- **Sample requests** in `/doc/sample-requests.http` for IDE testing
132146
- **Demo application** for end-to-end validation
133147

134148
### Testing Conventions
149+
135150
- Test classes named `[ClassUnderTest]Tests`
136151
- Arrange-Act-Assert pattern
137152
- Mock external dependencies (AI services, data backends)
138153
- Test both success and error scenarios
139154

140155
## Development Practices
141156

157+
### Pre-Commit Requirements
158+
159+
- **Code formatting**: Run `dotnet format ./NLWebNet.sln` before each commit to ensure consistent code style
160+
- **Automated formatting**: GitHub Actions will also auto-format code on push to feature branches
161+
142162
### CI/CD Pipeline
163+
143164
- **GitHub Actions** for automated builds and testing
144165
- **NuGet package** generation and validation
145166
- **Release automation** with version tagging
146167
- **Security scanning** for vulnerable dependencies
147168

148169
### Build and Packaging
170+
149171
- **Deterministic builds** for reproducible packages
150172
- **Symbol packages** (.snupkg) for debugging support
151173
- **Source Link** integration for GitHub source navigation
152174
- **Package validation** scripts for quality assurance
153175

154176
### Documentation Standards
177+
155178
- **Comprehensive README** with usage examples
156179
- **XML documentation** for all public APIs
157180
- **OpenAPI specification** generated automatically
@@ -160,12 +183,14 @@ src/NLWebNet/
160183
## AI Service Integration
161184

162185
### Microsoft.Extensions.AI Pattern
186+
163187
- Use `Microsoft.Extensions.AI` abstractions for AI service integration
164188
- Support multiple AI providers (Azure OpenAI, OpenAI API)
165189
- Configuration-driven AI service selection
166190
- Async/await patterns for AI service calls
167191

168192
### Error Handling
193+
169194
- **Graceful degradation** when AI services are unavailable
170195
- **Fallback responses** for service failures
171196
- **Proper exception handling** with meaningful error messages
@@ -174,20 +199,23 @@ src/NLWebNet/
174199
## Common Patterns and Best Practices
175200

176201
### When Adding New Features
202+
177203
1. **Start with interfaces** - Define contracts before implementations
178204
2. **Add configuration options** to `NLWebOptions` if needed
179205
3. **Include unit tests** - Maintain the 100% pass rate standard
180206
4. **Update documentation** - XML docs and README as appropriate
181207
5. **Consider MCP integration** - How does this fit with MCP protocol?
182208

183209
### When Modifying Endpoints
210+
184211
1. **Use Minimal APIs** - Prefer `Endpoints/` classes over `Controllers/`
185212
2. **Maintain protocol compliance** - Follow NLWeb specification
186213
3. **Add OpenAPI documentation** - Use `.WithSummary()` and `.WithDescription()`
187214
4. **Include error responses** - Proper status codes and problem details
188215
5. **Test with sample requests** - Update manual testing guides
189216

190217
### When Adding Dependencies
218+
191219
1. **Prefer Microsoft.Extensions.*** - Use standard .NET abstractions
192220
2. **Check for existing alternatives** - Avoid duplicate functionality
193221
3. **Update project files** - Include in main library and test projects
@@ -196,19 +224,22 @@ src/NLWebNet/
196224
## Limitations and Current Implementation Status
197225

198226
### Current Implementation Status
227+
199228
- **Early alpha prerelease** - Core functionality implemented, not yet production ready
200229
- **Mock data backend** as default - Real data source integrations can be implemented via `IDataBackend`
201230
- **Basic AI integration** - Extensible via Microsoft.Extensions.AI patterns
202231
- **Authentication framework** - Ready for implementation based on application requirements
203232
- **Code quality standards** - Production-level code quality maintained throughout development
204233

205234
### Performance Considerations
235+
206236
- **Streaming responses** for better perceived performance
207237
- **Async/await** throughout for scalability
208238
- **Minimal allocations** where possible
209239
- **Configuration caching** for frequently accessed settings
210240

211241
### Deployment Considerations
242+
212243
- **Requires .NET 9.0** - Latest framework dependency for modern features
213244
- **Early prerelease status** - Not yet ready for production deployment
214245
- **Production-quality code** - Library being developed with production standards
@@ -217,10 +248,11 @@ src/NLWebNet/
217248
## When to Seek Clarification
218249

219250
Ask for guidance when:
251+
220252
- **Breaking changes** to public APIs are needed
221253
- **New external dependencies** are required
222254
- **Significant architectural changes** are proposed
223255
- **Protocol compliance** questions arise
224256
- **Production deployment** patterns need to be established
225257

226-
Remember: This library is being developed with production-quality standards, though it is currently in early prerelease and not yet ready for production use. All code additions and edits should maintain production-level quality as the project works toward its goal of becoming a production-ready NLWeb protocol implementation for .NET applications.
258+
Remember: This library is being developed with production-quality standards, though it is currently in early prerelease and not yet ready for production use. All code additions and edits should maintain production-level quality as the project works toward its goal of becoming a production-ready NLWeb protocol implementation for .NET applications.

doc/advanced-tool-system-guide.md

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Advanced Tool System Usage Guide
2+
3+
The Advanced Tool System provides enhanced query capabilities through specialized tool handlers that route queries to appropriate processors based on intent analysis.
4+
5+
## Configuration
6+
7+
Enable the tool system in your configuration:
8+
9+
```json
10+
{
11+
"NLWebNet": {
12+
"ToolSelectionEnabled": true,
13+
"DefaultMode": "List"
14+
}
15+
}
16+
```
17+
18+
## Available Tools
19+
20+
### 1. Search Tool (`search`)
21+
Enhanced keyword and semantic search with result optimization.
22+
23+
**Example Queries:**
24+
- "search for REST API documentation"
25+
- "find information about microservices"
26+
- "locate best practices for authentication"
27+
28+
**Features:**
29+
- Query optimization (removes redundant search terms)
30+
- Enhanced relevance scoring
31+
- Result sorting and filtering
32+
33+
### 2. Details Tool (`details`)
34+
Retrieves comprehensive information about specific named items.
35+
36+
**Example Queries:**
37+
- "tell me about GraphQL"
38+
- "what is Docker?"
39+
- "describe OAuth 2.0"
40+
- "information about React hooks"
41+
42+
**Features:**
43+
- Subject extraction from natural language queries
44+
- Detailed information focus
45+
- Comprehensive result filtering
46+
47+
### 3. Compare Tool (`compare`)
48+
Side-by-side comparison of two items or technologies.
49+
50+
**Example Queries:**
51+
- "compare React vs Vue"
52+
- "difference between REST and GraphQL"
53+
- "Node.js versus Python for backend"
54+
55+
**Features:**
56+
- Automatic item extraction from comparison queries
57+
- Structured comparison results
58+
- Side-by-side analysis
59+
60+
### 4. Ensemble Tool (`ensemble`)
61+
Creates cohesive sets of related recommendations.
62+
63+
**Example Queries:**
64+
- "recommend a full-stack JavaScript development setup"
65+
- "suggest tools for DevOps pipeline"
66+
- "I need a complete testing framework"
67+
68+
**Features:**
69+
- Multi-category recommendations
70+
- Coherent item grouping
71+
- Thematic organization
72+
73+
### 5. Recipe Tool (`recipe`)
74+
Specialized for cooking, recipes, and food-related queries.
75+
76+
**Example Queries:**
77+
- "substitute eggs in baking"
78+
- "what goes with grilled salmon?"
79+
- "recipe for chocolate chip cookies"
80+
81+
**Features:**
82+
- Ingredient substitution guidance
83+
- Food pairing suggestions
84+
- Cooking technique advice
85+
86+
## Integration
87+
88+
The tool system integrates automatically with your existing NLWebNet setup:
89+
90+
```csharp
91+
// Add NLWebNet services (includes tool system)
92+
services.AddNLWebNet(options =>
93+
{
94+
options.ToolSelectionEnabled = true;
95+
});
96+
```
97+
98+
## Backward Compatibility
99+
100+
When `ToolSelectionEnabled = false`, the system uses the standard query processing pipeline, maintaining full backward compatibility.
101+
102+
## Query Processing Flow
103+
104+
1. **Query Analysis**: The `IToolSelector` analyzes query intent
105+
2. **Tool Selection**: Appropriate tool is selected based on keywords and patterns
106+
3. **Tool Execution**: The `IToolExecutor` routes to the selected tool handler
107+
4. **Result Enhancement**: Each tool applies specialized processing
108+
5. **Response Generation**: Results are formatted and returned
109+
110+
## Custom Tool Development
111+
112+
To create custom tools, implement the `IToolHandler` interface:
113+
114+
```csharp
115+
public class CustomToolHandler : BaseToolHandler
116+
{
117+
public override string ToolType => "custom";
118+
119+
public override async Task<NLWebResponse> ExecuteAsync(
120+
NLWebRequest request,
121+
CancellationToken cancellationToken = default)
122+
{
123+
// Custom tool logic here
124+
return CreateSuccessResponse(request, results, processingTime);
125+
}
126+
127+
public override bool CanHandle(NLWebRequest request)
128+
{
129+
// Determine if this tool can handle the request
130+
return request.Query.Contains("custom");
131+
}
132+
}
133+
```
134+
135+
Register your custom tool:
136+
137+
```csharp
138+
services.AddScoped<IToolHandler, CustomToolHandler>();
139+
```

0 commit comments

Comments
 (0)