LogoLogo
HomeNewsSupportVideos
  • Welcome
  • Wisej.NET
  • Concepts
    • Getting Started
    • General Concepts
    • Architecture
    • Extensibility
    • AI Providers
    • Vector Databases
    • Usage Metrics
    • Logging & Error Handling
  • Markup
  • Components
    • API
      • SmartAdapter
        • SmartAudioTTSAdapter
        • SmartAudioWhisperAdapter
        • SmartCalendarAdapter
        • SmartChartAdapter
        • SmartChartJS3Adapter
        • SmartChatBoxAdapter
        • SmartComboBoxAdapter
        • SmartCopilotAdapter
        • SmartDataEntryAdapter
        • SmartDocumentAdapter
        • SmartFullCalendarAdapter
        • SmartObjectAdapter
        • SmartPictureBoxAdapter
        • SmartQueryAdapter
        • SmartRealtimeAdapter
        • SmartReportAdapter
        • SmartTextBoxAdapter
        • SmartAdapter.ExtendsAttribute
        • SmartAdapter.FieldNameAttribute
        • SmartAdapter.FieldPromptAttribute
        • SmartAdapter.FieldRectangleAttribute
        • SmartAdapter.WorksWithAttribute
      • SmartEndpoint
        • AmazonBedrockEndpoint
        • AnthropicEndpoint
        • AzureAIEndpoint
        • CerebrasEndpoint
        • DeepSeekEndpoint
        • GoogleAIEndpoint
        • GroqCloudEndpoint
        • GroqCloudEndpointWhisper
        • HuggingFaceEndpoint
        • HuggingFaceJavaScriptEndpoint
        • LocalAIEndpoint
        • LocalAIEndpointImageGen
        • LocalAIEndpointTTS
        • LocalAIEndpointWhisper
        • NvidiaAIEndpoint
        • OllamaEndpoint
        • OpenAIEndpoint
        • OpenAIEndpointDallE
        • OpenAIEndpointRealtime
        • OpenAIEndpointTTS
        • OpenAIEndpointWhisper
        • SambaNovaEndpoint
        • SmartHttpEndpoint
        • TogetherAIEndpoint
        • XAIEndpoint
        • SmartEndpoint.Metrics
        • SmartEndpoint.Response
      • SmartExtensions
      • SmartHub
        • SmartSession.ConvertParameterEventArgs
        • SmartSession.ConvertParameterEventHandler
        • SmartSession.ErrorEventArgs
        • SmartSession.ErrorEventHandler
        • SmartSession.InvokeToolEventArgs
        • SmartSession.InvokeToolEventHandler
        • SmartSession.MessagesEventArgs
        • SmartSession.MessagesEventHandler
      • SmartObject
      • SmartPrompt
        • SmartAgentPrompt
        • SmartParallelPrompt
        • SmartPrompt.Parameter
        • SmartSession.ConvertParameterEventArgs
        • SmartSession.ConvertParameterEventHandler
        • SmartSession.ErrorEventArgs
        • SmartSession.ErrorEventHandler
        • SmartSession.InvokeToolEventArgs
        • SmartSession.InvokeToolEventHandler
        • SmartSession.MessagesEventArgs
        • SmartSession.MessagesEventHandler
      • SmartRealtimeSession
      • SmartSession
        • SmartSession.ConvertParameterEventArgs
        • SmartSession.ConvertParameterEventHandler
        • SmartSession.ErrorEventArgs
        • SmartSession.ErrorEventHandler
        • SmartSession.InvokeToolEventArgs
        • SmartSession.InvokeToolEventHandler
        • SmartSession.Message
        • SmartSession.MessageCollection
        • SmartSession.MessageRole
        • SmartSession.MessagesEventArgs
        • SmartSession.MessagesEventHandler
        • SmartSession.TrimmingStrategy
      • SmartTool
        • SmartTool.IToolProvider
        • SmartTool.ToolAttribute
        • SmartTool.ToolContext
      • Markup
        • MarkupExtensions
      • Controls
        • UVLightOverlay
      • Embeddings
        • EmbeddedDocument
        • Embedding
        • Matches
        • Metadata
      • Helpers
        • ApiKeys
        • Markdown
        • TextTokenizer
      • Services
        • DefaultSessionTrimmingService
        • IDocumentConversionService
          • DefaultDocumentConversionService
        • IEmbeddingGenerationService
          • DefaultEmbeddingGenerationService
          • HuggingFaceEmbeddingGenerationService
        • IEmbeddingStorageService
          • AzureAISearchEmbeddingStorageService
          • ChromaEmbeddingStorageService
          • FileSystemEmbeddingStorageService
          • MemoryEmbeddingStorageService
          • PineconeEmbeddingStorageService
          • QdrantEmbeddingStorageService
        • IHttpClientService
          • DefaultHttpClientService
        • ILoggerService
          • DefaultLoggerService
        • IOCRService
          • DefaultOCRService
        • IRerankingService
          • DefaultRerankingService
          • LocalAIRerankingService
          • PineconeRerankingService
        • ISessionTrimmingService
          • DefaultSessionTrimmingService
        • ITextSplitterService
          • RecursiveCharacterTextSplitterService
          • TextSplitterServiceBase
        • ITokenizerService
          • DefaultTokenizerService
        • IWebSearchService
          • BingWebSearchService
          • BraveWebSearchService
          • GoogleWebSearchService
      • Tools
        • ArxivTools
        • ChartJS3Tools
        • DatabaseTools
        • DataTableFilterTools
        • DocumentSearchTools
        • DocumentTools
        • FullCalendarTools
        • IToolsContainer
        • MathTools
        • ToolsContainer
        • UtilityTools
        • WebSearchTools
    • Built-in Services
      • IOCRService
      • ILoggerService
      • ITextSplitterService
      • ITokenizerService
      • IHttpClientService
      • IWebSearchService
      • IRerankingService
      • ISessionTrimmingService
      • IDocumentConversionService
      • IEmbeddingStorageService
      • IEmbeddingGenerationService
    • Built-in SmartTools
      • ToolsContainer
      • MathTools
      • UtilityTools
      • DatabaseTools
      • DocumentTools
      • DocumentSearchTools
      • WebSearchTools
      • ChartJS3Tools
      • FullCalendarTools
    • Built-in SmartAdapters
      • SmartAdapter
      • SmartAudioTTSAdapter
      • SmartAudioWhisperAdapter
      • SmartCalendarAdapter
      • SmartChartAdapter
      • SmartChartJS3Adapter
      • SmartChatBoxAdapter
      • SmartComboBoxAdapter
      • SmartCopilotAdapter
      • SmartDataEntryAdapter
      • SmartDocumentAdapter
      • SmartFullCalendarAdapter
      • SmartObjectAdapter
      • SmartPictureBoxAdapter
      • SmartQueryAdapter
      • SmartRealtimeAdapter
      • SmartReportAdapter
      • SmartTextBoxAdapter
    • Configure Services
    • Using SmartHub
    • Using SmartTools
    • Using SmartPrompt
    • Using SmartSession
    • Using SmartRealTimeAdapter
    • UVLightOverlay Control
