Skip to content
Merged
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
180 changes: 180 additions & 0 deletions src/assets/docs/contracts/stepbuilder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# ⚙️ StepBuilder Overview

The **`StepBuilder`** class provides a fluent interface for defining the **behavioral flow of an AI Agent**.
It allows developers to specify **how an agent should process input, use memory, access knowledge, or perform role-based actions** — all through a clear, chainable syntax.

This builder is primarily used when creating or configuring an Agent (e.g., via `AIHub.Agent()`), to define the ordered sequence of reasoning or operational steps the Agent should follow.

---

### 🧩 Namespace

```csharp
using MaIN.Domain.Entities.Agents.Knowledge;
using MaIN.Services.Services.Models.Commands;
```

---

### 🏗️ Class Definition

```csharp
public class StepBuilder
```

A utility class for constructing a list of predefined **agent execution steps**.
Each step defines a mode of operation that influences how the Agent interprets, searches, or responds to input.

---

### 🔹 Core Methods

#### **`Instance`**

```csharp
public static StepBuilder Instance => new();
```

Provides a new instance of `StepBuilder` for fluent chaining.
Used as an entry point for defining a step sequence:

```csharp
StepBuilder.Instance.Answer().Build();
```

---

#### **`Answer()`**

Marks a basic answering step — the Agent simply generates a direct response to the input.

---

#### **`AnswerUseMemory()`**

Enables the Agent to **access and use stored memory** when forming a response.

---

#### **`AnswerUseKnowledge(bool alwaysSearchMemory = false)`**

Allows the Agent to **search its knowledge base** to form an answer.
The optional `alwaysSearchMemory` flag ensures memory is always consulted alongside knowledge retrieval.

---

#### **`AnswerUseKnowledgeWithTags(params string[] tags)`**

Filters knowledge retrieval by **specific tags**, letting the Agent focus on a targeted domain of stored information.

Example:

```csharp
StepBuilder.Instance.AnswerUseKnowledgeWithTags("finance", "market");
```

---

#### **`AnswerUseKnowledgeWithType(KnowledgeItemType type)`**

Restricts knowledge usage to a particular **type** (e.g., documents, facts, summaries).

---

#### **`AnswerUseKnowledgeAndMemory()`**

Combines both **knowledge-based reasoning** and **memory recall** for more contextually rich responses.

---

#### **`AnswerUseKnowledgeAndMemoryWithTags(params string[] tags)`**

A hybrid mode using both memory and tagged knowledge retrieval.

---

#### **`Become(string role)`**

Instructs the Agent to **adopt a specific role or persona** before continuing execution.

Example:

```csharp
.Become("assistant_expert")
```

---

#### **`FetchData(FetchResponseType fetchResponseType = FetchResponseType.AS_Answer)`**

Defines a step where the Agent **fetches external data**, optionally as a system-level operation.

* `AS_Answer` → Fetches data to produce a normal response
* `AS_System` → Fetches data for internal processing or state updates

---

#### **`Mcp()`**

Adds an **MCP (Multi-Component Process)** step — typically used for complex, multi-agent or multi-step coordination workflows.

---

#### **`Redirect(string agentId, string output = "AS_Output", string mode = "REPLACE")`**

Redirects execution flow to another Agent.
Useful for **delegation or agent chaining**.

Example:

```csharp
.Redirect("knowledge_agent", "AS_Output", "MERGE");
```

---

#### **`Build()`**

Finalizes and returns the constructed list of steps.
This list is then passed to the Agent configuration pipeline.

Example:

```csharp
.WithSteps(StepBuilder.Instance
.AnswerUseKnowledgeAndMemory()
.Build())
```

---

### 🧠 Example Usage

```csharp
var steps = StepBuilder.Instance
.AnswerUseKnowledgeAndMemoryWithTags("research", "analysis")
.Become("data_researcher")
.Build();

await AIHub.Agent()
.WithModel("claude-sonnet-4-5-20250929")
.WithSteps(steps)
.CreateAsync(interactiveResponse: true);
```

---

### 🔍 Summary

| Category | Purpose |
| ---------------------- | --------------------------------------------- |
| **Answer** | Simple or knowledge/memory-enhanced responses |
| **Knowledge & Memory** | Access stored or learned context |
| **Role / Behavior** | Define how the agent behaves or identifies |
| **Data Fetching** | Integrate external or internal data sources |
| **Redirection** | Delegate tasks between agents |
| **MCP** | MCP server call |

---

The `StepBuilder` provides a **modular, declarative way to control agent logic**, making agent configurations expressive, reusable, and easy to reason about.
193 changes: 193 additions & 0 deletions src/assets/docs/contracts/toolbuilder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# 🧰 ToolsConfigurationBuilder Overview

The **`ToolsConfigurationBuilder`** class provides a structured and extensible way to define and register **tools** that can be used by AI agents during execution.
Tools act as **callable functions** — external operations the model can invoke dynamically to retrieve data, perform computations, or trigger actions.

