|
| 1 | +# SharpAIKit |
| 2 | + |
| 3 | +**A unified .NET large-model application and agentic AI development framework.** |
| 4 | + |
| 5 | +[](https://dotnet.microsoft.com/) |
| 6 | +[](LICENSE) |
| 7 | +[](https://www.nuget.org/packages/SharpAIKit) |
| 8 | + |
| 9 | +## 🎯 Why SharpAIKit? |
| 10 | + |
| 11 | +**More Powerful Than LangChain, Simpler Than LangChain** |
| 12 | + |
| 13 | +SharpAIKit is a production-ready .NET framework for building AI applications with large language models. It provides a unified API that works with any OpenAI-compatible service, while offering enterprise-grade features like type safety, modular architecture, and comprehensive observability. |
| 14 | + |
| 15 | +### Key Advantages |
| 16 | + |
| 17 | +- ✅ **Type Safety**: C# strong typing with compile-time checking |
| 18 | +- ✅ **Native Performance**: 10-100x faster than Python-based solutions |
| 19 | +- ✅ **Minimal Dependencies**: Lightweight, no dependency hell |
| 20 | +- ✅ **Unified API**: Works with any OpenAI-compatible API |
| 21 | +- ✅ **Enterprise Ready**: Built for production .NET applications |
| 22 | +- ✅ **Modular Design**: Clean separation of concerns, easy to extend |
| 23 | + |
| 24 | +## 🚀 Quick Start |
| 25 | + |
| 26 | +### Installation |
| 27 | + |
| 28 | +```bash |
| 29 | +dotnet add package SharpAIKit |
| 30 | +``` |
| 31 | + |
| 32 | +Or via Package Manager: |
| 33 | +``` |
| 34 | +Install-Package SharpAIKit |
| 35 | +``` |
| 36 | + |
| 37 | +### Basic Usage |
| 38 | + |
| 39 | +```csharp |
| 40 | +using SharpAIKit.LLM; |
| 41 | + |
| 42 | +// Works with ANY OpenAI-compatible API |
| 43 | +var client = LLMClientFactory.Create( |
| 44 | + "your-api-key", |
| 45 | + "https://api.deepseek.com/v1", |
| 46 | + "deepseek-chat" |
| 47 | +); |
| 48 | + |
| 49 | +// Simple chat |
| 50 | +var response = await client.ChatAsync("Hello, how are you?"); |
| 51 | +Console.WriteLine(response); |
| 52 | + |
| 53 | +// Streaming response |
| 54 | +await foreach (var chunk in client.ChatStreamAsync("Tell me a story")) |
| 55 | +{ |
| 56 | + Console.Write(chunk); |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +## 🔮 Killer Features |
| 61 | + |
| 62 | +### 1. Native C# Code Interpreter |
| 63 | + |
| 64 | +Execute C# code directly using Roslyn - no Python dependency, blazing fast! |
| 65 | + |
| 66 | +```csharp |
| 67 | +using SharpAIKit.CodeInterpreter; |
| 68 | + |
| 69 | +var interpreter = new RoslynCodeInterpreter(); |
| 70 | + |
| 71 | +// Math calculations |
| 72 | +var result = await interpreter.ExecuteAsync<double>("Math.Pow(3, 5)"); |
| 73 | +Console.WriteLine($"3^5 = {result}"); // Output: 243 |
| 74 | +
|
| 75 | +// Complex data processing |
| 76 | +var code = """ |
| 77 | + var numbers = Enumerable.Range(1, 100); |
| 78 | + var sum = numbers.Where(n => n % 2 == 0).Sum(); |
| 79 | + sum |
| 80 | + """; |
| 81 | +var sumResult = await interpreter.ExecuteAsync(code); |
| 82 | +Console.WriteLine($"Sum of even numbers: {sumResult.Output}"); |
| 83 | +``` |
| 84 | + |
| 85 | +**Why it's killer**: LangChain's Code Interpreter depends on Python, making deployment complex and slow. SharpAIKit uses .NET's Roslyn compiler for in-memory execution, delivering superior performance. |
| 86 | + |
| 87 | +### 2. SharpGraph - Graph Orchestration |
| 88 | + |
| 89 | +Handle complex workflows with loops and conditional branches using Finite State Machine. |
| 90 | + |
| 91 | +```csharp |
| 92 | +using SharpAIKit.Graph; |
| 93 | + |
| 94 | +// Self-correcting workflow: write → execute → check → fix → retry |
| 95 | +var graph = new SharpGraphBuilder("start", maxIterations: 20) |
| 96 | + .Node("start", async state => { |
| 97 | + state.Set("attempts", 0); |
| 98 | + state.NextNode = "write_code"; |
| 99 | + return state; |
| 100 | + }) |
| 101 | + .Node("write_code", async state => { |
| 102 | + // Generate code using LLM |
| 103 | + state.Set("code", await GenerateCodeAsync()); |
| 104 | + state.NextNode = "execute_code"; |
| 105 | + return state; |
| 106 | + }) |
| 107 | + .Node("execute_code", async state => { |
| 108 | + var code = state.Get<string>("code"); |
| 109 | + var result = await ExecuteCodeAsync(code); |
| 110 | + state.Set("result", result); |
| 111 | + state.NextNode = "check_result"; |
| 112 | + return state; |
| 113 | + }) |
| 114 | + .Node("check_result", async state => { |
| 115 | + var isValid = ValidateResult(state.Get<string>("result")); |
| 116 | + if (isValid) { |
| 117 | + state.ShouldEnd = true; |
| 118 | + } else { |
| 119 | + state.NextNode = "fix_code"; // Loop back |
| 120 | + } |
| 121 | + return state; |
| 122 | + }) |
| 123 | + .Node("fix_code", async state => { |
| 124 | + state.NextNode = "write_code"; // Retry |
| 125 | + return state; |
| 126 | + }) |
| 127 | + .Build(); |
| 128 | + |
| 129 | +var result = await graph.ExecuteAsync(); |
| 130 | +``` |
| 131 | + |
| 132 | +**Why it's killer**: LangChain's chains are linear (DAG), making loops difficult. SharpGraph uses Finite State Machine to handle complex, self-correcting workflows. |
| 133 | + |
| 134 | +### 3. DSPy-style Optimizer |
| 135 | + |
| 136 | +Automatically optimize prompts through iterative improvement - gets smarter over time! |
| 137 | + |
| 138 | +```csharp |
| 139 | +using SharpAIKit.Optimizer; |
| 140 | + |
| 141 | +var optimizer = new DSPyOptimizer(client) |
| 142 | +{ |
| 143 | + MaxIterations = 10, |
| 144 | + TargetScore = 0.9 |
| 145 | +}; |
| 146 | + |
| 147 | +// Add training examples |
| 148 | +optimizer |
| 149 | + .AddExample("What is C#?", "C# is an object-oriented programming language...") |
| 150 | + .AddExample("What is Python?", "Python is an interpreted programming language...") |
| 151 | + .AddExample("What is JavaScript?", "JavaScript is a dynamic programming language..."); |
| 152 | + |
| 153 | +// Set evaluation metric |
| 154 | +optimizer.SetMetric(Metrics.Contains); |
| 155 | + |
| 156 | +// Optimize prompt |
| 157 | +var initialPrompt = "Answer questions about programming languages: {input}"; |
| 158 | +var result = await optimizer.OptimizeAsync(initialPrompt); |
| 159 | + |
| 160 | +Console.WriteLine($"Optimized: {result.OptimizedPrompt}"); |
| 161 | +Console.WriteLine($"Best score: {result.BestScore:F2}"); |
| 162 | +// The optimizer automatically adds few-shot examples and improves the prompt! |
| 163 | +``` |
| 164 | + |
| 165 | +**Why it's killer**: LangChain's prompts are hardcoded, requiring manual tweaking. DSPy Optimizer automatically finds the best prompt through iterations. |
| 166 | + |
| 167 | +## 🏗️ Architecture Improvements (v0.3.0) |
| 168 | + |
| 169 | +### Strong Typed Context |
| 170 | + |
| 171 | +Type-safe data passing with compile-time checking: |
| 172 | + |
| 173 | +```csharp |
| 174 | +using SharpAIKit.Common; |
| 175 | + |
| 176 | +var context = new StrongContext(); |
| 177 | +context.Set("user_id", 12345); |
| 178 | +context.Set<UserProfile>(profile); |
| 179 | + |
| 180 | +// Type-safe access with IntelliSense support |
| 181 | +var userId = context.Get<int>("user_id"); |
| 182 | +var profile = context.Get<UserProfile>(); |
| 183 | + |
| 184 | +// Serialization support for persistence |
| 185 | +var json = context.ToJson(); |
| 186 | +var restored = StrongContext.FromJson(json); |
| 187 | +``` |
| 188 | + |
| 189 | +### Modular Architecture |
| 190 | + |
| 191 | +Clean separation of concerns with replaceable components: |
| 192 | + |
| 193 | +```csharp |
| 194 | +using SharpAIKit.Agent; |
| 195 | + |
| 196 | +// Planner: Generate execution plans |
| 197 | +var planner = new SimplePlanner(llmClient); |
| 198 | +var plan = await planner.PlanAsync("Complete data analysis task", context); |
| 199 | + |
| 200 | +// Tool Executor: Execute tool calls |
| 201 | +var executor = new DefaultToolExecutor(); |
| 202 | +executor.RegisterTool(myTool); |
| 203 | +var result = await executor.ExecuteAsync("tool_name", args, context); |
| 204 | + |
| 205 | +// Enhanced Agent: Combines all components |
| 206 | +var agent = new EnhancedAgent(llmClient, planner, executor, memory); |
| 207 | +var agentResult = await agent.RunAsync("Complex task"); |
| 208 | +``` |
| 209 | + |
| 210 | +### LLM Middleware System |
| 211 | + |
| 212 | +Unified middleware for retry, rate limiting, logging, and circuit breaking: |
| 213 | + |
| 214 | +```csharp |
| 215 | +using SharpAIKit.LLM; |
| 216 | + |
| 217 | +// Retry middleware |
| 218 | +var retryMiddleware = new RetryMiddleware( |
| 219 | + maxRetries: 3, |
| 220 | + delay: TimeSpan.FromSeconds(1) |
| 221 | +); |
| 222 | + |
| 223 | +// Rate limit middleware |
| 224 | +var rateLimitMiddleware = new RateLimitMiddleware( |
| 225 | + maxRequests: 10, |
| 226 | + TimeSpan.FromMinutes(1) |
| 227 | +); |
| 228 | + |
| 229 | +// Circuit breaker middleware |
| 230 | +var circuitBreaker = new CircuitBreakerMiddleware( |
| 231 | + failureThreshold: 5, |
| 232 | + timeout: TimeSpan.FromMinutes(1) |
| 233 | +); |
| 234 | +``` |
| 235 | + |
| 236 | +### Graph Engine Enhancements |
| 237 | + |
| 238 | +#### State Persistence |
| 239 | + |
| 240 | +Save and restore graph execution state: |
| 241 | + |
| 242 | +```csharp |
| 243 | +using SharpAIKit.Graph; |
| 244 | + |
| 245 | +var store = new FileGraphStateStore("./checkpoints"); |
| 246 | +var graph = new EnhancedSharpGraph("start"); |
| 247 | +graph.StateStore = store; |
| 248 | +graph.AutoSaveCheckpoints = true; |
| 249 | + |
| 250 | +// Auto-save during execution |
| 251 | +var state = await graph.ExecuteAsync(initialState); |
| 252 | + |
| 253 | +// Restore from checkpoint |
| 254 | +var checkpoint = await store.LoadCheckpointAsync(checkpointId); |
| 255 | +var restoredState = await graph.RestoreFromCheckpointAsync(checkpointId, store); |
| 256 | +``` |
| 257 | + |
| 258 | +#### Parallel Execution |
| 259 | + |
| 260 | +Execute multiple branches in parallel: |
| 261 | + |
| 262 | +```csharp |
| 263 | +var builder = new EnhancedSharpGraphBuilder("start"); |
| 264 | +builder |
| 265 | + .Fork("split", "branch1", "branch2", "branch3") |
| 266 | + .Join("merge", JoinStrategy.All, states => { |
| 267 | + // Merge results from all branches |
| 268 | + return MergeResults(states); |
| 269 | + }); |
| 270 | +``` |
| 271 | + |
| 272 | +#### Event System |
| 273 | + |
| 274 | +Lifecycle hooks for monitoring and debugging: |
| 275 | + |
| 276 | +```csharp |
| 277 | +var graph = new EnhancedSharpGraph("start"); |
| 278 | +graph.OnNodeStart += async (sender, e) => { |
| 279 | + Console.WriteLine($"Node {e.NodeName} started"); |
| 280 | +}; |
| 281 | +graph.OnNodeEnd += async (sender, e) => { |
| 282 | + Console.WriteLine($"Node {e.NodeName} completed in {e.ExecutionTime}"); |
| 283 | +}; |
| 284 | +graph.OnError += async (sender, e) => { |
| 285 | + Console.WriteLine($"Error in {e.NodeName}: {e.Error?.Message}"); |
| 286 | +}; |
| 287 | +``` |
| 288 | + |
| 289 | +### OpenTelemetry Integration |
| 290 | + |
| 291 | +Built-in distributed tracing support: |
| 292 | + |
| 293 | +```csharp |
| 294 | +using SharpAIKit.Observability; |
| 295 | + |
| 296 | +// LLM operation tracing |
| 297 | +using var activity = OpenTelemetrySupport.StartLLMActivity("Chat", model); |
| 298 | +activity?.SetTag("llm.provider", "DeepSeek"); |
| 299 | +var response = await client.ChatAsync("Hello"); |
| 300 | + |
| 301 | +// Tool execution tracing |
| 302 | +using var toolActivity = OpenTelemetrySupport.StartToolActivity("calculator"); |
| 303 | +// ... execute tool ... |
| 304 | +
|
| 305 | +// Graph node tracing |
| 306 | +using var nodeActivity = OpenTelemetrySupport.StartGraphNodeActivity("process"); |
| 307 | +// ... execute node ... |
| 308 | +``` |
| 309 | + |
| 310 | +### OpenAPI Tool Generation |
| 311 | + |
| 312 | +Auto-generate tool definitions from Swagger/OpenAPI specs: |
| 313 | + |
| 314 | +```csharp |
| 315 | +using SharpAIKit.Agent; |
| 316 | + |
| 317 | +// Load from URL |
| 318 | +var tools = await OpenAPIToolGenerator.GenerateFromUrlAsync( |
| 319 | + "https://api.example.com/swagger.json" |
| 320 | +); |
| 321 | + |
| 322 | +// Or generate from JSON string |
| 323 | +var tools = OpenAPIToolGenerator.GenerateFromOpenAPI(swaggerJson); |
| 324 | + |
| 325 | +// Register to executor |
| 326 | +foreach (var tool in tools) |
| 327 | +{ |
| 328 | + executor.RegisterTool(tool); |
| 329 | +} |
| 330 | +``` |
| 331 | + |
| 332 | +## 📚 Core Modules |
| 333 | + |
| 334 | +| Module | Description | |
| 335 | +|:-------|:------------| |
| 336 | +| **Chain** | LCEL-style pipeline composition with `\|` operator | |
| 337 | +| **Memory** | Buffer, Window, Summary, Vector, Entity strategies | |
| 338 | +| **Prompt** | Type-safe templates with variable substitution | |
| 339 | +| **Output Parser** | Strongly-typed JSON, Boolean, List, XML parsers | |
| 340 | +| **Document Loader** | Multi-format support (Text, CSV, JSON, Markdown, Web) | |
| 341 | +| **Callback** | Full-trace observability (Console, Logging, Metrics, File) | |
| 342 | +| **MultiModal** | Image support (URL, local file, Base64) | |
| 343 | +| **Agent** | ReAct, Plan-Execute, Multi-Agent systems | |
| 344 | +| **RAG** | Document indexing, vector search, intelligent Q&A | |
| 345 | + |
| 346 | +## 🌐 Supported Providers |
| 347 | + |
| 348 | +SharpAIKit works with **any OpenAI-compatible API**: |
| 349 | + |
| 350 | +| Provider | Base URL | |
| 351 | +|:---------|:--------| |
| 352 | +| OpenAI | `https://api.openai.com/v1` | |
| 353 | +| DeepSeek | `https://api.deepseek.com/v1` | |
| 354 | +| Qwen (Alibaba) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | |
| 355 | +| Mistral | `https://api.mistral.ai/v1` | |
| 356 | +| Yi (01.AI) | `https://api.lingyiwanwu.com/v1` | |
| 357 | +| Groq | `https://api.groq.com/openai/v1` | |
| 358 | +| Moonshot (Kimi) | `https://api.moonshot.cn/v1` | |
| 359 | +| Ollama (Local) | `http://localhost:11434` | |
| 360 | +| **Any OpenAI-compatible** | Custom URL | |
| 361 | + |
| 362 | +## 📖 Documentation |
| 363 | + |
| 364 | +- **GitHub**: https://github.com/dxpython/SharpAIKit |
| 365 | +- **中文文档**: [README_CN.md](https://github.com/dxpython/SharpAIKit/blob/main/README_CN.md) |
| 366 | +- **English Docs**: [README_EN.md](https://github.com/dxpython/SharpAIKit/blob/main/README_EN.md) |
| 367 | +- **Architecture Guide**: [ARCHITECTURE_IMPROVEMENTS.md](https://github.com/dxpython/SharpAIKit/blob/main/docs/ARCHITECTURE_IMPROVEMENTS.md) |
| 368 | +- **Issues**: https://github.com/dxpython/SharpAIKit/issues |
| 369 | + |
| 370 | +## 🆚 SharpAIKit vs LangChain |
| 371 | + |
| 372 | +| Feature | SharpAIKit | LangChain | |
| 373 | +|:--------|:----------|:----------| |
| 374 | +| **Type Safety** | ✅ C# Strong typing | ❌ Python weak typing | |
| 375 | +| **Performance** | ✅ Native compilation | ❌ Interpreted | |
| 376 | +| **Code Interpreter** | ✅ Native C# (Roslyn) | ❌ Python dependency | |
| 377 | +| **Graph Orchestration** | ✅ SharpGraph (FSM) | ⚠️ LangGraph (new) | |
| 378 | +| **Auto Optimization** | ✅ DSPy-style | ❌ None | |
| 379 | +| **State Persistence** | ✅ Built-in | ⚠️ Manual | |
| 380 | +| **Parallel Execution** | ✅ Fork/Join | ⚠️ Limited | |
| 381 | +| **Event System** | ✅ Lifecycle hooks | ❌ None | |
| 382 | +| **OpenTelemetry** | ✅ Built-in | ⚠️ Manual | |
| 383 | +| **Dependencies** | ✅ Minimal | ❌ Many | |
| 384 | + |
| 385 | +## 📄 License |
| 386 | + |
| 387 | +This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details. |
| 388 | + |
| 389 | +## 🙏 Acknowledgments |
| 390 | + |
| 391 | +Built with ❤️ for the .NET community. |
| 392 | + |
| 393 | +--- |
| 394 | + |
| 395 | +**⭐ Star this project if it helps you!** |
0 commit comments