Powered by GitBook
On this page
  • Overview
  • Examples
Export as PDF
  1. Components

Using SmartTools

PreviousUsing SmartHubNextUsing SmartPrompt

Last updated 4 days ago

Overview

The flexibility of the tools (also known as skills) system in Wisej.AI is one of its most powerful and important features. For an introduction to the tools architecture, please refer to the page.

In Wisej.AI, tools can take various forms, providing developers with significant flexibility. Tools can be implemented as:

  • Local functions

  • Anonymous functions (lambdas)

  • Asynchronous functions (async/await)

  • Plain Old CLR Objects (POCOs)

  • Objects that derive from the class

  • Objects that implement the interface

This versatility allows you to choose the most appropriate approach for your application's needs when defining and integrating tools within Wisej.AI.

There are two ways to provide a tool to the AI model in Wisej.AI:

  1. Decorate the function using the [SmartTool.Tool] attribute By applying the [SmartTool.Tool] attribute to a function, you allow Wisej.AI to automatically discover it as a tool when it is defined within a container class. When the container is associated with a SmartHub, all adapters linked to that hub will have access to the discovered tools.

  2. Register the function directly using the UseTools() method You can explicitly register a tool by passing it directly to the UseTools() method. This method accepts an instance of a tools container object or individual functions.