This builder simplifies tool creation by offering multiple overloads for different execution patterns (sync/async, typed/untyped, parameterized/no-parameter tools).

---

### 🧩 Namespace

```csharp
using System.Text.Json;
using MaIN.Domain.Entities.Tools;
```

---

### 🏗️ Class Definition

```csharp
public class ToolsConfigurationBuilder
```

A fluent builder for constructing a **`ToolsConfiguration`** object, which contains a list of **`ToolDefinition`** entries and optional configuration settings (such as tool selection behavior).

Each added tool defines a function name, description, expected parameters, and an execution delegate.

---

### 🔹 Core Usage

Used during agent configuration to specify tools the model can access:

```csharp
.WithTools(new ToolsConfigurationBuilder()
.AddTool(
name: "get_weather",
description: "Retrieve current weather information",
parameters: new { type = "object", properties = new { city = new { type = "string" } } },
execute: WeatherTools.GetWeather)
.WithToolChoice("auto")
.Build())
```

---

### 🔧 Methods Overview

#### **`AddDefaultTool(string type)`**

Registers a basic tool definition with a specific type.
Used when predefined tool behavior is already encapsulated elsewhere.

```csharp
.AddDefaultTool("system_logger")
```

---

#### **`AddTool(string name, string description, object parameters, Func<string, Task<string>> execute)`**

Registers an asynchronous tool that receives raw JSON input and returns a serialized string result.
This version is suitable when working directly with serialized arguments.

---

#### **`AddTool(string name, string description, object parameters, Func<string, string> execute)`**

Registers a synchronous version of the above method.
The provided function executes immediately and returns a plain string result.

---

#### **`AddTool<TArgs>(string name, string description, object parameters, Func<TArgs, Task<object>> execute)`**

Registers a **typed asynchronous tool**.
The input JSON is automatically deserialized into a strongly-typed object (`TArgs`), and the result is serialized back to JSON.

Example:

```csharp
.AddTool<CreateNoteArgs>(
"create_note",
"Create a new note with a title and content",
new
{
type = "object",
properties = new
{
title = new { type = "string", description = "Title of the note" },
content = new { type = "string", description = "Content of the note" }
},
required = new[] { "title", "content" }
},
NoteTools.CreateNoteAsync)
```

---

#### **`AddTool<TArgs>(string name, string description, object parameters, Func<TArgs, object> execute)`**

Registers a **typed synchronous tool**, similar to the previous method but without asynchronous execution.

The input is deserialized into the specified argument type (`TArgs`), the tool executes synchronously, and the result is serialized to JSON.

---

#### **`AddTool(string name, string description, Func<Task<object>> execute)`**

Registers an **asynchronous parameterless tool**, ideal for actions that don’t require inputs (e.g., fetching current time or status).

Example:

```csharp
.AddTool("get_current_time", "Get the current date and time", Tools.GetCurrentTimeAsync)
```

---

#### **`AddTool(string name, string description, Func<object> execute)`**

Registers a **synchronous parameterless tool**.
This overload is ideal for lightweight, immediate-return tools.

---

#### **`WithToolChoice(string choice)`**

Specifies the **tool selection strategy** for the agent.
Common values:

* `"auto"` → The model decides when to use tools automatically.
* `"none"` → Disables tool invocation.
* `"required"` → Forces tool usage if applicable.

---

#### **`Build()`**

Finalizes the configuration and returns a fully constructed **`ToolsConfiguration`** object.

---

### 🧠 Example Usage

```csharp
var toolsConfig = new ToolsConfigurationBuilder()
.AddTool<GetWeatherArgs>(
name: "get_weather",
description: "Get current weather conditions for a city",
parameters: new
{
type = "object",
properties = new
{
city = new { type = "string", description = "City name" }
},
required = new[] { "city" }
},
execute: WeatherTools.GetWeatherAsync)
.AddTool(
name: "get_current_time",
description: "Return the current local time",
execute: Tools.GetCurrentTime)
.WithToolChoice("auto")
.Build();
```

This configuration can then be attached to a chat or agent:

```csharp
await AIHub.Chat()
.WithModel("gpt-5-nano")
.WithTools(toolsConfig)
.CompleteAsync(interactive: true);
```

---

### 📘 Summary

| Category | Description |
| ----------------- | -------------------------------------------------------------------------------------- |
| **Purpose** | Defines callable tools the model can execute during interaction |
| **Supports** | Synchronous & asynchronous tools, typed & untyped execution |
| **Serialization** | Automatically handles JSON deserialization for input and serialization for output |
| **Integration** | Used directly with agents or chat sessions via `.WithTools()` |
| **Flexibility** | Allows parameterized tools, parameterless tools, and dynamic tool selection strategies |

---

The `ToolsConfigurationBuilder` provides a **clean, declarative, and extensible interface** for integrating external logic into AI-driven workflows, enabling agents to **go beyond text generation** and interact with real-world data and actions seamlessly.
Loading
Loading