In both cases, Wisej.AI will identify and make available all functions marked with the [SmartTool.Tool] attribute within the provided container.

Examples

The following samples provide practical demonstrations of how to define, register, and utilize tools within Wisej.AI. Each example is designed to highlight a specific aspect of the tools system

  • Defining the Simplest Tool: Demonstrates how to create and register a basic tool using Wisej.AI. This typically involves a straightforward function, such as a method that performs a simple calculation or returns static data, and shows how it can be exposed to the AI model for use.

  • Implementing an Asynchronous Tool: Shows how to define a tool that performs asynchronous operations, such as tasks that involve I/O-bound work (e.g., reading from a database or making external API calls). The example highlights how to structure asynchronous functions and register them so that the AI model can execute them correctly using async/await patterns.

  • Enabling the AI Model to Create and Use Its Own Tools from Scratch: Illustrates the advanced capability of Wisej.AI, where the AI model is empowered to define new tools at runtime or dynamically utilize new tool functions.

Defining the Simplest Tool
var endpoint = new OpenAIEndpoint { ApiKey = "..." };
var prompt = new SmartPrompt()
	.UseTool(
		[Description("Returns the current date/time.")]
		() => DateTime.Now);

Console.WriteLine((await prompt.AskAsync(endpoint, "What time is it?")).Text);

// Output
// The current time is 6:09 PM on Monday, June 2, 2025.
Implementing an Asynchronous Tool
async Task<string> get_weather(float latitude, float longitude)
{
    return await new HttpClient()
        .GetStringAsync(
        $"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m,weathercode,precipitation,wind_speed_10m,wind_direction_10m");
}

var prompt = new SmartPrompt().UseTool(get_weather);
Console.WriteLine((await prompt.AskAsync(endpoint, "How's the weather in San Francisco?")).Text);

// Output
/*
The current weather in San Francisco is as follows:

- **Temperature**: 23.5°C
- **Weather**: Clear sky
- **Precipitation**: 0.0 mm
- **Wind Speed**: 21.8 km/h
- **Wind Direction**: 279°

The weather is expected to remain clear throughout the day with no precipitation.
*/
Enabling the AI Model to Create and Use Its Own Tools from Scratch
// Initialize the Python subsystem
Runtime.PythonDLL = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\Programs\\Python\\Python39\\python39.dll";
PythonEngine.Initialize();
PythonEngine.BeginAllowThreads();

// Create a complex anonoymous tool
session.UseTool(
[Description("Use this tool to execute a python script every time you are unable to answer a user question.\n" +
			 "You have access to the local computer system, including the clock and the file system at this root path: `{{root-path}}`\n" +
			 "The last line must always be: __output__ = <value>\n")]
    (string python_script) =>
    {
        using (Py.GIL())
        {
            try
            {
              Console.WriteLine("Python:");
              Console.WriteLine(python_script);

              var scope = Py.CreateScope();
              scope.Exec(python_script);
              return scope.Get("__output__").ToString();
            }
            catch (Exception ex) {
              // Allows the AI to retry with a different syntax
              return ex.Message;
            }
       }
    });
    
session.Parameters.Add("root-path", Path.GetTempPath());

Console.WriteLine("Assistant:" + (await session.AskAsync("What time is it?")).Text);
Console.WriteLine("Assistant:" + (await session.AskAsync("Is 7878127381 a prime number?")).Text);
Console.WriteLine("Assistant:" + (await session.AskAsync("What is the square root of 09121.1287812313?")).Text);

// Output
/*
Python:
from datetime import datetime

# Get the current time
current_time = datetime.now().strftime('%H:%M:%S')

__output__ = current_time
Assistant: The current time is 18:32:26.

Python:
def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

# Check if the number is prime
number = 7878127381
result = is_prime(number)

__output__ = result
Assistant: The number 7878127381 is not a prime number.

Python:
import math

# Calculate the square root
number = 9121.1287812313
square_root = math.sqrt(number)

__output__ = square_root
Assistant: The square root of 9121.1287812313 is approximately 95.50460083802926.
*/
ToolsContainer
IToolsContainer
SmartTools