Only this pageAll pages
Powered by GitBook
Couldn't generate the PDF for 199 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Wisej.AI

Loading...

Concepts

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Components

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Welcome

Wisej.AI: Connecting Business Applications to AI.

Welcome to Wisej.AI. This guide is designed to help you seamlessly integrate AI-driven features into your Wisej.NET applications. Whether you are starting from scratch or enhancing existing projects, this documentation will help you maximize the potential of your applications with Wisej.AI.

What is Wisej.AI

Wisej.AI is an advanced system that enhances Wisej.NET components, including third-party widgets, by incorporating AI features to create "Smart" applications. It is designed to be comprehensive, cohesive, standalone, open, and flexible. Wisej.AI operates above infrastructure libraries such as Microsoft Semantic Kernel (SK) or LangChain .NET.

Architecture

Wisej.AI offers a range of ready-made components to enhance your application with AI features, allowing you to concentrate on desired outcomes instead of complex implementations. As an open system, Wisej.AI supports integration with other libraries and functionalities, including those built with SK, giving you flexibility in your development choices.

How to Use It

It's quite simple, add the Wisej-3-AI or Wisej-4-AI NuGet package, and start by dropping the SmartHub component on any design surface. Then click "Create Endpoint" to pick your AI provider, then click "Create Adapter" to pick the AI feature you would like to add.

For a comprehensive understanding of Large Language Models (LLMs) and to learn what they can do to enhance your application, please review all concepts in the Concepts section of this documentation. This section contains all the necessary information.

Getting Started

Getting Started

Step-by-step instructions to start using Wisej.AI.

Installing Wisej.AI

Wisej.AI is distributed through two distinct NuGet packages: Wisej-4-AI.4.0.x.x.nupkg and Wisej-3-AI.3.5.x.x.nupkg. These packages include the necessary designer assemblies for both the .NET Framework and .NET Core, eliminating the need for separate designer packages.

The NuGet packages will not be available on NuGet.org, instead you will need to deploy them locally on your file system. To utilize these local NuGet packages, you'll need to add the file path to Visual Studio's list of NuGet sources.

Visual Studio Options Dialog

As an alternative you can simply add a NuGet.config file to your solution (at the same level as the .sln file) to include the configuration with the project. See nuget.config for details.

Adding AI Features to Your Application

After you've created a Wisej.NET application or opened an existing one, and added the Wisej-AI NuGet packages, you're ready to start using AI in your apps!

The fastest way is to drop a SmartHub component (you'll find it in the toolbox under the Wisej.AI tab) onto a Page (or any open designer).

Once you have the Hub (smartHub1) you have to select an endpoint (this is your AI provider, can be a public one or your own AI server, see for more information).

Selecting the endpoint first is important because it determines which adapters are compatible. Not all adapters work with every endpoint. For instance, some endpoints might support vision, while others require TTS or voice recognition.

Here are the initial steps:

1

Add a SmartHub

The SmartHub serves as the core unit that links and manages communication between the AI endpoint and adapters.

2

Once everything is in place, the specific control or set of controls that have been connected to the SmartAdapter will have a new set of AI properties.

Not all SmartAdapters are designed to connect directly to controls. Some, like the SmartObjectAdapter, offer functionality that can be utilized within the code itself.

How to Create Endpoints

After adding a SmartHub component, you have two options to create an Endpoint. You can either click the quick actions arrow and select "Create Endpoint," or you can select the SmartHub component and click the "Create Endpoint" link located at the bottom of the property grid.

You will see the SmartEndpoint picker dialog:

Select the provider you want to use, verify that the default properties are set correctly, and click OK. See for more information.

Wisej.AI will create the selected SmartEndpoint component and assign it to the Endpoint property of the SmartHub component. It is important to always check and make sure the SmartHub has an endpoint assigned.

All the designer dialogs are under development and will change before the release.

How to Select Adapters

After the SmartHub is associated with an endpoint, it can filter which adapters can work with that specific AI provider. Click the quick actions arrow and select "Create Adapter", or click the link "Create Adapter" in the property grid.

The SmartAdapter Picker shows all the built-in adapters that can use the endpoint plus any custom adapter that you have created in your application. Please note the Documentation link provided in the description field of each adapter. This link directs you straight to the documentation for the adapter, ensuring you have easy access to the relevant materials.

Click OK to create the adapter component.

Once the SmartAdapter is created, you have to connect it to the components to augment. Some adapters may support augmenting multiple controls, while others may allow extending only one control at a time, in which case you can add the same adater multiple times, if needed.

The screenshot above displays the SmartDataEntry adapter linked to the splitContainer1.Panel1 control. Once connected, the adapter will enhance all child controls, at every level, by integrating the new AI properties required for it to perform its functions effectively.

Configuring Api Keys

Most Endpoints, Vector Databases, and Web Search Engines require an Api Key to get authenticated. You can set Api Key for each component that requires one in three ways:

  1. Set the ApiKey property on the component

  2. Save the api key in the ~/AI/ApiKeys.json file

  3. Set the api key in an environment variable

ApiKeys.json File

To set up your Wisej.NET project properly, create a new folder named "AI" at the root level of your project. This folder will serve as an organized space for various AI features. Once the "AI" folder is in place, create a file named ApiKeys.json within it. This file will allow you to manage your api keys in one central location.

To ensure the security of your ApiKeys.json file when deploying with .NET Core (ASP.NET Core), you should prevent the server from allowing its download. A simple way to do this is by modifying the code in Startup.cs.

When deploying using .NET Framework, all json files are blocked in web.config.

You can store various types of keys in the ApiKeys.json file. Wisej.AI utilizes these keys for its Endpoints, Vector Databases, and Web Search Engines by identifying the service by its name without suffixes. For instance, if the service is named "BingWebService", Wisej.AI will use "BingWeb" to locate the key within the ApiKeys.json file.

Api Keys in Environment Variables

You can manage API keys securely by storing them in environment variables through your cloud provider. For example, Azure App Services lets you manage environment variables for each service efficiently.

The name of the environment variable is:

WISEJ_AI_APIKEY_ + Endpoint Name without the "Endpoint" suffix.

For the OpenAIEndpoint the api key environment variable is WISEJ_AI_APIKEY_OPENAI.

Environment variables override the settings in the ApiKeys.json file.

Custom Api Keys

If you choose to store custom keys in ApiKeys.json or as environment variables, you can retrieve these keys using the class. Here’s how you can do it:

In the example above, the method first attempts to read the environment variable named "KEY_MYCOOLSERVICE" with the second parameter (the name postfix) left empty. If this environment variable does not exist, it then checks for the key "MyCoolService" in the ApiKeys.json file.

If the final parameter, the envPrefix, is not specified, it defaults to "WISEJ_AI_APIKEY_" as the prefix for environment variables.

Your First AI Application

Start by creating a Wisej.NET new application with either a main page or a main form. And add a few fields and a button, like this:

Use the NuGet Package Manager to add Wisej-AI and Wisej-AI-Design to the project.

Add a new folder "AI" to the root of the project.

From the Toolbox, under "Wisej.AI Test" select SmartHub and drop it on the page being designed.

Now click the "Create Endpoint" link in the property grid or click the quick action arrow and select "Create Endpoint". See above.

Pick your AI provider. In this case we use OpenAI. Make sure you have an api key from Open AI. Put the api key in the ApiKey property (see also ).

Now create the SmartDataEntryAdapter (see ).

Leave all the default properties unchanged. Select the Page and you should see this in the properties panel.

Select the smartDataEntryAdapter1 component to assign it to the Adapter property.

Once the adapter is connected to the Page, all its child controls will gain new AI properties. In this case you will find the FieldName, FieldPrompt and FieldRectangleproperties under the group "AI Features"

For each field from top down, set the FieldName property to "First Name", "Last Name", "Email Address", "Summary". Then double click on the button and add this code to the button1_Click event handler. Notice that the handler is async.

Run the app. Then go to an email you received from someone, select the text including the signature and copy to the clipboard. Go back to the app, make sure to click somewhere on the page first or the browser will block clipboard access, and click the Smart Paste button.

This is already something! Now add a checkbox, set the text to "SPAM" but now set the FieldPrompt to "Detect if the text is likely to be a SPAM email."

Run it again and try now.

You can also try by select and copying an image to the clipboard. The SmartDataEntryAdapter supports just about anything.

API

Welcome

This book covers the full API for the Wisej.AI assembly only. For an in-depth guide of Wisej.AI features, please refer to the section.

Legend

Markup

Overview

Wisej.AI's core components—including endpoint, prompt, session, and hub—utilize the fluent markup syntax, enabling developers to seamlessly chain property settings and event handling. This streamlined approach enhances code readability and efficiency by allowing developers to configure components in a more intuitive and concise manner.

Helpers

Markup

Add a SmartEndpoint

The SmartEndpoint serves as the bridge connecting the AI provider with the adapters.

3

Add one or more SmartAdapters

SmartAdapters augment various Wisej.NET components with advanced AI capabilities, including data extraction, enhanced filtering, auto-pilot features, content generation, and auto correction.

4

Connect the SmartAdapters to the component to augment

To finish, select the component to augment, i.e. a TextBox or Panel, and connect it to an adapter: in the Property panel, locate the "AI on smartHub1" property, expand it, and choose the adapter.

AI Providers
AI Providers
Wisej.AI.Helper.ApiKeys
SmartEndpoint Picker Dialog
SmartAdapter Picker Dialog
How to Create Endpoints
Configuring Api Keys
How to Select Adapters
var endpoint = new OpenAIEndpoint()
	.Name("openAI")
	.Model("gpt-4o")
	.ApiKey("...");

var session = new SmartSession(endpoint1)
	.UseTools(new WebSearchTools())
	.UseTools(new DocumentSearchTools())
	.OnStart(() => AlertBox.Show("Thinking..."))
	.OnConvertParameter(e => e.Value = Convert.ToString(e.Value));
{
    // Endpoints
    "OpenAI": "<api key>",
    "AzureAI": "<api key>",

    // Vector DB Services
    "Pinecone": "<api key",
    
    // Web Search Eginens
    "BingWeb" : "<api key>"
}
// app.UseFileServer();
app.UseWhen(
    cx => !cx.Request.Path.StartsWithSegments("/AI"), 
     app => app.UseFileServer());

var apikey = ApiKeys.GetApiKey("MyCoolService", "", "KEY_");
private async void button1_Click(object sender, EventArgs e)
{
    await this.smartDataEntryAdapter1.FromClipboardAsync();
}
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Await Me.smartDataEntryAdapter1.FromClipboardAsync()
End Sub
Icon
Description

​​

Instance method, or property, or event.

​​

Static method or property or event.

​​

Protected method or property or event.

​​

Deprecated method or property or event.

Comment

Concepts & Reference

The concept documentation and the API reference are a never-ending work in progress. We update it almost daily. Please check back if what you are looking for is not available.

Skills

We assume that you have a good working knowledge of the following tools and technologies:

  • C# or VB.NET

  • .NET in general

  • Visual Studio

  • JavaScript

Concepts

General Concepts

Introduction to LLM Concepts in Wisej.AI

Overview

In this section, we will explore the foundational concepts of Large Language Models (LLMs) as they are utilized within Wisej.AI. This primer is designed to provide software developers with a comprehensive understanding of how LLMs work. We will cover the basic principles, architectural frameworks, and applications of LLMs, ensuring that you have the necessary background to effectively leverage these advanced models in your development projects through Wisej.AI and Wisej.NET.

LLMs are built upon the architecture. This document assumes that the reader has at least a basic understanding of how neural networks function.

Large Language Models (LLMs)

Large Language Models are a type of artificial intelligence designed to understand, generate, and manipulate human language. These models are trained on vast datasets and use deep learning techniques to achieve natural language processing tasks with impressive accuracy and fluency. Some key attributes of LLMs include:

Contextual Understanding: LLMs comprehend the context of the information they process, enabling them to generate responses that are relevant and coherent within the given framework.

Adaptability: These models can be fine-tuned for a plethora of applications, ranging from content generation to automated customer support, and, in the case of Wisej.AI, augmenting user interface components and widgets.

Scalability: The architecture of LLMs allows them to handle concurrent requests efficiently, which is crucial for real-time interaction in browser-based applications.

LLMs (Large Language Models) are a component of Generative AI, which is built upon the foundational principles of traditional Machine Learning (ML) architecture.

Fundamentally, LLMs are straightforward to use. They operate by predicting the next token in a sequence and continue this process until they reach a specified stopping point or condition, such as the end of a sentence or a predefined token limit.

For example, if the prompt is "Hello, how are you?" the likelihood of the next token being "banana" is very low. In contrast, the probability of the sequence continuing with "Very," followed by "good," then ", thank," "you," "for," and "asking" is much higher.

The complexity of the prompt that a model can handle effectively typically depends on the size of its Artificial Neural Network (ANN). When reviewing a model's description, you might encounter a number like 90B next to its name. This number represents the model's parameters, which are the weights of the ANN, expressed as single-precision floating-point numbers (float32). Consequently, a model with 90 billion parameters consists of 90 billion float32 numbers, resulting in an approximate size of 360 GB.

The "Hello" example is quite trivial. To better illustrate how Wisej.AI can leverage LLMs to deliver valuable functionality to applications—primarily without engaging in chat—consider the following simplified example:

System Prompt is always the first part of the request sent to the LLM. After that the "User" prompt is the message from the application, and the "Assistant" message is the response from the LLM.

The example above demonstrates how Wisej.AI dynamically generates a prompt by analyzing the code to identify the fields required by a .NET class. The agent message, which is the LLM's response, is formatted as valid JSON. This approach enables the system to read the response, parse it, and populate the appropriate fields in the application. This process is accomplished without engaging in chat and without handling "conversational" responses.

In other words, we are utilizing the LLM in a manner similar to how one would use a SQL database or a cloud service.

This is just the first crucial step in understanding the Wisej.AI architecture. Once this concept is clear, you can appreciate how Wisej.AI leverages this highly structured request-response approach to seamlessly integrate AI features into virtually any aspect of a Wisej.NET application.

Building on the concept of "harnessing" the AI model, Wisej.AI develops agents and super-agents, along with tools that enhance the model's capabilities. For instance, while a model is inherently limited to appending words (or , to be precise) to a prompt, Wisej.AI constructs structured prompts with specific instructions for obtaining additional information. By parsing these responses and invoking code iteratively (), Wisej.AI creates agents that deliver significantly more value to the system.

Empowering the AI through Tools

Tools are essentially functions that the LLM can "invoke" within its response. See for details on how Wisej.AI defines tools.

The simplest way to understand tools is through an example: if you ask any model, "What time is it?" the model will typically respond with something like, "I'm sorry, but I don't have the capability to provide real-time information such as the current time."

If you ask ChatGPT "what time is it" it will respond correctly - that is because it utilized a tool! But when you ask directly any model anywhere it will respond that it doesn't know.

If we simulate the request-response cycle managed by the Wisej.AI internal agent and have provided the get_current_time tool to the AI, the query would look like this (the content is very simplified):

Now imagine equipping the LLM with a variety of tools: one for web searches, another for querying your company's database, another for scanning through documents, one for building charts, and yet another for sending emails, among others. These tools effectively expand the AI's capabilities. Consequently, when an application uses Wisej.AI to extract data from a PDF document, it can also fill in missing information, check for anomalies, send alerts via email, and correlate internal documents with public information—all through a single message to the AI provider via Wisej.AI.

Retrieval-Augmented Generation (RAG)

LLMs cannot learn or retain information; they have no memory or state. Each request is independent and must include all the necessary information for the LLM to generate the correct subsequent tokens (the response) to the prompt.

If you've read that LLMs can process vast amounts of data in a single request, that's a misconception. In reality, the opposite is true. The combined size of requests and responses is quite limited. While the model itself is likely trained on a vast amount of information, its capacity to generate responses is constrained by what is known as the . This is the maximum number of tokens (for simplicity, you can think of a token as a word) that can be submitted to the ANN at once. It encompasses everything from the system prompt to the final question being submitted. You can think of it as a large string, similar to a lengthy SQL statement. A context window of 128,000 tokens is considered large with the current technology.

A common use case might involve a request to create a table listing all legal deadlines, along with summaries, from 8,000 documents in a folder. It is entirely impractical to concatenate the text from all these documents into a single prompt. Assuming an average of 20 pages per document and 400 words per page, you would end up with approximately 64 million words, which far exceeds the typical limit of 128K tokens.

Indeed, just as an AI (or a person, for that matter) cannot feasibly read billions of web pages but can submit a query to a search engine to receive a list of relevant pages, RAG is used to provide pertinent context to the AI. It does this by extracting the few chunks of text that are relevant to a query from a large collection of data.

Even when using RAG, the process may yield too many chunks, necessitating the truncation of relevant data, which can result in inaccurate responses. There are advanced techniques that can summarize, extract, and aggregate data to process more information effectively. However, there is always a limit to how much data can be handled in this manner.

For instance, if we want to create a chart of the "5-year cumulative returns" from an 80-page PDF 10-K filing from Apple, we would need to extract and process the relevant data from the document, as it cannot be included in its entirety within the prompt.

We accomplish this by splitting the document into chunks and generating an vector for each chunk. Then, we generate an embedding vector for the query (or a version of the query optimized by the LLM), select the top N chunks based on relevance, and submit only those chunks for processing.

Another example would be asking the AI to classify a line item in an invoice according to a list of codes in a chart of accounts stored in a database. Since we cannot submit the entire database, we need to extract the most relevant data to include with the prompt, providing the AI with sufficient information to complete the task accurately.

In essence, RAG (Retrieval-Augmented Generation) leverages traditional coding methods, which are capable of processing unlimited amounts of data, to extract a small, relevant subset of information for submission to the LLM (Large Language Model). Utilizing is just one of the many techniques available to accomplish this task.

Embeddings (Vectors)

Embeddings are vector representations of text that position the specific text in relation to other texts within a multidimensional space.

A vector representation is an array of floating-point numbers that indicates the text's position within the space, with the array's length corresponding to the number of dimensions. For instance, a vector with 1536 values places the text within a 1536-dimensional space.

This representation enables applications to efficiently filter large volumes of data by performing similarity searches, which involve calculating the distance between two vectors in the multidimensional space.

Before the introduction of embeddings, a developer would typically split the query into individual words, then iterate through each text chunk, perhaps counting how many keywords appeared in each. Additionally, they might have used traditional letter-swapping algorithms to account for similar words and possibly the relative positions of the keywords. This approach was highly inaccurate, as it only considered character matches and sequences, ignoring conceptual similarity. For instance, the character "5" and the word "five" would never match in such a search.

Using embeddings and various methods to calculate the distance between vectors is a straightforward mathematical operation. It allows applications to process vast amounts of data efficiently and quickly.

Wisej.AI offers a range of services and methods to generate embeddings, with options to store them in memory, on the file system, or in efficient vector databases such as Azure AI Search, Pinecone, or Chroma.

Embeddings stored in memory or the file system should be used solely for development purposes. For deployment, it is recommended to use a vector database for optimal performance and scalability.

Context Window and Tokens

All models have a limited context window, which is measured in tokens. Tokens are not the same as words, but for simplicity, they can be considered as such. To gain a better understanding of tokens in the context of LLMs, you can try using this tokenizer from OpenAI: .

When you type "Hello, how are you?" (which is 4 words, 3 spaces and 2 punctuations) you get 6 tokens. But if you type "Dearest, how are you?" you get 7 tokens.

There are various types of tokenizers, and different models may be trained using distinct tokenizers. On average, a token typically consists of about 3.5 characters.

Wisej.AI includes the ITokenizerService and offers a default implementation based on OpenAI's . This service can be accessed directly by the Wisej.NET application to count tokens, truncate strings, or split a string into tokens.

When a request to an LLM exceeds the maximum allowed tokens in the context window, the request will typically fail, resulting in an error. To resolve this, you may need to shorten the input or split it into multiple requests that fit within the context token limit.

Wisej.AI automatically manages content overflow before any errors occur by utilizing the SmartEndpoint.ContextWindow property as the token limit. When this limit is exceeded, the SmartSession object optimizes the history using various techniques to ensure smooth operation.

Semantic Kernel does it like . Wisej.AI does it automatically. See and for more information.

For a more detailed description of the automatic trimming employed by Wisej.AI, refer to the "" section under Usage Metrics.

Reranking

Reranking refers to the process of reordering a list of items, typically search results or recommendations, to improve their relevance or quality with respect to a specific criterion. This is often achieved by applying machine learning algorithms that re-evaluate and adjust the initial ranking, utilizing additional information or more sophisticated models.

When utilizing one of the built-in implementations of the IEmbeddingStorageService service, the order of relevance is initially determined by the similarity score of the embedding vectors. However, there may be instances where a more precise ordering is desired. Reranking is a common technique used to achieve this. It involves submitting the results of the vector search to a more advanced model, which then reorders the text chunks based on their relevancy to the query. This approach leverages the enhanced capabilities of the model to provide a more accurate order of results.

Wisej.AI offers the and an overridable method named RerankAsync within the DocumentTools and DocumentSearchTools classes. The default implementation uses the IRerankingService to reorganize the RAG documents.

What is an Agent and a Super-Agent

Utilizing a model typically involves sending a question and receiving a response. There are numerous examples available that demonstrate this process using Semantic Kernel or LangChain. Additionally, you will find many samples of workflows or pipelines that take a response and use it as a new request.

The process can be visualized as follows: Start with the question "What is the capital of China?" which results in the response "Beijing." This response is then used in a follow-up question, "How is the weather in Beijing?" leading to the response "Rainy."

All of this is based on the concept of "conversational AI."

However, Wisej.AI does not employ LLMs in this manner. Instead, it consistently supports context management, tools, and adapters through a composition pattern. Therefore, the smallest unit of AI utilization in Wisej.AI is always an agent.

Subsequently, since the Wisej.AI agents are utilized by adapters operating at the next layer, and these adapters have specific tasks and can incorporate multiple decisions and interactions, we can refer to them as super-agents.

Refer to the section in the documentation to see straightforward examples of this approach.

SambaNovaEndpoint

Wisej.AI.Endpoints.SambaNovaEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartSession.InvokeToolEventArgs

Wisej.AI.SmartSession InvokeToolEventArgs

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Constructors

DeepSeekEndpoint

Wisej.AI.Endpoints.DeepSeekEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartPrompt.Parameter

Wisej.AI.SmartPrompt Parameter

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Parameters are typically used in scenarios where dynamic content needs to be inserted into a prompt with placeholders.

Constructors

GroqCloudEndpoint

Wisej.AI.Endpoints.GroqCloudEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartAdapter.FieldPromptAttribute

Wisej.AI.SmartAdapter FieldPromptAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents an attribute used to define a prompt for a property or control.

Constructors

NvidiaAIEndpoint

Wisej.AI.Endpoints.NvidiaAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

LocalAIEndpoint

Wisej.AI.Endpoints.LocalAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartSession.ConvertParameterEventHandler

Wisej.AI.SmartSession ConvertParameterEventHandler

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Parameters

Name

Embeddings

Artificial Neural Network (ANN)
tokens
tools
SmartTools
Context Window
embedding
embeddings
OpenAI Tokenizer
Tiktoken
this
SmartSession.ContextOverflow
SmartSession.OnTrimMessages
Context Overflow
IRerankingService
SmartPrompt
Architecture
System Prompt
Your job is to extract the values for the fields listed below.

## Rules:
- Complete the task without asking questions.
- Repeating field are indicated by --.
- Infer missing values from the provided text.
- Carefully follow the instructions for each field specified after the field name.
- Combine multiple values into one value, if necessary.
- Return null for missing values.
- Resolve all the missing values before returning the data.
- Output your response as a JSON object.
- When a value is missing, use all the available tools to find it.

```Fields
Name (First name of the person.)
LastName (Last name of the person.)
Email (Email address. Deduct it from the text if not specified.)
Summary (Summarize the text in less than 256 characters.)
Spam (Detect whether the text is likely to be a SPAM message.)
```
User Message
Dear Client,
Here's introducing Glocal RPO, a global RPO that works with over 100+ clients and a team of 750+ employees.
We help clients reduce costs and support them in Sourcing and Recruiting for Healthcare, Life Sciences & Pharma sectors with our low-cost models.
I would be happy to run a trial on a few positions and showcase how we work.
If you have some time on Monday, can we connect?
Can we schedule a quick call so we can discuss this in more detail?
Eagerly awaiting your response!

Best Regards
Rohit Singh
Digital Marketing Head
[email protected]
Assistant Message
{
  "Name": "Rohit",
  "LastName": "Singh",  
  "Email": "[email protected]",  
  "Summary": "Glocal RPO offers cost-effective sourcing...",
  "Spam": true
}
System Prompt
You can utilize the following tools:
    
    // Returns the current time.
    get_current_time();
User Message
What time is it?
Assistant Tools Message
{
  "tool": "get_current_time()"
}
Execute tool request
return get_current_time();
User Tools Message
get_current_time() = "10:10:44 AM"
Assistant Message
The current time is 10:10:44 AM.
OpenAIEndpoint
  • SambaNovaEndpoint

Represents a connection to SambaNova endpoints, inheriting from OpenAIEndpoint.

public class SambaNovaEndpoint : OpenAIEndpoint
Public Class SambaNovaEndpoint
    Inherits OpenAIEndpoint

This class is used to configure and manage connections to the SambaNova API, providing properties to set the model and URL for the endpoint.

Constructors

SambaNovaEndpoint()

Initializes a new instance of the SambaNovaEndpoint class with default settings.

The default authentication method is set to "Bearer", the model is set to "Meta-Llama-3.1-8B-Instruct", and the URL is set to "https://api.sambanova.ai/v1".

Properties

Model

String: Gets or sets the model used by the SambaNova endpoint. (Default: "Meta-Llama-3.1-8B-Instruct")

URL

String: Gets or sets the URL of the SambaNova endpoint. (Default: "https://fast-api.snova.ai/v1")

UseNativeTools

Boolean: (Default: True)

SmartEndpoint
SmartHttpEndpoint
InvokeToolEventArgs(session, context)

Initializes a new instance of InvokeToolEventArgs.

Name
Type
Description

session

context

Properties

Session

SmartSession: Gets the session associated with the event.

ToolContext

ToolContext:

Used By

Name
Description

Public Class InvokeToolEventArgs
    Inherits HandledEventArgs
public class InvokeToolEventArgs : HandledEventArgs
OpenAIEndpoint
  • DeepSeekEndpoint

Represents a connection to DeepSeek endpoints, inheriting from OpenAIEndpoint.

public class DeepSeekEndpoint : OpenAIEndpoint
Public Class DeepSeekEndpoint
    Inherits OpenAIEndpoint

This class is used to configure and manage connections to the DeepSeek API, providing properties to set the model and URL for the endpoint.

Constructors

DeepSeekEndpoint()

Initializes a new instance of the DeepSeekEndpoint class with default settings.

The default authentication method is set to "Bearer", the model is set to "Meta-Llama-3.1-8B-Instruct", and the URL is set to "https://api.deepseek.com".

Properties

Model

String: Gets or sets the model used by the DeepSeek endpoint. (Default: "deepseek-chat")

URL

String: Gets or sets the URL of the DeepSeek endpoint. (Default: "https://api.deepseek.com")

UseNativeTools

Boolean: (Default: True)

SmartEndpoint
SmartHttpEndpoint
Parameter()

Initializes a new instance of Parameter.

Properties

Name

String: Gets or sets the name of the parameter.

Value

Object: Gets or sets the value of the parameter.

Public Class Parameter
public class Parameter
OpenAIEndpoint
  • GroqCloudEndpoint

https://console.groq.com/docs/openai

public class GroqCloudEndpoint : OpenAIEndpoint
Public Class GroqCloudEndpoint
    Inherits OpenAIEndpoint

Constructors

GroqCloudEndpoint()

Initializes a new instance of the GroqCloudEndpoint class with default settings.

The default authentication method is set to "Bearer", and the default model is "llama-3.2-90b-vision-preview". The URL is set to "https://api.groq.com/openai/v1".

Properties

Model

String: Gets or sets the model used for the GroqCloud endpoint. (Default: "llama-3.2-90b-vision-preview")

URL

String: Gets or sets the URL for the GroqCloud API endpoint. (Default: "https://api.groq.com/openai/v1")

UseNativeTools

Boolean: (Default: True)

SmartEndpoint
SmartHttpEndpoint
FieldPromptAttribute(prompt)

Initializes a new instance of the FieldPromptAttribute class with the specified prompt.

Name
Type
Description

prompt

The prompt text associated with the property or control.

Properties

Prompt

String: Gets or sets the prompt text associated with the property or control.

Public Class FieldPromptAttribute
    Inherits Attribute
public class FieldPromptAttribute : Attribute
OpenAIEndpoint
  • NvidiaAIEndpoint

Represents a connection to NVIDIA AI endpoints, providing access to various AI models and services.

public class NvidiaAIEndpoint : OpenAIEndpoint
Public Class NvidiaAIEndpoint
    Inherits OpenAIEndpoint

This class extends the OpenAIEndpoint to specifically connect to NVIDIA's AI services. It sets default values for the authentication method, model, embedding model, and URL.

Constructors

NvidiaAIEndpoint()

Initializes a new instance of the NvidiaAIEndpoint class with default settings.

The default authentication method is set to "Bearer", the model to "meta/llama-3.1-405b-instruct", the embedding model to "nvidia/embed-qa-4", and the URL to "https://integrate.api.nvidia.com/v1".

Properties

EmbeddingModel

String: Gets or sets the embedding model used for AI processing. (Default: "nvidia/embed-qa-4")

Model

String: Gets or sets the model used for AI processing. (Default: "meta/llama-3.1-405b-instruct")

URL

String: Gets or sets the URL for the NVIDIA AI endpoint. (Default: "https://integrate.api.nvidia.com/v1")

UseNativeTools

Boolean: (Default: True)

SmartEndpoint
SmartHttpEndpoint
OpenAIEndpoint
  • LocalAIEndpoint

Represents a connection to LocalAI endpoints, providing access to various AI models and services.

public class LocalAIEndpoint : OpenAIEndpoint
Public Class LocalAIEndpoint
    Inherits OpenAIEndpoint

This class extends the OpenAIEndpoint to connect specifically to LocalAI's API. It initializes with default models and a URL for the TogetherAI service.

Constructors

LocalAIEndpoint()

Initializes a new instance of the LocalAIEndpoint class with default settings.

Properties

EmbeddingModel

String: Gets or sets the embedding model used for AI operations. (Default: "text-embedding-ada-002")

Model

String: Gets or sets the model used for AI operations. (Default: "")

URL

String: Gets or sets the URL for the LocalAI API endpoint. (Default: "http://localhost:8080/v1")

SmartEndpoint
SmartHttpEndpoint
Type
Description

sender

e

Fired By

Name
Description

Occurs when a parameter needs to be converted.

Public Delegate Sub ConvertParameterEventHandler(ByVal sender As [Object], ByVal e As ConvertParameterEventArgs)
public delegate void ConvertParameterEventHandler(Object sender, ConvertParameterEventArgs e)

SmartCalendarAdapter

Wisej.AI.Adapters.SmartCalendarAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartCalendarAdapter

Represents a smart calendar adapter that extends the functionality of a SmartAdapter.

public class SmartCalendarAdapter : SmartAdapter

The SmartCalendarAdapter class provides methods to process text or clipboard content asynchronously.

Constructors

SmartCalendarAdapter()

Initializes a new instance of the class.

This constructor initializes the SmartPrompt with a default prompt message.

Methods

FromClipboardAsync()

Processes the content from the clipboard asynchronously.

Returns: . A task that represents the asynchronous operation.

This method reads text or image data from the clipboard and processes it asynchronously.

Throws:

  • Thrown when the adapter is busy.

FromTextAsync(text)

Processes the specified text asynchronously.

Parameter
Type
Description

Returns: . A task that represents the asynchronous operation.

This method sets the internal text and initiates the asynchronous processing.

Throws:

  • Thrown when the text is null.

  • Thrown when the adapter is busy.

RunAsyncCore(control)

Executes the core logic of the adapter asynchronously.

Parameter
Type
Description

Returns: . A task that represents the asynchronous operation, containing the message response.

This method uses a session to ask a question based on the provided text and tracks the usage.

Inherited By

Name
Description

Implements

Name
Description

SmartAdapter.FieldRectangleAttribute

Wisej.AI.SmartAdapter FieldRectangleAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents an attribute that defines a rectangular area using a Rectangle associated to a property or a control.

public class FieldRectangleAttribute : Attribute
Public Class FieldRectangleAttribute
    Inherits Attribute

This attribute can be used to specify a rectangle by providing either its dimensions or a string representation.

Constructors

FieldRectangleAttribute(x, y, width, height)

Initializes a new instance of the class with specified dimensions.

Name
Type
Description

FieldRectangleAttribute(rectangle)

Initializes a new instance of the class with a rectangle specified as a string.

Name
Type
Description

The string should be in a format that can be converted to a using the type converter.

Properties

Rectangle

: Gets or sets the associated with this attribute.

SmartAdapter.FieldNameAttribute

Wisej.AI.SmartAdapter FieldNameAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents an attribute that can be used to specify a custom field name for a property or control.

public class FieldNameAttribute : Attribute
Public Class FieldNameAttribute
    Inherits Attribute

Constructors

FieldNameAttribute(name)

Initializes a new instance of the class with the specified field name.

Name
Type
Description

Properties

Name

: Gets or sets the custom field name associated with the property or control.

SmartChartJS3Adapter

Wisej.AI.Adapters.SmartChartJS3Adapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartChartAdapter

Represents an adapter that enhances a ChartJS control with several AI features.

This class extends the functionality of the ChartJS3 control by integrating AI capabilities. It is part of the SmartAdapter API category and does not allow multiple extensions.

Constructors

SmartChartJS3Adapter()

Initializes a new instance of .

Properties

ChartJS3

: Gets the ChartJS3 control associated with this adapter.

This property is not browsable in the property grid and is hidden from designer serialization.

Methods

OnControlCreated(control)

Called when a control is created.

Parameter
Type
Description

This method initializes the ChartJS3Tools with the associated ChartJS3 control. It ensures that the base class's OnControlCreated method is also called.

Implements

Name
Description

SmartRealtimeSession

Wisej.AI.SmartRealtimeSession

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

  • SmartObject

    • SmartSession

Constructors

SmartRealtimeSession(hub, systemPrompt)

Initializes a new instance of the class with the specified hub and optional system prompt.

Name
Type
Description

Throws:

  • Thrown when the hub is null.

SmartRealtimeSession(endpoint, systemPrompt)

Initializes a new instance of the class with the specified endpoint and optional system prompt.

Name
Type
Description

Throws:

  • Thrown when the endpoint is null.

TogetherAIEndpoint

Wisej.AI.Endpoints.TogetherAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents a connection to TogetherAI endpoints, providing access to various AI models and services.

This class extends the to connect specifically to TogetherAI's API. It initializes with default models and a URL for the TogetherAI service.

Constructors

TogetherAIEndpoint()

Initializes a new instance of the class with default settings.

The default authentication method is set to "Bearer". The default models and URL are pre-configured for TogetherAI services.

Properties

EmbeddingModel

: Gets or sets the embedding model used for AI operations. (Default: "togethercomputer/m2-bert-80M-8k-retrieval")

Model

: Gets or sets the model used for AI operations. (Default: "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo")

URL

: Gets or sets the URL for the TogetherAI API endpoint. (Default: "https://api.together.xyz/v1")

CerebrasEndpoint

Wisej.AI.Endpoints.CerebrasEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents a connection to Cerebras endpoints, inheriting from OpenAIEndpoint.

This class is specifically designed to connect to Cerebras AI endpoints, providing default values for the model and URL.

Constructors

CerebrasEndpoint()

Initializes a new instance of the class with default settings.

The default authentication method is set to "Bearer", the model to "llama3.1-70b", and the URL to "https://api.cerebras.ai/v1".

Properties

Model

: Gets or sets the model used by the Cerebras endpoint. (Default: "llama-3.3-70b")

URL

: Gets or sets the URL of the Cerebras endpoint. (Default: "https://api.cerebras.ai/v1")

UseNativeTools

: (Default: True)

SmartSession.MessagesEventArgs

Wisej.AI.SmartSession MessagesEventArgs

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Provides data for events that involve a collection of messages in the SmartSession API.

public class MessagesEventArgs : EventArgs
Public Class MessagesEventArgs
    Inherits EventArgs

Constructors

MessagesEventArgs(session, messages)

Initializes a new instance of the class with the specified list of messages.

Name
Type
Description

Properties

Messages

: Gets the list of messages sent and received.

Session

: Gets the session associated with the event.

Used By

Name
Description

SmartSession.InvokeToolEventHandler

Wisej.AI.SmartSession InvokeToolEventHandler

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

public delegate void InvokeToolEventHandler(Object sender, InvokeToolEventArgs e)
Public Delegate Sub InvokeToolEventHandler(ByVal sender As [Object], ByVal e As InvokeToolEventArgs)

Parameters

Name
Type
Description

Fired By

Name
Description

Matches

Wisej.AI.Embeddings.Matches

Namespace: Wisej.AI.Embeddings

Assembly: Wisej.AI (3.5.0.0)

public class Matches
Public Class Matches

Constructors

Matches(chunks, similarity)

Initializes a new instance of .

Name
Type
Description

Properties

Chunks

:

Similarity

:

SmartSession.MessagesEventHandler

Wisej.AI.SmartSession MessagesEventHandler

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents the method that will handle message-related events for the SmartSession object.

public delegate void MessagesEventHandler(Object sender, MessagesEventArgs e)
Public Delegate Sub MessagesEventHandler(ByVal sender As [Object], ByVal e As MessagesEventArgs)

Parameters

Name
Type
Description

Fired By

Name
Description

SmartSession.TrimmingStrategy

Wisej.AI.SmartSession TrimmingStrategy

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Specifies the strategy for handling context overflow in a session.

public enum TrimmingStrategy : Enum
Public Enum TrimmingStrategy As [Enum]

Fields

Name
Description

Used By

Name
Description

UVLightOverlay

Wisej.AI.Controls.UVLightOverlay

Namespace: Wisej.AI.Controls

Assembly: Wisej.AI (3.5.0.0)

  • Control

    • UVLightOverlay

Represents a control that displays an animated UV light overlay to simulate an optical scanner.

public class UVLightOverlay : Control

Constructors

UVLightOverlay()

Initializes a new instance of .

Methods

OnWebRender(config)

Renders the UV light overlay on the web client.

Parameter
Type
Description

XAIEndpoint

Wisej.AI.Endpoints.XAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents a connection to X.AI endpoints, extending the functionality of OpenAIEndpoint.

This class is used to interact with the X.AI API, providing properties and methods specific to X.AI's capabilities.

Constructors

XAIEndpoint()

Initializes a new instance of the class with default settings.

The default authentication method is set to "Bearer", the model to "grok-beta", and the URL to "https://api.x.ai/v1".

Properties

Model

: Gets or sets the model used by the X.AI endpoint. (Default: "grok-beta")

URL

: Gets or sets the URL of the X.AI API endpoint. (Default: "https://api.x.ai/v1")

UseNativeTools

: (Default: True)

SmartSession.ErrorEventHandler

Wisej.AI.SmartSession ErrorEventHandler

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents the method that will handle an error event in a SmartSession.

public delegate void ErrorEventHandler(Object sender, ErrorEventArgs e)
Public Delegate Sub ErrorEventHandler(ByVal sender As [Object], ByVal e As ErrorEventArgs)

Parameters

Name
Type
Description

Fired By

Name
Description

Usage Metrics

How to keep track of the tokens

Overview

Most AI cloud providers charge based on the . They differentiate between input tokens (the tokens you send) and output tokens (the tokens generated).

Wisej.AI tracks InputTokens, OutputTokens, and CallCount in the Usage property across multiple levels, providing detailed insights into how resources are being utilized:

Logging & Error Handling

How to handle errors and log AI activity

Logging

All logging within Wisej.AI is managed via the . The default implementation is provided by , which forwards the log entries to according to the specified TraceLevel.

You can set up your own logging implementation by registering a service that implements the ILoggerService interface. The optimal location for this registration is within the static constructor of the Program class.

SmartSession.Message

Wisej.AI.SmartSession Message

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a message within a SmartSession, containing various types of content such as text, image, and binary data.

The Message class is used to encapsulate different types of content that can be part of a session. It includes properties for text, image, and binary content, as well as methods to retrieve role and image data in specific formats.

SmartSession.ErrorEventArgs

Wisej.AI.SmartSession ErrorEventArgs

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Provides data for the event in a .

Constructors

SmartFullCalendarAdapter

Wisej.AI.Adapters.SmartFullCalendarAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

SmartTool

Wisej.AI.SmartTool

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a tool that can be used to perform operations on a target object using a specified method.

Constructors

Embedding

Wisej.AI.Embeddings.Embedding

Namespace: Wisej.AI.Embeddings

Assembly: Wisej.AI (3.5.0.0)

Represents an embedding which contains chunks of data, their associated vectors, and the model used for embedding.

Constructors

SmartSession.MessageRole

Wisej.AI.SmartSession MessageRole

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents the role of a message within a smart session context.

Fields

ApiKeys

Wisej.AI.Helpers.ApiKeys

Namespace: Wisej.AI.Helpers

Assembly: Wisej.AI (3.5.0.0)

Provides methods to retrieve API keys from environment variables or a configuration file.

Methods

SmartTool.ToolAttribute

Wisej.AI.SmartTool ToolAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Attribute to categorize methods as part of the SmartTool API.

Constructors

sender

Object

e

InvokeToolEventArgs

SmartObject.BeforeInvokeTool

Occurs before a tool is invoked.

SmartObject.AfterInvokeTool

Occurs after a tool is invoked.

sender

Object

The source of the event.

e

MessagesEventArgs

A MessagesEventArgs that contains the event data.

SmartObject.BeforeSendRequest

Occurs before a request is sent.

SmartObject.AfterResponseReceived

Occurs after a response is received.

SmartObject.PrepareMessages

Occurs after the messages have been prepared and before they are send to the AI.

RollingWindow

Uses a rolling window strategy to handle context overflow.

Summarization

Uses summarization to handle context overflow.

DefaultSessionTrimmingService.TrimmingStrategy

Gets or sets the strategy for handling context overflow.

ISessionTrimmingService.TrimmingStrategy

Gets or sets the strategy for handling context overflow.

sender

Object

The source of the event.

e

ErrorEventArgs

An ErrorEventArgs that contains the event data.

SmartObject.Error

Occurs when an error is encountered.

Object
ConvertParameterEventArgs
SmartObject.ConvertParameter

x

Int32

The x-coordinate of the upper-left corner of the rectangle.

y

Int32

The y-coordinate of the upper-left corner of the rectangle.

width

Int32

The width of the rectangle.

height

Int32

The height of the rectangle.

rectangle

String

A string representation of the rectangle.

FieldRectangleAttribute
FieldRectangleAttribute
Rectangle
Rectangle
Rectangle

name

String

The custom field name to associate with the property or field.

FieldNameAttribute
String

session

SmartSession

The SmartSession associated with the event.

messages

IList<Message>

The list of messages associated with the event.

SmartSession.MessagesEventHandler

Represents the method that will handle message-related events for the SmartSession object.

MessagesEventArgs
IList<Message>
SmartSession

chunks

IEnumerable<String>

similarity

IEnumerable<Single>

Matches
String[]
Single[]

config

Object

The dynamic configuration object used to render the control.

Public Class UVLightOverlay
    Inherits Control
UVLightOverlay
SmartSession
ToolContext
SmartSession.InvokeToolEventHandler
String

control

Control

The control that was created.

IToolProvider

Represents a provider that supplies tools.

SmartChartJS3Adapter
Public Class SmartChartJS3Adapter
    Inherits SmartChartAdapter
SmartChartJS3Adapter
ChartJS3
public class SmartChartJS3Adapter : SmartChartAdapter

hub

SmartHub

The smart hub associated with the session.

systemPrompt

SmartPrompt

The optional system prompt for the session. Default is null.

endpoint

SmartEndpoint

The smart endpoint associated with the session.

systemPrompt

SmartPrompt

The optional system prompt for the session. Default is null.

SmartRealtimeSession
Public Class SmartRealtimeSession
    Inherits SmartSession
SmartSession
ArgumentNullException
SmartSession
ArgumentNullException
public class SmartRealtimeSession : SmartSession
OpenAIEndpoint
TogetherAIEndpoint
Public Class TogetherAIEndpoint
    Inherits OpenAIEndpoint
OpenAIEndpoint
TogetherAIEndpoint
String
String
String
public class TogetherAIEndpoint : OpenAIEndpoint
OpenAIEndpoint
CerebrasEndpoint
Public Class CerebrasEndpoint
    Inherits OpenAIEndpoint
CerebrasEndpoint
String
String
Boolean
public class CerebrasEndpoint : OpenAIEndpoint
OpenAIEndpoint
XAIEndpoint
Public Class XAIEndpoint
    Inherits OpenAIEndpoint
XAIEndpoint
String
String
Boolean
public class XAIEndpoint : OpenAIEndpoint

Controls

static class Program
{
    static Program()
    {
        Application.Services.
            .AddOrReplaceService<ILoggerService, MyLoggerService>();
    }
}
Module Program
    Shared Sub New()
        Application.Services.AddOrReplaceService( _
            Of ILoggerService, MyLoggerService)()
    End Sub
End Module

Error Handling

When using an AI provider, several types of errors can occur: channel errors, provider errors, server errors, and model errors.

  1. Channel Errors: These involve issues with communication, such as loss of connectivity or network problems.

  2. Provider Errors: These are related to your account with the AI provider, such as exceeding credit or usage limits.

  3. Server Errors: Related to issues on the server side which might affect availability or performance.

  4. Model Errors: These generally pertain to payload construction, token limits, or other constraints specific to the AI model being used.

If an error occurs while using the AI directly through a SmartPrompt.AskAsync call, you can handle it by wrapping the call in a try/catch block. This allows you to manage exceptions effectively as your code processes the response.

If an error occurs while using the AI through a SmartAdapter, and the SmartAdapter is connected to a SmartHub (as it should be), you can manage the error using the SmartHub.Error event. However, if the adapter is not connected to a hub and you are using the RunAsync() method (or its variations) directly, you can manage errors by wrapping the call in a try/catch block.

If an error occurs while using a SmartSession instance, you can handle it by utilizing the SmartSession.Error event to manage the error.

The error event allows you to modify the last AI response and the assistant's response, effectively allowing you to "simulate" an AI response. To achieve this, you can handle the error (or override the OnError method) by adjusting the ReplacementMessage or changing the Text property of the predefined ReplacementMessage (which defaults to the exception message). Then, set the Handled property to true. This indicates that the error has been managed and that your custom response should be used.

ILoggerService
DefaultLoggerService
System.Diagnostics.Trace

text

String

The text to be processed.

control

Control

The control associated with the operation.

SmartFullCalendarAdapter

IToolProvider

Represents a provider that supplies tools.

Public Class SmartCalendarAdapter
    Inherits SmartAdapter
SmartCalendarAdapter
Task
InvalidOperationException
Task
ArgumentNullException
InvalidOperationException
Task<Message>
this.hub1.Error += (s, e) =>
{
    if (IsNetworkError(e.Exception)
    {
        e.ReplacementMessage.Text  = 
            "We're currently experiencing a temporary communication issue. " +
            "Please try again later or reach out to support at...";
            
        e.Handled = true;
    }
}
AddHandler Me.hub1.Error, Sub(s, e)
    If IsNetworkError(e.Exception) Then
        e.ReplacementMessage.Text = 
          "We're currently experiencing a temporary communication issue. " & _
          "Please try again later or reach out to support at..."
        e.Handled = True
    End If
End Sub

var adapter = new SmartCalendarAdapter();
await adapter.FromClipboardAsync();

var adapter = new SmartCalendarAdapter();
await adapter.FromTextAsync("Sample text");
Component
Usage Description

The total usage related to the SmartPrompt instance is collected, allowing for a comprehensive analysis of resource consumption tied specifically to that instance.

The total usage for the lifetime of the session is collected, offering detailed insights into resource utilization for the entire duration of the session.

Usage metrics utilized by the message. Only the ToolCall and Assistant message roles carry these metrics, as they represent the responses from the LLM, which is what provides the metrics data.

The total usage for the lifetime of the endpoint instance is collected continuously, providing a complete view of resource consumption throughout the instance's duration.

The total usage related to the hub instance is collected continuously and does not reset even if the endpoint associated with the hub changes.

Please note that input tokens aren't limited to just the tokens sent with the question. Because Wisej.AI offers a higher layer of functionality, any AI request may include additional tokens for elements such as the system prompt, tools, and internal agentic loops.

Metrics

All the components mentioned above expose the Usage property of type Metrics. Wisej.AI ensures that this property is kept up-to-date at all times. The usage data is parsed directly from the LLM response using the ReadUsage method in the SmartEndpoint implementation, and it is then tallied across the different layers.

For example, if you use the SmartChatBoxAdapter without any tools and engage in a simple chat, the usage would look like this:

Component
CallCount
InputTokens
OutputTokens

SmartPrompt

1
648
9

SmartSession

1
648
9

SmartSession.Message

1
648

We made one call by sending "Hello," which is 1 token, and received a response of 9 tokens. However, the AI provider logged 648 input tokens! This is because we didn't just send "Hello"; we also included the built-in Wisej.AI system prompt, which has a minimum size of 648 tokens. If you incorporated some tools, you could easily exceed 2,000 tokens.

Component
CallCount
InputTokens
OutputTokens

SmartPrompt

2
1312
43

SmartSession

2
1312
43

SmartSession.Message

1
664

The cost with OpenAI for the queries described above would involve calculating the total number of input and output tokens used and applying the pricing model provided by OpenAI.

Input Tokens: $2.50 / 1M tokens * 1312 = $0.00328

Output Tokens: $10 / 1M tokens * 43 = $0.00043


Total Cost: $0.00371

If we repeated the scenario 1,000 times, the cost would be approximately $3.71. This estimation is based on the number of tokens used in each request and the pricing model typically applied by OpenAI for token usage.

Local Hosting

Local hosting operates under a different cost structure. If you're using a hosted virtual machine (VM), the pricing is typically charged by the hour. In contrast, if you're using owned hardware, the costs involve the purchase of the hardware and its housing, either on-premises or in a data center.

The granular approach Wisej.AI employs to track usage is beneficial in this scenario as well, enabling you to compare the total cost of ownership when using local hosting against the usage cost of an AI cloud provider.

Context Overflow

Wisej.AI utilizes the ContextWindow property value configured on the endpoint in use, along with the current usage metrics, to proactively optimize and trim messages before submitting them to the model.

When Wisej.AI detects that the payload about to be submitted exceeds the allowed context window size in tokens, it employs the ISessionTrimmingService to trim the messages within the session. This process aims to maximize the preservation of memory for the model. The trimming strategy used is governed by the service and is influenced by the values of the TrimmingStrategy and TrimmingPercentage properties.

RollingWindow Approach:

In this method, Wisej.AI reduces the entire message history by half. Crucially, it preserves the System Prompt at the top of the message list. It then methodically removes tool calls and tool responses in pairs to maintain a balanced history. If further reduction is necessary, it starts removing user and assistant messages from the top of the list.

Summarization Approach:

In the summarization method, Wisej.AI constructs a summarization payload that includes half of all the messages, except for the System Prompt at the top which remains intact. This payload is then sent to a summarization prompt (specified under the "[SmartSession.Summarization]" key). The outcome of this process is that all the messages are replaced with a single assistant message containing the summary of half of the history.

Custom:

To implement your own trimming strategy, you need to create a class that implements the ISessionTrimmingService interface and replace the default service with your implementation. Within this class, you can utilize other models or libraries to efficiently manage the overflow of session messages.

number of tokens used
Constructors

Message()

Initializes a new instance of Message.

Properties

Binary

BinaryContent: Gets or sets the binary content of the message.

FinishReason

String: Gets the "finish_reason" returned by the model.

Image

Image: Gets or sets the image content of the message.

Role

MessageRole: Gets or sets the role associated with the message.

Text

String: Gets or sets the text content of the message.

Usage

Metrics: Gets the usage metrics associated with the message.

Methods

GetImageBase64()

Converts the image content of the message to a Base64 string.

Returns: String. A Base64 string representation of the image content.

If the image is null, an empty string is returned. Otherwise, the image is serialized to a Base64 string.

GetImageBase64DataURL()

Converts the image content of the message to a Base64 Data URL string.

Returns: String. A Base64 Data URL string representation of the image content.

If the image is null, an empty string is returned. Otherwise, the image is serialized to a Base64 Data URL string.

GetImageMediaType()

Returns the media type string for the image content.

Returns: String. The media type string, or an empty string if the image is null.

GetRole()

Retrieves the role of the message as a string.

Returns: String. A string representing the role of the message.

The method returns a string representation of the message role, which can be "system", "assistant", or "user".

Public Class Message
public class Message
ErrorEventArgs(session, exception, replacementMessage)

Initializes a new instance of the ErrorEventArgs class.

Name
Type
Description

session

The SmartSession where the error occurred.

exception

The exception that was thrown.

replacementMessage

The message to replace the original answer, if applicable.

Properties

Exception

Exception: Gets the exception that was thrown.

ReplacementMessage

Message: Gets or sets the message to replace the original answer, if applicable.

Session

SmartSession: Gets the SmartSession where the error occurred.

Used By

Name
Description

Represents the method that will handle an error event in a SmartSession.

Error
SmartSession
Public Class ErrorEventArgs
    Inherits HandledEventArgs
public class ErrorEventArgs : HandledEventArgs
SmartFullCalendarAdapter
public class SmartFullCalendarAdapter : SmartCalendarAdapter
Public Class SmartFullCalendarAdapter
    Inherits SmartCalendarAdapter

Constructors

SmartFullCalendarAdapter()

Initializes a new instance of SmartFullCalendarAdapter.

Properties

FullCalendar

FullCalendar: Gets the FullCalendar control associated with this adapter.

This property retrieves the first FullCalendar control found within the adapter's controls collection.

Methods

OnControlCreated(control)

Called when a control is created within the adapter.

Parameter
Type
Description

control

The control that has been created.

This method initializes the FullCalendarTools with the associated FullCalendar control and then calls the base implementation.

Implements

Name
Description

Represents a provider that supplies tools.

SmartAdapter
SmartCalendarAdapter
SmartTool(target, method)

Initializes a new instance of the SmartTool class with the specified target and method.

Name
Type
Description

target

The target object on which the method will be invoked.

method

The method to be invoked on the target object.

Throws:

  • ArgumentNullException Thrown when the method is null.

Properties

Description

String: Gets the description of the method.

FullName

String: Gets the full name of the method including the namespace.

Name

String: Gets the name of the method.

Namespace

String:

NamespaceDescription

String: Gets the description of the namespace.

Parameters

Parameter[]: Gets the parameters of the method.

ReturnType

Type: Gets the return type of the method.

Target

Object: Gets the object containing this tool.

Methods

GetParametersSchema()

Returns a JSON schema representing the tool's parameters or null when the function doesn't have arguments.

Returns: Object. JSON schema object

Public Class SmartTool
public class SmartTool
Embedding(chunks, vectors, model)

Initializes a new instance of the Embedding class with specified chunks, vectors, and model.

Name
Type
Description

chunks

An array of strings representing the data chunks to be embedded.

vectors

A jagged array of floats representing the vectors associated with the chunks.

model

A string representing the model used for embedding.

This constructor initializes the Embedding class by setting the provided data chunks, their corresponding vectors, and the embedding model. The chunks parameter is used to input the raw data which will be embedded. The vectors parameter provides the associated vector representations for these chunks. The model specifies the model name used in the embedding process. Here is an example of how to create an instance of the Embedding class:

Properties

Chunks

String[]: Gets the chunks of data that were embedded.

Model

String: Gets the model name used for embedding.

Vectors

Single[][]: Gets the vectors associated with the data chunks.

Methods

Add(embedding)

Adds the vectors and chunks from embedding .

Parameter
Type
Description

embedding

The instance providing the values to combine.

Returns: Embedding.

Clone()

Creates a deep copy of the current Embedding instance.

Returns: Embedding. A new Embedding instance that is a deep copy of the current instance.

Public Class Embedding
    Inherits ICloneable
public class Embedding : ICloneable
Name
Description

Assistant

Indicates that the message is from an assistant.

System

Indicates that the message is from the system.

ToolCalls

Indicates that the message involves tool calls.

ToolResults

Indicates that the message contains tool results.

User

Indicates that the message is from a user.

Used By

Name
Description

Adds a message with the specified role and content.

Gets or sets the role associated with the message.

Public Enum MessageRole As [Enum]
public enum MessageRole : Enum
GetApiKey(name, namePostfix, envPrefix)

Retrieves the API key associated with the specified name.

Parameter
Type
Description

name

The name of the API key to retrieve.

namePostfix

An optional postfix to remove from the name when searching for the key.

envPrefix

The prefix for environment variables. Default is "WISEJ_AI_APIKEY_".

Returns: String. The API key if found; otherwise, null.

This method first attempts to retrieve the API key from environment variables using the specified prefix. If not found, it attempts to read the key from a JSON configuration file located at the path defined by AI_PATH and APIKEYS_FILENAME.

Public Class ApiKeys
public class ApiKeys
ToolAttribute()

Creates a new instance of the ToolAttribute class.

ToolAttribute(name)

Creates a new instance of the ToolAttribute class initialized with the specified tool name .

Name
Type
Description

name

Properties

Name

String: Gets the name of the tool function when it should be different from the method name.

Public Class ToolAttribute
    Inherits Attribute
public class ToolAttribute : Attribute

SmartChartAdapter

Wisej.AI.Adapters.SmartChartAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartChartAdapter

Represents an adapter that enhances a chart control with AI features.

public class SmartChartAdapter : SmartAdapter

The SmartChartAdapter class extends the functionality of a chart control by integrating AI capabilities. It allows for dynamic chart generation and interaction based on the provided data source and prompt.

Constructors

SmartChartAdapter()

Initializes a new instance of the class.

Properties

DataSource

: Gets or sets the data source for the chart. (Default: null)

The data source is used by the AI to generate the chart based on the specified prompt.

DefaultChartType

: Gets or sets the default chart type to be used. (Default: "Bar")

Description

: Gets the description of the chart generated by the adapter.

The description is generated based on the AI response to the provided prompt and data source.

Prompt

: Gets or sets the prompt used to generate the chart. (Default: null)

Changing the prompt will trigger a re-run of the AI process if is enabled and controls are present.

Methods

OnControlCreated(control)

Called when a control is created and initializes the AI process if is enabled.

Parameter
Type
Description

RunAsyncCore(control)

Executes the core AI process asynchronously to generate a chart.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation, with a containing the AI response.

The method uses the provided data source and default chart type to interact with the AI session and generate a chart description.

Inherited By

Name
Description

Implements

Name
Description

SmartComboBoxAdapter

Wisej.AI.Adapters.SmartComboBoxAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartComboBoxAdapter

Adds semantic filtering to the ComboBox auto-complete functionality.

public class SmartComboBoxAdapter : SmartAdapter, IExtenderProvider

Works with the . Semantic filtering (items embedding) is entirely hosted on the user's browser and runs in JavaScript. Uses the HuggingFace TransformersJs library to run in-browser embeddings.

Constructors

SmartComboBoxAdapter()

Initializes a new instance of the class.

Properties

AutoRun

: Gets or sets a value indicating whether the adapter should run automatically. (Default: True)

Model

: Gets or sets the embeddings model. See for available models. The default is "Xenova/all-MiniLM-L6-v2". (Default: null)

Methods

GetSimilarity(control)

Gets the similarity level threshold needed for an item to qualify, ranging from 0.1 to 1.0 (1 means identical).

Parameter
Type
Description

Returns: . The minimum similarity level.

Throws:

  • Thrown when the control is null.

OnControlCreated(control)

Handles the event when a control is created.

Parameter
Type
Description

OnControlDisposed(control)

Handles the event when a control is disposed.

Parameter
Type
Description

SetSimilarity(control, value)

Sets the similarity level threshold for an item to qualify.

Parameter
Type
Description

Throws:

  • Thrown when the control is null.

  • Thrown when the value is not between 0 and 1.

Implements

Name
Description

LocalAIEndpointImageGen

Wisej.AI.Endpoints.LocalAIEndpointImageGen

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents an endpoint for connecting to LocalAI Image Generation services.

This class is used to interact with the LocalAI DallE API for generating images. It sets up the necessary authentication and model parameters required for the API requests.

Constructors

LocalAIEndpointImageGen()

Initializes a new instance of the class.

Sets default values for authentication, model, and URL specific to the DallE API.

Properties

Model

: Gets or sets the model used for the DallE API. (Default: "dall-e-3")

URL

: Gets or sets the URL for the DallE API endpoint. (Default: "https://api.LocalAI.com/v1/images/generations")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for the API request.

Parameter
Type
Description

Throws:

  • Thrown when any of the parameters are null.

ReadAssistantMessage(response, message)

Reads the assistant's message from the API response.

Parameter
Type
Description

Parses the response to extract image URLs or base64 encoded images and assigns them to the message.Throws:

  • Thrown when any of the parameters are null.

ReadUsage(message, reply)

Reads the usage information from the API response.

Parameter
Type
Description

This method does not process usage information as it is not returned by the API.

HuggingFaceEndpoint

Wisej.AI.Endpoints.HuggingFaceEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents a connection to HuggingFace serverless endpoints for model inference and embeddings.

This class is used to interact with HuggingFace's API for model inference and embeddings. It provides methods to construct API URLs, add options and messages to requests, and read responses.

Constructors

HuggingFaceEndpoint()

Initializes a new instance of the class with default settings.

Properties

EmbeddingModel

: Gets or sets the model used for generating embeddings. (Default: "sentence-transformers/all-MiniLM-L6-v2")

MaxOutputTokens

: Gets or sets the maximum number of output tokens. (Default: 2048)

Model

: Gets or sets the model used for inference. (Default: "meta-llama/Llama-3.2-11B-Vision-Instruct")

URL

: Gets or sets the base URL for the HuggingFace API. (Default: "https://api-inference.huggingface.co")

Methods

BuildEmbeddingsPayload(inputs)

Builds the payload for an embeddings request.

Parameter
Type
Description

Returns: . The constructed payload object.

This method constructs the payload for an embeddings request, including options such as wait_for_model.

GetApiURL()

Constructs the API URL for model inference.

Returns: . The constructed API URL.

GetEmbeddingsURL()

Constructs the API URL for embeddings.

Returns: . The constructed embeddings URL.

ReadEmbeddingsResponse(response)

Reads the embeddings from the API response.

Parameter
Type
Description

Returns: . A two-dimensional array of floats representing the embeddings.

This method parses the response to extract the embeddings data.

LocalAIEndpointTTS

Wisej.AI.Endpoints.LocalAIEndpointTTS

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents an endpoint for connecting to LocalAI's speech services.

This class is designed to interact with LocalAI's text-to-speech (TTS) API, allowing for the conversion of text into speech audio files.

Constructors

LocalAIEndpointTTS()

Initializes a new instance of the class with default settings.

The default model is set to "tts-1", and the voice option is "alloy". The response format is set to "mp3".

Properties

Model

: Gets or sets the model used for the TTS operation. (Default: "tts-1")

URL

: Gets or sets the URL for the LocalAI TTS API endpoint. (Default: "http://localhost:8080/v1/audio/speech")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for processing.

Parameter
Type
Description

Throws:

  • Thrown when session , payload , or messages is null.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response.

Parameter
Type
Description

Throws:

  • Thrown when response or message is null.

ReadUsage(message, reply)

Reads the usage information from the reply.

Parameter
Type
Description

This method does not return usage information as it is not applicable for TTS operations.

SmartQueryAdapter

Wisej.AI.Adapters.SmartQueryAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartQueryAdapter

Represents an adapter that generates a data set from a database schema and a user-provided description.

public class SmartQueryAdapter : SmartAdapter

The class is designed to interact with a database schema and generate SQL queries based on user input. It utilizes a to facilitate the query generation process.

Constructors

SmartQueryAdapter()

Initializes a new instance of the class.

Properties

Connection

: Gets or sets the database connection used to execute the query.

DataSource

: Gets or sets the data source binding for the query results.

Query

: Gets or sets the query description provided by the user.

When the property is set to true, setting this property will automatically execute the query asynchronously.

Schema

: Gets or sets the database schema used to generate the query.

ServerType

: Gets or sets the type of the database server. (Default: "Microsoft Sql Server")

SQL

: Gets the SQL statement generated from the query description.

Methods

GetSQL(message)

Returns the JSON string returned in the message by stripping the enclosing markers (sql and ) if present.

Parameter
Type
Description

Returns: . JSON string.

RunAsyncCore(control)

Asynchronously runs the core logic to generate and execute the SQL query.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation, with a result containing the query execution details.

Implements

Name
Description

SmartEndpoint.Response

Wisej.AI.SmartEndpoint Response

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a response that can be initialized with a stream or a string and provides methods to read its content.

public class Response
Public Class Response

Constructors

Response(stream)

Initializes a new instance of the class with the specified stream.

Name
Type
Description

Throws:

  • Thrown when the stream is null.

Response(response)

Initializes a new instance of the class with the specified string.

Name
Type
Description

Throws:

  • Thrown when the response is null.

Properties

Stream

: Gets a copy of the underlying stream.

The returned stream is a copy of the original stream, allowing for independent reading without affecting the original stream's position.

Methods

ReadBufferAsync()

Asynchronously reads the content of the response as a byte array.

Returns: . A task that represents the asynchronous read operation. The task result contains the content of the response as a byte array.

This method reads the entire content of the stream and returns it as a byte array.

ReadContentAsync()

Asynchronously reads the content of the response as a string.

Returns: . A task that represents the asynchronous read operation. The task result contains the content of the response as a string.

This method reads the entire content of the stream and returns it as a string.

SmartSession.ConvertParameterEventArgs

Wisej.AI.SmartSession ConvertParameterEventArgs

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

public class ConvertParameterEventArgs : HandledEventArgs
Public Class ConvertParameterEventArgs
    Inherits HandledEventArgs

Constructors

ConvertParameterEventArgs(session, name, value)

Initializes a new instance of the class with the specified parameter.

Name
Type
Description

Properties

Name

: Gets the name of the parameter.

Session

: Gets the associated with the event.

Value

: Gets or sets the value of the parameter after conversion.

Used By

Name
Description

OpenAIEndpointTTS

Wisej.AI.Endpoints.OpenAIEndpointTTS

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

LocalAIEndpointWhisper

Wisej.AI.Endpoints.LocalAIEndpointWhisper

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

OpenAIEndpointWhisper

Wisej.AI.Endpoints.OpenAIEndpointWhisper

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartAdapter.WorksWithAttribute

Wisej.AI.SmartAdapter WorksWithAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents an attribute that specifies the compatibility of a with a .

This attribute is used to indicate that a works with a specific . It can be applied multiple times to specify compatibility with different types.

SmartPictureBoxAdapter

Wisej.AI.Adapters.SmartPictureBoxAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

Represents an adapter for a PictureBox that generates images based on a description using the OpenAI DALL-E endpoint.

SmartTool.IToolProvider

Wisej.AI.SmartTool IToolProvider

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a provider that supplies tools.

Properties

SmartSession.MessageCollection

Wisej.AI.SmartSession MessageCollection

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a collection of messages in a session.

Constructors

SmartAudioWhisperAdapter

Wisej.AI.Adapters.SmartAudioWhisperAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

Transcribes the audio file of the of the associated control to its property in the original language of the audio.

EmbeddedDocument

Wisej.AI.Embeddings.EmbeddedDocument

Namespace: Wisej.AI.Embeddings

Assembly: Wisej.AI (3.5.0.0)

Represents a document that can be embedded with metadata and embedding data.

The class is designed to hold information about a document that can be embedded within a system. It contains properties for the document's name, metadata, and embedding data. This class provides constructors for initializing a document with or without embedding data. The embedded documents can be used in systems that require document similarity measures or need to store additional metadata for each document.

SmartAgentPrompt

Wisej.AI.SmartAgentPrompt

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

OpenAIEndpointDallE

Wisej.AI.Endpoints.OpenAIEndpointDallE

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

> User: Hello
> Assistant: Hello! How can I assist you today?
> User: Tell me something nice
> Assistant: You are capable of achieving great things, and your 
             potential is limitless. Remember, every day is a new opportunity 
             to grow and make a positive impact. Keep shining bright!

  string[] chunks = { "data1", "data2" };
  float[][] vectors = { new float[] { 1.0f, 2.0f }, new float[] { 3.0f, 4.0f } };
  string model = "exampleModel";
  Embedding embedding = new Embedding(chunks, vectors, model);

string apiKey = ApiKeys.GetApiKey("MyService", "Postfix");
if (apiKey != null)
{
// Use the API key
}
9

SmartEndpoint

1
648
9

SmartHub

1
648
9
34

SmartEndpoint

2
1312
43

SmartHub

2
1312
43
SmartPrompt
SmartSession
SmartSession.Message
SmartEndpoint
SmartHub
MessageCollection.Add
Message.Role

control

Control

The control that was created.

control

Control

The control for which the chart is generated.

SmartChartJS3Adapter

Represents an adapter that enhances a ChartJS control with several AI features.

IToolProvider

Represents a provider that supplies tools.

Public Class SmartChartAdapter
    Inherits SmartAdapter
SmartChartAdapter
Object
String
String
String
AutoRun
AutoRun
Task<Message>
Message

control

Control

The control for which to get the similarity level.

control

Control

The control that was created.

control

Control

The control that was disposed.

control

Control

The control for which to set the similarity level.

value

Double

The similarity level, must be between 0 and 1.

IToolProvider

Represents a provider that supplies tools.

Public Class SmartComboBoxAdapter
    Inherits SmartAdapter
    Implements IExtenderProvider
HuggingFaceJavaScriptEndpoint
SmartComboBoxAdapter
Boolean
String
index
Double
ArgumentNullException
ArgumentNullException
ArgumentException

message

Message

Message with the response text that may be a JSON string.

control

Control

The control associated with the operation, if any.

IToolProvider

Represents a provider that supplies tools.

Public Class SmartQueryAdapter
    Inherits SmartAdapter
SmartQueryAdapter
SmartPrompt
SmartQueryAdapter
IDbConnection
BindingSource
String
AutoRun
DataTable
String
String
String
Task<Message>
Message

stream

Stream

The stream to initialize the response with.

response

String

The string to initialize the response with.

Response
ArgumentNullException
Response
ArgumentNullException
Stream
Task<Byte[]>
Task<String>

session

SmartSession

The session associated with the event.

name

String

The name of the parameter to be converted.

value

Object

Value to convert

SmartSession.ConvertParameterEventHandler

ConvertParameterEventArgs
String
SmartSession
SmartSession
Object
SmartSession
Exception
Message
SmartSession.ErrorEventHandler
Control
IToolProvider
Object
MethodInfo
String[]
Single[][]
String
Embedding
Embedding
String
String
String
String

payload

Object

The dynamic payload object to be sent to the API.

session

SmartSession

The current session containing user context.

messages

IList<Message>

The list of messages to be processed.

response

Response

The response received from the API.

message

Message

The message object to populate with the response data.

message

Message

The message object to populate with usage data.

reply

Object

The dynamic reply object containing the response data.

LocalAIEndpointImageGen
Public Class LocalAIEndpointImageGen
    Inherits SmartHttpEndpoint
LocalAIEndpointImageGen
String
String
ArgumentNullException
ArgumentNullException
public class LocalAIEndpointImageGen : SmartHttpEndpoint

inputs

String[]

The input strings for which embeddings are requested.

response

Response

The API response containing the embeddings.

OpenAIEndpoint
HuggingFaceEndpoint
Public Class HuggingFaceEndpoint
    Inherits OpenAIEndpoint
HuggingFaceEndpoint
String
Int32
String
String
Object
String
String
Single[][]
public class HuggingFaceEndpoint : OpenAIEndpoint

payload

Object

The dynamic payload object to be sent to the API.

session

SmartSession

The current session containing user context.

messages

IList<Message>

A list of messages to be processed.

response

Response

The response received from the API.

message

Message

The message object to populate with the response data.

message

Message

The message object to populate with usage data.

reply

Object

The dynamic reply object containing usage information.

LocalAIEndpointTTS
Public Class LocalAIEndpointTTS
    Inherits SmartHttpEndpoint
LocalAIEndpointTTS
String
String
ArgumentNullException
ArgumentNullException
public class LocalAIEndpointTTS : SmartHttpEndpoint
OpenAIEndpointTTS

Represents an endpoint for connecting to OpenAI's speech services.

public class OpenAIEndpointTTS : SmartHttpEndpoint
Public Class OpenAIEndpointTTS
    Inherits SmartHttpEndpoint

This class is designed to interact with OpenAI's text-to-speech (TTS) API, allowing for the conversion of text into speech audio files.

Constructors

OpenAIEndpointTTS()

Initializes a new instance of the OpenAIEndpointTTS class with default settings.

The default model is set to "tts-1", and the voice option is "alloy". The response format is set to "mp3".

Properties

Model

String: Gets or sets the model used for the TTS operation. (Default: "tts-1")

URL

String: Gets or sets the URL for the OpenAI TTS API endpoint. (Default: "https://api.openai.com/v1/audio/speech")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for processing.

Parameter
Type
Description

payload

The dynamic payload object to be sent to the API.

session

The current session containing user context.

messages

A list of messages to be processed.

Throws:

  • ArgumentNullException Thrown when session , payload , or messages is null.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response.

Parameter
Type
Description

response

The response received from the API.

message

The message object to populate with the response data.

Throws:

  • ArgumentNullException Thrown when response or message is null.

ReadUsage(message, reply)

Reads the usage information from the reply.

Parameter
Type
Description

message

The message object to populate with usage data.

reply

The dynamic reply object containing usage information.

This method does not return usage information as it is not applicable for TTS operations.

SmartEndpoint
SmartHttpEndpoint
LocalAIEndpointWhisper

Represents an endpoint for connecting to LocalAI's Whisper model for speech-to-text transcriptions.

public class LocalAIEndpointWhisper : SmartHttpEndpoint
Public Class LocalAIEndpointWhisper
    Inherits SmartHttpEndpoint

This class is designed to interact with LocalAI's Whisper model, providing functionality to send audio data and receive transcriptions. It extends the SmartHttpEndpoint to leverage HTTP communication.

Constructors

LocalAIEndpointWhisper()

Initializes a new instance of the LocalAIEndpointWhisper class with default settings.

Sets the authentication method to "Bearer", the model to "whisper-1", and the response format to "text". The URL is set to LocalAI's audio transcription endpoint.

Properties

Model

String: Gets or sets the model used for transcription. (Default: "whisper-1")

URL

String: Gets or sets the URL for the LocalAI audio transcription endpoint. (Default: "http://localhost:8080/v1/audio/transcriptions")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for the request.

Parameter
Type
Description

payload

The payload to which messages will be added.

session

The current session containing user data.

messages

The list of messages to be processed.

Throws:

  • ArgumentNullException Thrown if any of the parameters are null.

CreateContent(data)

Creates the HTTP content for the request using the provided data.

Parameter
Type
Description

data

The data to be included in the request content.

Returns: HttpContent. A HttpContent object containing the request data.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response and updates the message object.

Parameter
Type
Description

response

The response received from the server.

message

The message object to be updated with the assistant's reply.

Throws:

  • ArgumentNullException Thrown if any of the parameters are null.

ReadUsage(message, reply)

Reads the usage information from the reply. Not supported in this implementation.

Parameter
Type
Description

message

The message object to be updated with usage information.

reply

The reply containing usage data.

SmartEndpoint
SmartHttpEndpoint
OpenAIEndpointWhisper

Represents an endpoint for connecting to OpenAI's Whisper model for speech-to-text transcriptions.

public class OpenAIEndpointWhisper : SmartHttpEndpoint
Public Class OpenAIEndpointWhisper
    Inherits SmartHttpEndpoint

This class is designed to interact with OpenAI's Whisper model, providing functionality to send audio data and receive transcriptions. It extends the SmartHttpEndpoint to leverage HTTP communication.

Constructors

OpenAIEndpointWhisper()

Initializes a new instance of the OpenAIEndpointWhisper class with default settings.

Sets the authentication method to "Bearer", the model to "whisper-1", and the response format to "text". The URL is set to OpenAI's audio transcription endpoint.

Properties

Model

String: Gets or sets the model used for transcription. (Default: "whisper-1")

URL

String: Gets or sets the URL for the OpenAI audio transcription endpoint. (Default: "https://api.openai.com/v1/audio/transcriptions")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for the request.

Parameter
Type
Description

payload

The payload to which messages will be added.

session

The current session containing user data.

messages

The list of messages to be processed.

Throws:

  • ArgumentNullException Thrown if any of the parameters are null.

CreateContent(data)

Creates the HTTP content for the request using the provided data.

Parameter
Type
Description

data

The data to be included in the request content.

Returns: HttpContent. A HttpContent object containing the request data.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response and updates the message object.

Parameter
Type
Description

response

The response received from the server.

message

The message object to be updated with the assistant's reply.

Throws:

  • ArgumentNullException Thrown if any of the parameters are null.

ReadUsage(message, reply)

Reads the usage information from the reply. Not supported in this implementation.

Parameter
Type
Description

message

The message object to be updated with usage information.

reply

The reply containing usage data.

SmartEndpoint
SmartHttpEndpoint
Constructors

WorksWithAttribute(type, allowed)

Initializes a new instance of the WorksWithAttribute class with the specified type and allowed status.

Name
Type
Description

type

The type that the class works with. Must be a subclass of .

allowed

Indicates whether the type is allowed. Default is true.

Throws:

  • ArgumentNullException Thrown when the type is null.

  • ArgumentException Thrown when the type is not a subclass of SmartEndpoint.

WorksWithAttribute(type, allowed)

Initializes a new instance of the WorksWithAttribute class with the specified type name and allowed status.

Name
Type
Description

type

The name of the type that the class works with. Must be a subclass of .

allowed

Indicates whether the type is allowed. Default is true.

Throws:

  • ArgumentNullException Thrown when the type is null.

  • ArgumentException Thrown when the type is not a subclass of SmartEndpoint.

Properties

Allowed

Boolean: Gets a value indicating whether the SmartEndpoint is allowed.

Type

Type: Gets the SmartEndpoint that the attribute allows or disallows.

TypeName

String: Gets the type name of the SmartEndpoint that the attribute allows or disallows.

SmartAdapter
SmartEndpoint
Public Class WorksWithAttribute
    Inherits Attribute
SmartAdapter
SmartEndpoint
SmartEndpoint
public class WorksWithAttribute : Attribute
Public Class SmartPictureBoxAdapter
    Inherits SmartAdapter

This adapter extends the functionality of a PictureBox by allowing it to generate images from text descriptions. It works with the OpenAI DALL-E endpoint and supports different image formats and sizes.

Constructors

SmartPictureBoxAdapter()

Initializes a new instance of SmartPictureBoxAdapter.

Properties

ImageFormat

String: Gets or sets the format in which the generated images are returned. Must be one of "url" or "b64_json". (Default: "url")

ImageSize

String: Gets or sets the size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Smaller images are faster. (Default: "1024x1024")

For DALL-E-2, image sizes must be one of "256x256", "512x512", or "1024x1024". When using DALL-E-3, images can have a size of 1024x1024, 1024x1792, or 1792x1024 pixels.

Methods

OnControlCreated(control)

Handles the event when the control is created.

Parameter
Type
Description

control

The control that was created.

OnControlDisposed(control)

Handles the event when the control is disposed.

Parameter
Type
Description

control

The control that was disposed.

RunAsyncCore(control)

Asynchronously runs the core logic for generating an image based on the control's text.

Parameter
Type
Description

control

The control containing the text description.

Returns: Task<Message>. A task representing the asynchronous operation, with a Message result containing the generated image or image URL.

Throws:

  • ArgumentNullException Thrown when the control is null.

Implements

Name
Description

Represents a provider that supplies tools.

SmartAdapter
SmartPictureBoxAdapter
public class SmartPictureBoxAdapter : SmartAdapter
HasTools

Boolean: Gets a value indicating whether the provider has any tools available.

Tools

ToolCollection: Gets the collection of tools available from the provider.

Implemented By

Name
Description

TODO:

Represents a smart parallel prompt that can execute multiple tasks concurrently.

Represents an abstract base class for creating smart adapters that interact with AI endpoints.

Represents a SmartHub component that provides AI capabilities to controls within a container.

Represents a smart prompt component that can process and manage prompts with tools and parameters.

Converts the of the associated control into lifelike speech.

Public Interface IToolProvider
public interface IToolProvider
MessageCollection()

Initializes a new instance of MessageCollection.

Methods

Add(role, content)

Adds a message with the specified role and content.

Parameter
Type
Description

role

The role of the message.

content

The content of the message.

Returns: MessageCollection. The current MessageCollection instance.

Throws:

  • ArgumentNullException Thrown when the content is null.

AddRange(messages)

Adds a range of messages to the collection.

Parameter
Type
Description

messages

The messages to add.

Returns: MessageCollection. The current MessageCollection instance.

Clone()

Creates a shallow clone of the collection.

Returns: MessageCollection. A shallow clone of the MessageCollection.

InsertItem(index, item)

Inserts a message at the specified index.

Parameter
Type
Description

index

The zero-based index at which the message should be inserted.

item

The message to insert.

MoveItem(oldIndex, newIndex)

Moves a message from one index to another.

Parameter
Type
Description

oldIndex

The zero-based index specifying the location to move from.

newIndex

The zero-based index specifying the location to move to.

RemoveAll(predicate)

Removes all messages that match the specified predicate.

Parameter
Type
Description

predicate

The predicate to match messages.

Returns: MessageCollection. The current MessageCollection instance.

RemoveLast(count)

Removes the last message(s) from the collection.

Parameter
Type
Description

count

The number of messages to remove. Default is 1.

Returns: MessageCollection. The current MessageCollection instance.

Public Class MessageCollection
    Inherits ObservableCollection(Of )
    Implements ICloneable
public class MessageCollection : ObservableCollection<>, ICloneable
Public Class SmartAudioWhisperAdapter
    Inherits SmartAdapter

Works with:

  • OpenAI Whisper

  • GroqCloud Whisper

Set the SourceURL property of the associated Audio control to the audio file that you want to transcribe to text. When AutoRun is true and the user presses the play button the adapter will automatically start the transcription. If AutoRun is set to false, use RunAsync (where control is the Audio control) to start the transcription. You can use the SystemPrompt to improve the quality of the transcripts generated by the Whisper model. The model will try to match the style of the prompt, so it will be more likely to use capitalization and punctuation if the prompt does too. For more information prompting.

Constructors

SmartAudioWhisperAdapter()

Initializes a new instance of SmartAudioWhisperAdapter.

Methods

OnControlDisposed(control)

Parameter
Type
Description

control

RegisterControl(control)

Parameter
Type
Description

control

RunAsyncCore(control)

Parameter
Type
Description

control

Returns: Task<Message>.

Implements

Name
Description

Represents a provider that supplies tools.

SmartAdapter
SmartAudioWhisperAdapter
Audio
Text
speech-to-text
public class SmartAudioWhisperAdapter : SmartAdapter
Constructors

EmbeddedDocument(name, metadata, embedding)

Initializes a new instance of the EmbeddedDocument class with the specified name, metadata, and embedding.

Name
Type
Description

name

The name of the document. Cannot be null.

metadata

Optional metadata associated with the document. If null, a new instance is created.

embedding

Optional embedding data for the document.

Throws:

  • ArgumentNullException Thrown when name is null.

Properties

Metadata

Metadata: Gets the metadata of the document.

Name

String: Gets the name of the document.

Methods

Clone(includeEmbedding)

Creates a deep copy of the current EmbeddedDocument instance.

Parameter
Type
Description

includeEmbedding

Whether to clone the embeddings.

Returns: EmbeddedDocument. A new EmbeddedDocument instance that is a deep copy of the current instance.

GetEmbedding()

Retrieves the embedding data associated with the document.

Returns: Embedding. The embedding data of the document.

GetMatches()

Returns: Matches.

SetEmbedding(embedding)

Sets the embedding data for the document.

Parameter
Type
Description

embedding

The embedding data to set for the document.

Returns: EmbeddedDocument. The current instance of EmbeddedDocument with updated embedding data.

Use this method to update the embedding data of an existing document. This might be necessary when the document's context or representation changes.

SetMatches(matches)

Parameter
Type
Description

matches

Returns: EmbeddedDocument.

Public Class EmbeddedDocument
    Inherits ICloneable
EmbeddedDocument
public class EmbeddedDocument : ICloneable
SmartAgentPrompt

TODO:

public class SmartAgentPrompt : SmartPrompt
Public Class SmartAgentPrompt
    Inherits SmartPrompt

Constructors

SmartAgentPrompt(text)

Initializes a new instance of the SmartAgentPrompt class with optional text.

Name
Type
Description

text

The text associated with the prompt. Default is null.

Methods

RunAgentAsync(adapter, message)

Executes the agent request asynchronously with the specified sender and message.

Parameter
Type
Description

adapter

The sender adapter initiating the request.

message

Message to send to the agent for processing.

Returns: Task<Message>. A task representing the asynchronous operation, with a Message as the result.

Throws:

  • InvalidOperationException Thrown when the SmartAdapter is busy.

  • ArgumentNullException Thrown when the sender is null.

Subscribe(adapter)

Subscribes the agent to the specified adapter.

Parameter
Type
Description

adapter

The adapter to which the agent will be subscribed.

Throws:

  • ArgumentNullException Thrown when the adapter is null.

Unsubscribe(adapter)

Unsubscribes the agent from the specified adapter.

Parameter
Type
Description

adapter

The adapter from which the agent will be unsubscribed.

Throws:

  • ArgumentNullException Thrown when the adapter is null.

Implements

Name
Description

Represents a provider that supplies tools.

SmartObject
SmartPrompt
OpenAIEndpointDallE

Represents an endpoint for connecting to OpenAI DallE services.

public class OpenAIEndpointDallE : SmartHttpEndpoint
Public Class OpenAIEndpointDallE
    Inherits SmartHttpEndpoint

This class is used to interact with the OpenAI DallE API for generating images. It sets up the necessary authentication and model parameters required for the API requests.

Constructors

OpenAIEndpointDallE()

Initializes a new instance of the OpenAIEndpointDallE class.

Sets default values for authentication, model, and URL specific to the DallE API.

Properties

Model

String: Gets or sets the model used for the DallE API. (Default: "dall-e-3")

URL

String: Gets or sets the URL for the DallE API endpoint. (Default: "https://api.openai.com/v1/images/generations")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for the API request.

Parameter
Type
Description

payload

The dynamic payload object to be sent to the API.

session

The current session containing user context.

messages

The list of messages to be processed.

Throws:

  • ArgumentNullException Thrown when any of the parameters are null.

ReadAssistantMessage(response, message)

Reads the assistant's message from the API response.

Parameter
Type
Description

response

The response received from the API.

message

The message object to populate with the response data.

Parses the response to extract image URLs or base64 encoded images and assigns them to the message.Throws:

  • ArgumentNullException Thrown when any of the parameters are null.

ReadUsage(message, reply)

Reads the usage information from the API response.

Parameter
Type
Description

message

The message object to populate with usage data.

reply

The dynamic reply object containing the response data.

This method does not process usage information as it is not returned by the API.

SmartEndpoint
SmartHttpEndpoint

AzureAIEndpoint

Wisej.AI.Endpoints.AzureAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents an endpoint for connecting to Azure AI services, specifically designed to interact with OpenAI models.

This class provides properties and methods to configure and interact with Azure AI endpoints, allowing for operations such as generating text completions and embeddings.

Constructors

AzureAIEndpoint()

Initializes a new instance of the class with default settings.

Properties

ApiVersion

: Gets or sets the API version used for requests. (Default: "2024-02-01")

Authentication

: Gets or sets the authentication method for the endpoint. (Default: "api-key")

EmbeddingModel

: Gets or sets the model used for generating text embeddings. (Default: "text-embedding-3-small")

Model

: Gets or sets the model used for generating text completions. (Default: "gpt-4o")

URL

: Gets or sets the URL of the Azure AI endpoint. (Default: "https://YOUR_RESOURCE_NAME.openai.azure.com")

Methods

AddOptions(message, session)

Adds options to the message for a session.

Parameter
Type
Description

BuildEmbeddingsPayload(inputs)

Builds the payload for an embeddings request.

Parameter
Type
Description

Returns: . An object representing the payload for the embeddings request.

Throws:

  • Thrown when inputs is null.

GetApiURL()

Constructs the API URL for text completion requests.

Returns: . A string representing the API URL.

GetEmbeddingsURL()

Constructs the API URL for embedding requests.

Returns: . A string representing the embeddings API URL.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response.

Parameter
Type
Description

Throws:

  • Thrown when response or message is null.

ReadEmbeddingsResponse(response)

Reads the embeddings from the response.

Parameter
Type
Description

Returns: . A jagged array of floats representing the embeddings.

Throws:

  • Thrown when response is null.

ReadUsage(message, reply)

Reads the usage statistics from the reply and updates the message.

Parameter
Type
Description

GroqCloudEndpointWhisper

Wisej.AI.Endpoints.GroqCloudEndpointWhisper

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents a connection to GroqCloud speech endpoints for audio transcription.

This class is used to interact with the GroqCloud API for converting audio inputs into text transcriptions using the Whisper model.

Constructors

GroqCloudEndpointWhisper()

Initializes a new instance of the class with default settings.

Sets the default authentication method, model, response format, and API URL.

Properties

Model

: Gets or sets the model used for audio transcription. (Default: "whisper-large-v3")

URL

: Gets or sets the URL for the GroqCloud API endpoint. (Default: "https://api.groq.com/openai/v1/audio/transcriptions")

Methods

AddMessages(payload, session, messages)

Adds user messages to the payload for the API request.

Parameter
Type
Description

This method extracts the last user message and adds its binary and text content to the payload.

CreateContent(data)

Creates the HTTP content for the request.

Parameter
Type
Description

Returns: . A object containing the request data.

This method constructs a multipart form data content from the provided data, supporting both binary and string content.

ReadAssistantMessage(response, message)

Reads the assistant's message from the API response.

Parameter
Type
Description

This method parses the response content and updates the message text accordingly.

ReadUsage(message, reply)

Reads the usage information from the API reply.

Parameter
Type
Description

This functionality is not supported in the current implementation.

Metadata

Wisej.AI.Embeddings.Metadata

Namespace: Wisej.AI.Embeddings

Assembly: Wisej.AI (3.5.0.0)

Represents metadata that can store key-value pairs with case-insensitive keys. Implements the ISerializable interface for JSON serialization.

public class Metadata : ISerializable
Public Class Metadata
    Inherits ISerializable

Constructors

Metadata()

Initializes a new instance of the class with empty data.

Metadata(data)

Initializes a new instance of the class with the specified initial data.

Name
Type
Description

Metadata(data)

Initializes a new instance of the class with data from a .

Name
Type
Description

Properties

Item(name)

: Gets or sets the value associated with the specified name.

Throws:

  • Thrown when setting a value that is not of type string, number, boolean, or date.

Methods

Clone()

Creates a new instance of the class that is a copy of the current instance.

Returns: . A new object that is a copy of this instance.

This method creates a deep copy of the current metadata, allowing modifications to the clone without affecting the original.

GetProperties()

Retrieves all property names within the metadata.

Returns: . An array of strings containing all property names.

This method returns the keys of all stored metadata entries as an array of strings. If the metadata is empty, it returns an empty array.

Remove(keys)

Removes metadata entries with the specified keys.

Parameter
Type
Description

This method will iterate through the provided keys and remove the corresponding entries from the metadata. If the metadata is empty or the keys do not exist, the method does nothing.

SmartAudioTTSAdapter

Wisej.AI.Adapters.SmartAudioTTSAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartAudioTTSAdapter

Converts the Text of the associated Audio control into lifelike speech.

public class SmartAudioTTSAdapter : SmartAdapter

This class works with the OpenAI TTS platform to generate audio from text. To use this adapter, set the Text property of the control to the desired text. If is true, the audio is generated automatically when the text changes. The input text is limited to 4096 characters. If is false, call with the control to generate the audio. The generated audio file is saved in the directory at the root of the project. The file name is a combination of the control's and a unique hash code, with the extension specified by .

Constructors

SmartAudioTTSAdapter()

Initializes a new instance of .

Properties

AudioFilesPath

: Gets or sets the path where audio files are stored. (Default: "~AI\AudioFiles")

The path should be relative to the application's root folder to allow the audio control to download the audio as a regular URL.

AudioFormat

: Gets or sets the audio format for the generated speech. (Default: "mp3")

The default format is "mp3". Other available formats include "opus", "aac", "flac", and "pcm".

Speed

: Gets or sets the speed of the generated audio. (Default: 1)

The speed can range from 0.25 to 4.0, with 1.0 as the default value.

Voice

: Gets or sets the voice to use for speech synthesis. (Default: "Alloy")

The available voices are optimized for English. Supported voices include: Alloy (default), Echo, Fable, Onyx, Nova, and Shimmer. New voices can be used as they become available.

Methods

OnControlCreated(control)

Parameter
Type
Description

OnControlDisposed(control)

Parameter
Type
Description

RunAsyncCore(control)

Asynchronously generates audio from the text of the specified control.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation, with a result containing the response.

Throws:

  • Thrown if or is null or empty.

Implements

Name
Description

SmartAdapter.ExtendsAttribute

Wisej.AI.SmartAdapter ExtendsAttribute

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents an attribute that specifies the type a SmartAdapter extends, allowing for multiple extensions if specified.

public class ExtendsAttribute : Attribute
Public Class ExtendsAttribute
    Inherits Attribute

This attribute can be applied to SmartAdapter classes to indicate that they extend a particular type. It supports specifying the type either by a Type object or by a type name string.

Constructors

ExtendsAttribute(type, allowMultiple)

Initializes a new instance of the class with the specified type.

Name
Type
Description

Throws:

  • Thrown when the type is null.

ExtendsAttribute(typeName, allowMultiple)

Initializes a new instance of the class with the specified type name.

Name
Type
Description

Throws:

  • Thrown when the typeName is null.

Properties

AllowMultiple

: Gets a value indicating whether the adapter can extend multiple controls.

Type

: Gets the object that the class extends.

If the type was specified by name, this property attempts to resolve it to a object.

TypeName

: Gets the name of the type that the adapter can extend.

AI Providers

Supported AI providers

Overview

Wisej.AI is compatible with any LLM provider, whether it's on a public cloud, a private deployment, or a local server. Most providers offer a REST API that is compatible with the OpenAI API. In such cases, if you need to add a new SmartEndpoint, you can either use the SmartOpenAIEndpoint and specify a different URL or create a derived class.

Typically, private models are hosted exclusively by their owners. In contrast, open-source models can be hosted by various providers and can also be deployed on proprietary hardware.

The currently available implementations include:

HuggingFaceJavaScriptEndpoint

Wisej.AI.Endpoints.HuggingFaceJavaScriptEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

Represents an endpoint that uses the transformers.js module in the user's browser to provide AI services to Wisej.AI components.

SmartExtensions

Wisej.AI.SmartExtensions

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Provides extension methods for various operations such as calculating cosine similarity, computing clusters, converting strings to camel case, and managing services in a service provider.

Methods

AmazonBedrockEndpoint

Wisej.AI.Endpoints.AmazonBedrockEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

SmartCopilotAdapter

Wisej.AI.Adapters.SmartCopilotAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

Turns the control into a AI-powered assistant. It can control and navigate an application, click menu items, navigation bar items, buttons, etc. It can also invoke methods in your applications as needed (see ).

SmartEndpoint.Metrics

Wisej.AI.SmartEndpoint Metrics

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents a collection of metrics related to token usage and call counts.

This class is used to track and manipulate metrics such as input tokens, output tokens, and the number of calls.

Constructors


  var document = new EmbeddedDocument("SampleDoc");
  var newEmbedding = new Embedding();
  document.SetEmbedding(newEmbedding);

control

Control

control

Control

control

Control

The control containing the text to convert to audio.

IToolProvider

Represents a provider that supplies tools.

Public Class SmartAudioTTSAdapter
    Inherits SmartAdapter
Audio
AutoRun
AutoRun
RunAsync
Audio
AudioFilesPath
Audio
Name
AudioFormat
SmartAudioTTSAdapter
String
String
Single
String
Task<Message>
Message
ArgumentNullException
AudioFormat
Voice

type

Type

The type that the class extends.

allowMultiple

Boolean

Indicates whether multiple extensions are allowed. Default is false.

typeName

String

The name of the type that the class extends.

allowMultiple

Boolean

Indicates whether multiple extensions are allowed. Default is false.

ExtendsAttribute
ArgumentNullException
ExtendsAttribute
ArgumentNullException
Boolean
Type
Type
Type
String
Object
SmartSession
IList<Message>
Response
Message
Message
Object
Object
SmartSession
IList<Message>
Object
Response
Message
Message
Object
Object
SmartSession
IList<Message>
Object
Response
Message
Message
Object
Type
SmartEndpoint
Boolean
String
SmartEndpoint
Boolean
Control
Control
Control
IToolProvider

SmartAudioWhisperAdapter

Transcribes the audio file of the of the associated Audio control to its Text property in the original language of the audio. speech-to-text

SmartCalendarAdapter

Represents a smart calendar adapter that extends the functionality of a SmartAdapter.

SmartChartAdapter

Represents an adapter that enhances a chart control with AI features.

SmartChartJS3Adapter

Represents an adapter that enhances a ChartJS control with several AI features.

SmartChatBoxAdapter

Turns the ChatBox control into a AI-powered bot. It can answer any question (depending on the AI model being used) and can invoke methods in your applications as needed (see SmartTool).

SmartComboBoxAdapter

Adds semantic filtering to the ComboBox auto-complete functionality.

SmartCopilotAdapter

Turns the ChatBox control into a AI-powered assistant. It can control and navigate an application, click menu items, navigation bar items, buttons, etc. It can also invoke methods in your applications as needed (see SmartTool).

SmartDataEntryAdapter

Enhances all the controls in the associated container with the AI-powered capability to extract structured data from unstructured text.

SmartDocumentAdapter

Represents a document adapter that can perform AI tasks using a document as a data source and interact with the user through a ChatBox control.

SmartFullCalendarAdapter

SmartObjectAdapter

Converts unstructured text into a structured .NET object.

SmartPictureBoxAdapter

Represents an adapter for a PictureBox that generates images based on a description using the OpenAI DALL-E endpoint.

SmartQueryAdapter

Represents an adapter that generates a data set from a database schema and a user-provided description.

SmartRealtimeAdapter

Represents a smart adapter that provides real-time data processing capabilities for use with the OpenAIEndpointRealtime endpoint.

SmartReportAdapter

Enhances the ChatBox control to allow seamless PDF report queries using an AI provider.

SmartTextBoxAdapter

Enhances a TextBox control with several AI features, including suggestions, translation, and auto-correction.

SmartAgentPrompt
SmartParallelPrompt
SmartAdapter
SmartHub
SmartPrompt
SmartAudioTTSAdapter
Text
Audio
MessageRole
String
IList<Message>
Int32
Message
Int32
Int32
Predicate<Message>
Int32
Control
Control
Control
IToolProvider
String
Metadata
Metadata
Embedding
Boolean
Embedding
Matches
String
SmartAdapter
Message
SmartAdapter
SmartAdapter
IToolProvider
Object
SmartSession
IList<Message>
Response
Message
Message
Object

message

Object

The message to which options are added.

session

SmartSession

The session context.

inputs

String[]

The input strings for which embeddings are requested.

response

Response

The response from the API.

message

Message

The message object to populate.

response

Response

The response from the API.

message

Message

The message object to update.

reply

Object

The dynamic reply object containing usage data.

AzureAIEndpoint
Public Class AzureAIEndpoint
    Inherits SmartHttpEndpoint
AzureAIEndpoint
String
String
String
String
String
Object
ArgumentNullException
String
String
ArgumentNullException
Single[][]
ArgumentNullException
public class AzureAIEndpoint : SmartHttpEndpoint

payload

Object

The payload to be sent to the API.

session

SmartSession

The current session containing user data.

messages

IList<Message>

The list of messages to be processed.

data

Object

The data to be included in the request.

response

Response

The response received from the API.

message

Message

The message object to populate with the response data.

message

Message

The message object to update with usage data.

reply

Object

The reply data from the API.

GroqCloudEndpointWhisper
Public Class GroqCloudEndpointWhisper
    Inherits SmartHttpEndpoint
GroqCloudEndpointWhisper
String
String
HttpContent
HttpContent
public class GroqCloudEndpointWhisper : SmartHttpEndpoint

data

IDictionary<String, Object>

Initial data to populate the metadata. If data is null, an empty metadata is created.

data

DynamicObject

A DynamicObject containing initial data. If data is null, an empty metadata is created.

keys

String[]

An array of keys identifying the metadata entries to remove.

Metadata
Metadata
Metadata
DynamicObject
Object
ArgumentException
Metadata
Metadata
Metadata
String[]

  var original = new Metadata();
  var clone = original.Clone();

  var metadata = new Metadata();
  var properties = metadata.GetProperties();

  var metadata = new Metadata();
  metadata["key1"] = "value1";
  metadata.Remove("key1");
Name
URL
Features

OpenAI

1, 3, 4, 7

OpenAITTS

1, 5

OpenAIDallE

1, 7

OpenAIWhisper

1, 6

Notes:

  1. Proprietary models

  2. Open source models

  3. Embeddings

  4. Vision

  5. Text to Speech

  6. Speech to Text

  7. Imaging

Local Hosting

By "Local Hosting," we refer to using a server to provide AI features outside the typical cloud services. This server could be located on-premises, housed in a data center, or hosted as a virtual machine instance with any cloud provider. This setup offers flexibility in deploying AI solutions by allowing organizations to have more control over their data and resources while still benefiting from sophisticated AI capabilities.

Wisej.AI can seamlessly integrate with any non-cloud server, providing flexibility and adaptability in deploying AI features. One of the most common types of servers used for this purpose is Ollama, which allows for efficient hosting of AI models and services. This capability ensures that you can leverage Wisej.AI's advanced functionalities, whether your infrastructure is cloud-based or locally hosted.

To use an Ollama server, instantiate the OllamaEndpoint and provide the URL of your server:

To use other local servers, such as vLLM, Localai, LM Studio, and others, you can most likely use or extend the OpenAIEndpoint. This provides the flexibility to integrate a variety of servers seamlessly.

Another excellent local server option is LocalAI. It offers an API compatible with OpenAI and supports a comprehensive range of features. These features include text completion, embedding, image generation, text-to-speech, speech-to-text, and re-ranking.

Public Class HuggingFaceJavaScriptEndpoint
    Inherits SmartEndpoint

This class is part of the SmartEndpoint category and is designed to interact with the Hugging Face transformers.js library. It provides various AI services such as text generation, translation, and more, by utilizing different pipelines.

Constructors

HuggingFaceJavaScriptEndpoint()

Initializes a new instance of the HuggingFaceJavaScriptEndpoint.

Properties

Id

String: Gets the unique identifier for the component.

Model

String: Gets or sets the model used by the endpoint. (Default: null)

Pipeline

TransformersPipeline: Gets or sets the pipeline used by the endpoint. (Default: None)

The pipeline determines the type of AI service provided, such as translation or text generation. index

PipelineSubtask

String: Gets or sets the subtask for the selected pipeline. (Default: "")

This property allows further specification of the task within the chosen pipeline. index

SourceURL

String: Gets or sets the source URL for the transformers.js library. (Default: "https://cdn.jsdelivr.net/npm/@xenova/transformers")

Methods

AskAsync(session, messages)

Asynchronously processes a list of messages and returns a response message.

Parameter
Type
Description

session

The current smart session.

messages

A list of messages to process.

Returns: Task<Message>. A task that represents the asynchronous operation. The task result contains the response message.

Throws:

  • ArgumentNullException Thrown when session or messages is null.

  • NotSupportedException Thrown when the pipeline is not supported.

Dispose(disposing)

Releases the unmanaged resources used by the component and optionally releases the managed resources.

Parameter
Type
Description

disposing

true to release both managed and unmanaged resources; false to release only unmanaged resources.

GetSimilarityAsync(query, text)

Asynchronously calculates the similarity between a query and an array of text.

Parameter
Type
Description

query

The query string to compare.

text

An array of text strings to compare against the query.

Returns: Task<Single[]>. A task that represents the asynchronous operation. The task result contains an array of similarity scores.

ReadAssistantMessage(response, message)

Reads the assistant message from the response and updates the message.

Parameter
Type
Description

response

The response containing the assistant message.

message

The message to update with the assistant's response.

Throws:

  • ArgumentNullException Thrown when response or message is null.

ReadUsage(message, reply)

Reads the usage information from the reply and updates the message.

Parameter
Type
Description

message

The message to update with usage information.

reply

The reply containing usage information.

SmartEndpoint
HuggingFaceJavaScriptEndpoint
public class HuggingFaceJavaScriptEndpoint : SmartEndpoint
AddOrReplaceService<TService, TImplementation>(services, lifetime)

Adds or replaces a service in the service provider with the specified implementation type.

Parameter
Type
Description

TService

The type of service to add or replace.

TImplementation

The type of the implementation to use.

services

The service provider to modify.

lifetime

The lifetime of the service.

Returns: ServiceProvider. The modified service provider.

AddOrReplaceService<TService>(services, implementation, lifetime)

Adds or replaces a service in the service provider with the specified implementation instance.

Parameter
Type
Description

TService

The type of service to add or replace.

services

The service provider to modify.

implementation

The implementation instance to use.

lifetime

The lifetime of the service.

Returns: ServiceProvider. The modified service provider.

AddOrReplaceService<TService>(services, factory, lifetime)

Adds or replaces a service in the service provider using a factory method.

Parameter
Type
Description

TService

The type of service to add or replace.

services

The service provider to modify.

factory

The factory method to create the service instance.

lifetime

The lifetime of the service.

Returns: ServiceProvider. The modified service provider.

ComputeClusters(embeddings, count, maxDivergence)

Computes clusters from the given embeddings using the K-Means clustering algorithm.

Parameter
Type
Description

embeddings

The embeddings to cluster.

count

The number of clusters to create.

maxDivergence

The maximum divergence allowed for convergence.

Returns: ValueTuple`2[]. An array of tuples containing the centroid and vectors of each cluster.

K-Means clustering is a method of vector quantization, originally from signal processing, that is popular for cluster analysis in data mining. This method partitions the embeddings into count clusters.

CosineSimilarity(vectorA, vectorB)

Calculates the cosine similarity between two vectors.

Parameter
Type
Description

vectorA

The first vector.

vectorB

The second vector.

Returns: Single. The cosine similarity between the two vectors.

Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space. It is defined as the cosine of the angle between the two vectors.

CosineSimilarity(vectorA, vectorB)

Calculates the cosine similarity between a vector and an array of vectors.

Parameter
Type
Description

vectorA

The vector to compare.

vectorB

The array of vectors to compare against.

Returns: Single[]. An array of cosine similarity values for each vector in the array.

This method extends the single vector cosine similarity calculation to handle multiple vectors, returning an array of similarity scores.

ToCamelCase(text)

Converts the first character of the string to lowercase, making it camel case.

Parameter
Type
Description

text

The string to convert.

Returns: String. The camel case version of the string.

This method is useful for converting PascalCase strings to camelCase, which is often used in JSON serialization and other contexts.

Public Class SmartExtensions
public class SmartExtensions
AmazonBedrockEndpoint

Represents an endpoint for connecting to Amazon Bedrock services.

public class AmazonBedrockEndpoint : SmartHttpEndpoint
Public Class AmazonBedrockEndpoint
    Inherits SmartHttpEndpoint

This class is used to configure and manage connections to Amazon Bedrock endpoints, specifically for interacting with the Anthropic API.

Constructors

AmazonBedrockEndpoint()

Initializes a new instance of the AmazonBedrockEndpoint class.

Sets default values for authentication, model, URL, and headers.

Properties

Authentication

String: Gets or sets the authentication method for the endpoint. (Default: "x-api-key")

Model

String: Gets or sets the model used for the endpoint. (Default: "claude-3-opus-20240229")

URL

String: Gets or sets the URL for the endpoint. (Default: "https://api.anthropic.com/v1/messages")

Methods

AddMessages(payload, session, messages)

Adds messages to the payload.

Parameter
Type
Description

payload

The payload to which messages are added.

session

The current session context.

messages

The list of messages to add.

Ensures the system message is complete and prepares the payload for sending.

AddOptions(message, session)

Adds options to the message payload.

Parameter
Type
Description

message

The message payload to modify.

session

The current session context.

Sets default values for temperature and max tokens in the message payload.

BuildMessage(message)

Builds a message object from a Message instance.

Parameter
Type
Description

message

The message to convert.

Returns: Object. A dynamic object representing the message.

Handles different input types, including text and images.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response.

Parameter
Type
Description

response

The response containing the assistant's message.

message

The message object to populate.

Parses the response stream to extract the assistant's message content.

ReadUsage(message, reply)

Reads the usage information from the reply.

Parameter
Type
Description

message

The message object to update with usage data.

reply

The dynamic reply object containing usage information.

SmartEndpoint
SmartHttpEndpoint
public class SmartCopilotAdapter : SmartAdapter
Public Class SmartCopilotAdapter
    Inherits SmartAdapter

Works with:

  • AzureAI/OpenAI gpt-4

  • AzureAI/OpenAI gpt-4o

  • AzureAI/OpenAI gpt-3.5

  • AzureAI/Anthropic Claude

  • Google Gemini

  • Llama3:8b and 70b

When the user instructions contain extra information (i.e. "add Microsoft as a new client"), the additional parameters are extracted, processed and are available in the Parameters property delivered with the ExecuteAction event arguments. You are not limited to the predefined actions in the application. When you add a method decorated with the ToolAttribute the AI can invoke it when necessary. This is a simple example that sends an email when prompted by the user:

Constructors

SmartCopilotAdapter()

Initializes a new instance of the SmartCopilotAdapter class.

Properties

BotAvatar

String: Gets or sets the icon of the AI bot. (Default: "resource.wx/Wisej.AI/Icons/wisej-avatar.svg")

BotName

String: Gets or sets the name of the AI bot. (Default: "Wisej.AI")

ChatBox

ChatBox: Gets the ChatBox control associated with this adapter.

User

User: Gets the User associated with the AI bot.

The User is created using BotName and BotAvatar.

Methods

OnControlCreated(control)

Parameter
Type
Description

control

OnControlDisposed(control)

Parameter
Type
Description

control

OnExecuteAction(e)

Raises the ExecuteAction event.

Parameter
Type
Description

e

The instance containing the event data.

RunAsyncCore(control)

Executes the core logic asynchronously.

Parameter
Type
Description

control

The control associated with the operation.

Returns: Task<Message>. A task representing the asynchronous operation.

Events

ExecuteAction

ExecuteActionEventHandler Occurs when an action is executed.

Implements

Name
Description

Represents a provider that supplies tools.

SmartAdapter
SmartCopilotAdapter
ChatBox
SmartTool

Metrics()

Initializes a new instance of the Metrics class.

Properties

CallCount

Int32: Gets the number of calls.

InputTokens

Int32: Gets the number of input tokens.

OutputTokens

Int32: Gets the number of output tokens.

Methods

Add(inputTokens, outputTokens, callCount)

Adds the specified number of input tokens, output tokens, and call count to the current metrics.

Parameter
Type
Description

inputTokens

The number of input tokens to add.

outputTokens

The number of output tokens to add.

callCount

The number of calls to add. Default is 1.

Returns: Metrics. The updated Metrics instance.

Add(usage)

Adds the metrics from another Metrics instance to the current metrics.

Parameter
Type
Description

usage

The instance whose values are to be added.

Returns: Metrics. The updated Metrics instance.

This method updates the current metrics by adding the values from another Metrics instance.

Reset()

Resets the input tokens, output tokens, and call count to 0.

Returns: Metrics. The updated Metrics instance.

Subtract(usage)

Subtracts the metrics from another Metrics instance from the current metrics.

Parameter
Type
Description

usage

The instance whose values are to be subtracted.

Returns: Metrics. The updated Metrics instance.

This method updates the current metrics by subtracting the values from another Metrics instance.

Public Class Metrics
public class Metrics

SmartReportAdapter

Wisej.AI.Adapters.SmartReportAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartReportAdapter

Enhances the ChatBox control to allow seamless PDF report queries using an AI provider.

public class SmartReportAdapter : SmartAdapter

Utilizes these services: . The class extends the functionality of a to provide capabilities for reading and interpreting reports. It utilizes prompts and sessions to interact with the user and process report data.

Constructors

SmartReportAdapter()

Initializes a new instance of the class.

Properties

AutoReset

: Gets or sets a value indicating whether the history of the conversation is cleared after each response. (Default: False)

BotAvatar

: Gets or sets the avatar image source for the bot. (Default: "resource.wx/Wisej.AI/Icons/wisej-avatar.svg")

BotName

: Gets or sets the name of the bot. (Default: "Wisej.AI")

ChatBox

: Gets the control associated with this adapter.

ConversionService

: Gets or sets the document conversion service used for converting documents to text.

Prompt

: Gets or sets the prompt to execute. Used only when the adapter is not connected to a . (Default: null)

ReportPdfSource

: Gets or sets the PDF source stream for the report.

User

: Gets the user associated with the bot.

Methods

AskAsync(question)

Parameter
Type
Description

Returns: .

Throws:

  • When question is null.

evaluate_expression(expression)

Evaluates a mathematical expression asynchronously.

Parameter
Type
Description

Returns: . A task that represents the asynchronous operation. The task result contains the evaluated result of the expression.

This method uses the browser's evaluation engine to compute the result of the given expression.

OnAnswerReceived(e)

Raises the event.

Parameter
Type
Description

OnControlCreated(control)

Parameter
Type
Description

OnControlDisposed(control)

Parameter
Type
Description

OnReadingReport(e)

Raises the event.

Parameter
Type
Description

ResetSession(removeMessages)

Resets the conversation history.

Parameter
Type
Description

RunAsyncCore(control)

Executes the core logic asynchronously for running the session.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation.

Events

AnswerReceived

Occurs when an answer is received from the session.

ReadingReport

Occurs when a report is being read.

Implements

Name
Description

SmartChatBoxAdapter

Wisej.AI.Adapters.SmartChatBoxAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

  • SmartAdapter

    • SmartChatBoxAdapter

Turns the ChatBox control into a AI-powered bot. It can answer any question (depending on the AI model being used) and can invoke methods in your applications as needed (see SmartTool).

public class SmartChatBoxAdapter : SmartAdapter

Works with:

  • AzureAI/OpenAI gpt-4

  • AzureAI/OpenAI gpt-4o

  • AzureAI/OpenAI gpt-3.5

  • AzureAI/Anthropic Claude

You are not limited to what the model can answer. When you add a method decorated with the the AI can invoke it when necessary in order to retrieve any information or take any action. This is a simple example that provides current date/time knowledge to the AI bot, including the name of the day:

When the AI needs to know the current date/time it will invoke this method. For example: "When is the next national holiday in {country}?". In this example you can see how to allow the AI to take an action.

When the AI wants to change the header color it will invoke this method with the correct parameter. Use this feature with a lot of caution! A method like "LaunchThermonuclearStrike()" is not allowed.

Constructors

SmartChatBoxAdapter()

Initializes a new instance of .

Properties

AutoReset

: Gets or sets a value indicating whether the history of the conversation is cleared after each response. (Default: False)

BotAvatar

: Icon of the AI bot. (Default: "resource.wx/Wisej.AI/Icons/wisej-avatar.svg")

BotName

: Name of the AI bot. (Default: "Wisej.AI")

ChatBox

:

User

: The User associated to the AI bot. It's created using and .

Methods

FormatAnswer(answer, sources)

Parameter
Type
Description

Returns: .

OnAnswerReceived(args)

Parameter
Type
Description

OnControlCreated(control)

Parameter
Type
Description

OnControlDisposed(control)

Parameter
Type
Description

OnSourceClicked(args)

Parameter
Type
Description

ParseAnswer(text)

Parameter
Type
Description

Returns: .

ParseSources(text)

Parameter
Type
Description

Returns: .

ResetSession(removeMessages)

Resets the conversation history.

Parameter
Type
Description

RunAsyncCore(control)

Parameter
Type
Description

Returns: .

Events

AnswerReceived

SourceClicked

Implements

Name
Description

OllamaEndpoint

Wisej.AI.Endpoints.OllamaEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents an endpoint that connects to Ollama services, providing functionalities for chat and embeddings.

This class extends the to interact with Ollama endpoints. It provides methods to construct API URLs, add options to messages, and handle responses.

Constructors

OllamaEndpoint()

Initializes a new instance of the class with default settings.

Properties

EmbeddingModel

: Gets or sets the embedding model used by the endpoint. (Default: "all-minilm")

MaxContextTokens

: Gets or sets the maximum number of tokens the context window for the specified can hold. (Default: 8192)

Methods

AddOptions(message, session)

Adds options to the message for the current session.

Parameter
Type
Description

Throws:

  • Thrown when the message is null.

AskEmbeddingsAsync(inputs)

Asynchronously requests embeddings for the specified inputs.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation, with a result of type .

Throws:

  • Thrown when the inputs are null.

BuildEmbeddingsPayload(inputs)

Builds the payload for the embeddings request.

Parameter
Type
Description

Returns: . An object representing the payload for the embeddings request.

Throws:

  • Thrown when the inputs are null.

GetApiURL()

Constructs the API URL for chat interactions.

Returns: . A string representing the chat API URL.

GetEmbeddingsURL()

Constructs the API URL for embeddings interactions.

Returns: . A string representing the embeddings API URL.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response and updates the message object.

Parameter
Type
Description

Throws:

  • Thrown when the response or message is null.

ReadEmbeddingsResponse(response)

Reads the embeddings response and extracts the embeddings data.

Parameter
Type
Description

Returns: . A jagged array of floats representing the embeddings.

Throws:

  • Thrown when the response is null.

ReadUsage(message, reply)

Reads the usage statistics from the reply and updates the message usage.

Parameter
Type
Description

AnthropicEndpoint

Wisej.AI.Endpoints.AnthropicEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

  • SmartEndpoint

    • SmartHttpEndpoint

Represents an endpoint for connecting to Anthropic services.

This class is used to configure and manage connections to Anthropic endpoints, providing methods to send messages and handle responses. It inherits from .

Constructors

AnthropicEndpoint()

Initializes a new instance of the class.

Sets default values for authentication, model, URL, and headers.

Properties

Authentication

: Gets or sets the authentication method for the endpoint. (Default: "x-api-key")

Model

: Gets or sets the model used by the Anthropic endpoint. (Default: "claude-3-5-sonnet-20241022")

URL

: Gets or sets the URL for the Anthropic API endpoint. (Default: "https://api.anthropic.com/v1/messages")

Methods

AddMessages(payload, session, messages)

Adds messages to the payload for the Anthropic API request.

Parameter
Type
Description

Prepares the system message and other messages for the API request.Throws:

  • Thrown if session , payload , or messages is null.

AddOptions(message, session)

Adds options to the message before sending it to the Anthropic endpoint.

Parameter
Type
Description

Sets default values for temperature and max tokens in the message.

BuildMessage(message)

Builds a message object for the Anthropic API.

Parameter
Type
Description

Returns: . An object representing the message for the API.

Handles different input types, including text and images.Throws:

  • Thrown if message is null.

ReadAssistantMessage(response, message)

Reads the assistant's message from the response.

Parameter
Type
Description

Parses the response content and updates the message text.Throws:

  • Thrown if response or message is null.

ReadUsage(message, reply)

Reads the usage information from the API reply.

Parameter
Type
Description

SmartTool.ToolContext

Wisej.AI.SmartTool ToolContext

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Represents the context in which a smart tool operates, providing properties and methods to manage tool execution.

public class ToolContext
Public Class ToolContext

The ToolContext class encapsulates the state and behavior required to execute a smart tool, including its arguments, session, and endpoint.

Constructors

ToolContext()

Initializes a new instance of .

Properties

Abort

: Gets a value indicating whether the tool execution should be aborted.

Arguments

: Gets the arguments for the tool execution.

Endpoint

: Gets the endpoint associated with the tool context.

Id

: Gets the unique identifier for the tool context.

Iteration

: Gets the current iteration count for the tool execution.

ReturnValue

: Gets or sets the return value of the tool execution.

Session

: Gets the session associated with the tool context.

Tool

: Gets the tool associated with the context.

Methods

Invoke()

Invokes the tool synchronously.

Returns: . The result of the tool invocation.

InvokeAsync(session)

Invokes the tool asynchronously.

Parameter
Type
Description

Returns: . A task representing the asynchronous operation.

This method handles exceptions and manages the tool invocation lifecycle, including raising events before and after invocation.

SmartRealtimeAdapter

Wisej.AI.Adapters.SmartRealtimeAdapter

Namespace: Wisej.AI.Adapters

Assembly: Wisej.AI (3.5.0.0)

Represents a smart adapter that provides real-time data processing capabilities for use with the endpoint.

SmartObject

Wisej.AI.SmartObject

Namespace: Wisej.AI

Assembly: Wisej.AI (3.5.0.0)

Provides common events and properties to , , and objects.

Properties

OpenAIEndpoint

Wisej.AI.Endpoints.OpenAIEndpoint

Namespace: Wisej.AI.Endpoints

Assembly: Wisej.AI (3.5.0.0)

var ollama = new OllamaEndpoint { URL = "http:\\localhost:8080" };

      [SmartTool.Tool]
      [Description("Sends an email message.")]
      public void SendEmailMessage(
        [Description("Email address of the recipient.")]
        string destinationEmail,
        
        [Description("Subject line.")]
        string subject,

        [Description("Message text.")]
        string message) {
        
        // code to send an email, or open a dialog box.
      }

question

String

expression

String

The mathematical expression to evaluate.

e

AnswerReceivedArgs

The AnswerReceivedArgs instance containing the event data.

control

Control

control

Control

e

ReadingReportEventArgs

The ReadingReportEventArgs instance containing the event data.

removeMessages

Boolean

Indicates whether all messages from the ChatBox control should also be removed.

control

Control

The control associated with the session.

IToolProvider

Represents a provider that supplies tools.

Public Class SmartReportAdapter
    Inherits SmartAdapter
IDocumentConversionService
SmartReportAdapter
ChatBox
SmartReportAdapter
Boolean
String
String
ChatBox
ChatBox
IDocumentConversionService
String
ChatBox
Stream
User
Task<String>
ArgumentNullException
Task<Object>
AnswerReceived
ReadingReport
Task<Message>
AnswerReceivedHandler
ReadingReportEventHandler

session

SmartSession

The session invoking the tool.

ToolContext
Boolean
Dictionary<String, Object>
SmartEndpoint
String
Int32
Object
SmartSession
SmartTool
Object
Task
SmartSession
IList<Message>
Boolean
String
String[]
Response
Message
Message
Object
ServiceProvider
ServiceLifetime
ServiceProvider
TService
ServiceLifetime
ServiceProvider
Func<Type, Object>
ServiceLifetime
Single[][]
Int32
Double
Single[]
Single[]
Single[]
Single[][]
String
Object
SmartSession
IList<Message>
Object
SmartSession
Message
Response
Message
Message
Object
Control
Control
ExecuteActionEventArgs
ExecuteActionEventArgs
Control
IToolProvider
Int32
Int32
Int32
Metrics
Metrics
Metrics
Metrics

message

Object

The dynamic message object to which options are added.

session

SmartSession

The current session containing model options.

inputs

String[]

An array of input strings for which embeddings are requested.

inputs

String[]

An array of input strings for which the payload is built.

response

Response

The response received from the API.

message

Message

The message object to be updated with the assistant's response.

response

Response

The response received from the API.

message

Message

The message object to be updated with usage statistics.

reply

Object

The dynamic reply object containing usage information.

OllamaEndpoint
Public Class OllamaEndpoint
    Inherits SmartHttpEndpoint
SmartHttpEndpoint
OllamaEndpoint
String
Int32
Model
ArgumentNullException
Task<Embedding>
Embedding
ArgumentNullException
Object
ArgumentNullException
String
String
ArgumentNullException
Single[][]
ArgumentNullException
public class OllamaEndpoint : SmartHttpEndpoint

payload

Object

The payload to be sent.

session

SmartSession

The current session.

messages

IList<Message>

The list of messages to include.

message

Object

The message to be sent.

session

SmartSession

The current session.

message

Message

The message to be converted.

response

Response

The response from the API.

message

Message

The message object to populate.

message

Message

The message object to update.

reply

Object

The dynamic reply object from the API.

AnthropicEndpoint
Public Class AnthropicEndpoint
    Inherits SmartHttpEndpoint
SmartHttpEndpoint
AnthropicEndpoint
String
String
String
ArgumentNullException
Object
ArgumentNullException
ArgumentNullException
public class AnthropicEndpoint : SmartHttpEndpoint
Google Gemini
  • Llama3:8b and 70b

  • answer

    String

    sources

    String[]

    args

    AnswerReceivedEventArgs

    control

    Control

    control

    Control

    args

    SourceClickedEventArgs

    text

    String

    text

    String

    removeMessages

    Boolean

    Indicates whether all messages from the ChatBox control should also be removed.

    control

    Control

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartChatBoxAdapter
        Inherits SmartAdapter
    ToolAttribute
    SmartChatBoxAdapter
    Boolean
    String
    String
    ChatBox
    User
    BotName
    BotAvatar
    String
    String
    String[]
    Task<Message>
    AnswerReceivedEventHandler
    SourceClickedEventHandler
    
        [SmartTool.Tool]
        [Description("Returns the current date and time.")]
        public DateTime GetCurrentDateTime() {
          return DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
        }
      
    
      [SmartTool.Tool]
      [Description("Changes the background color of the application header.")]
      public void SetHeaderColor(
          [Description("Name of the new color. Use @toolbar to reset to the original color.")]
          string color)
      {
        ((MainPage)Application.MainPage).panelHeader.BackColor = Color.FromName(color);
      }
    
    Public Class SmartRealtimeAdapter
        Inherits SmartAdapter

    The SmartRealtimeAdapter class extends the SmartAdapter base class to enable real-time data handling and integration with OpenAI's real-time endpoint. This adapter is designed to facilitate seamless communication and data exchange in scenarios where immediate processing and response are required.

    Constructors

    SmartRealtimeAdapter()

    Initializes a new instance of the SmartRealtimeAdapter class.

    This constructor sets up the SmartRealtimeAdapter by initializing the internal prompt and subscribing to the application's refresh event. The prompt is initialized with a default label, and the adapter will respond to application-wide refresh events for real-time updates.

    Properties

    Enabled

    Boolean: Gets or sets a value indicating whether the component accepts voice input from the user. (Default: True)

    When set to true (the default value), the component is enabled to receive and process voice input from the user. Setting this property to false disables voice input functionality for the component.

    Listening

    Boolean: Gets a value indicating whether the component is currently listening for the user's voice.

    The Listening property reflects the current listening state of the component.

    Muted

    Boolean: Gets or sets a value indicating whether the component is muted. (Default: False)

    When set to true, the component is muted and may not produce sound or notifications. The default value is false.

    TranscriptionEnabled

    Boolean: Gets or sets a value indicating whether transcription functionality is enabled. (Default: False)

    When set to true, transcription features are activated. The default value is false.

    Voice

    String: Gets or sets the voice of the model. (Default: "Alloy")

    Supported voices include: Alloy (default), Ash, Ballad, Coral, Echo, Sage, Shimmer, Verse. New voices can be used as they become available.

    Methods

    CreateSession<T>(systemPrompt)

    Parameter
    Type
    Description

    T

    systemPrompt

    Returns: T.

    OnAnswerReceived(e)

    Raises the AnswerReceived event.

    Parameter
    Type
    Description

    e

    The instance containing the event data.

    This method invokes the AnswerReceived event, passing the specified event arguments to all registered event handlers.

    OnEnabledChanged(e)

    Raises the EnabledChanged event.

    Parameter
    Type
    Description

    e

    An instance that contains the event data.

    This method is called to trigger the EnabledChanged event. Derived classes can override this method to provide additional logic when the event is raised.

    OnListeningChanged(e)

    Raises the ListeningChanged event.

    Parameter
    Type
    Description

    e

    An instance containing the event data.

    This method is called to notify subscribers that the listening state has changed. Derived classes can override this method to provide custom event data or additional logic.

    OnMutedChanged(e)

    Raises the MutedChanged event.

    Parameter
    Type
    Description

    e

    An instance containing the event data.

    This method is called to notify subscribers that the muted state has changed. Derived classes can override this method to provide custom event data or additional logic.

    OnTranscriptionReceived(e)

    Raises the TranscriptionReceived event.

    Parameter
    Type
    Description

    e

    The instance containing the event data.

    This protected virtual method allows derived classes to trigger the TranscriptionReceived event. Override this method to provide custom event invocation logic.

    Reset()

    Resets the current conversation with the OpenAI Realtime API endpoint.

    This method clears the ongoing conversation state, allowing a new conversation to begin with the OpenAI endpoint. It is useful when you want to discard the current context and start fresh.

    StartListening()

    Starts capturing and processing user voice input through the OpenAI Realtime API.

    Call this method to begin listening for user voice input. The component will capture audio from the input device, transmit it to the OpenAI Realtime API, and process the response in real time. This enables interactive voice-driven features within your application.

    StopListening()

    Stops capturing and processing user voice input.

    Call this method to stop listening for user voice input. The component will cease capturing audio from the input device and terminate any ongoing communication with the OpenAI Realtime API. This is useful for conserving resources or when voice input is no longer required.

    Events

    AnswerReceived

    AnswerReceivedEventHandler Occurs when an answer is received.

    Subscribe to this event to handle actions when an answer is received. The event provides AnswerReceivedEventArgs containing details about the received answer.

    EnabledChanged

    EventHandler Occurs when the enabled state of the object changes.

    Subscribe to this event to be notified whenever the enabled state of the object is modified. The event provides standard EventArgs data.

    ListeningChanged

    EventHandler Occurs when the listening state of the component changes.

    Subscribe to this event to be notified when the listening state is updated, such as when the component starts or stops listening for input.

    MutedChanged

    EventHandler Occurs when the muted state of the component changes.

    Subscribe to this event to be notified when the muted state is updated, such as when the component is muted or unmuted.

    TranscriptionReceived

    TranscriptionReceivedEventHandler Occurs when a transcription is received.

    Subscribe to this event to handle actions when a new transcription is received. The event provides TranscriptionReceivedEventArgs containing details about the transcription.

    Implements

    Name
    Description

    Represents a provider that supplies tools.

    SmartAdapter
    SmartRealtimeAdapter
    OpenAIEndpointRealtime
    public class SmartRealtimeAdapter : SmartAdapter
    HasTools

    Boolean: Gets a value indicating whether the session has tools.

    Parameters

    ParameterCollection: Gets the collection of parameters for the session.

    Tools

    ToolCollection: Gets the collection of tools available in the session.

    Usage

    Metrics: Gets the usage metrics for the session.

    Methods

    ClearTools()

    Clears all tools from the smart prompt.

    OnAfterInvokeTool(args)

    Raises the AfterInvokeTool event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnAfterResponseReceived(args)

    Raises the AfterResponseReceived event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnBeforeInvokeTool(args)

    Raises the BeforeInvokeTool event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnBeforeSendRequest(args)

    Raises the BeforeSendRequest event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnConvertParameter(args)

    Raises the ConvertParameter event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnDone(e)

    Raises the Done event.

    Parameter
    Type
    Description

    e

    An that contains the event data.

    OnError(args)

    Raises the Error event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    OnPrepareMessages(e)

    Raises the PrepareMessages event.

    Parameter
    Type
    Description

    e

    An that contains the event data.

    OnStart(e)

    Raises the Start event.

    Parameter
    Type
    Description

    e

    An that contains the event data.

    Events

    AfterInvokeTool

    InvokeToolEventHandler Occurs after a tool is invoked.

    AfterResponseReceived

    MessagesEventHandler Occurs after a response is received.

    BeforeInvokeTool

    InvokeToolEventHandler Occurs before a tool is invoked.

    BeforeSendRequest

    MessagesEventHandler Occurs before a request is sent.

    ConvertParameter

    ConvertParameterEventHandler Occurs when a parameter needs to be converted.

    Done

    EventHandler Occurs when the session is done processing a question.

    Error

    ErrorEventHandler Occurs when an error is encountered.

    PrepareMessages

    MessagesEventHandler Occurs after the messages have been prepared and before they are send to the AI.

    Start

    EventHandler Occurs when the session starts processing a question.

    Inherited By

    Name
    Description

    TODO:

    Represents a smart parallel prompt that can execute multiple tasks concurrently.

    Represents a SmartHub component that provides AI capabilities to controls within a container.

    Represents a smart prompt component that can process and manage prompts with tools and parameters.

    Represents a session that manages interactions with a smart hub and endpoint, handling prompts, messages, and tools within the session context.

    SmartPrompt
    SmartSession
    SmartHub
    Public Class SmartObject
        Inherits Component
    public class SmartObject : Component
    OpenAIEndpoint

    Represents an endpoint for connecting to OpenAI services.

    public class OpenAIEndpoint : SmartHttpEndpoint
    Public Class OpenAIEndpoint
        Inherits SmartHttpEndpoint

    This class is used to interact with OpenAI's API, providing methods to send requests and process responses for both chat completions and embeddings.

    Constructors

    OpenAIEndpoint()

    Initializes a new instance of the OpenAIEndpoint class with default settings.

    The default authentication is set to "Bearer".

    Properties

    EmbeddingModel

    String: Gets or sets the model used for embeddings. (Default: "text-embedding-3-small")

    Model

    String: Gets or sets the model used for chat completions. (Default: "gpt-4o")

    URL

    String: Gets or sets the base URL for the OpenAI API. (Default: "https://api.openai.com/v1")

    UseNativeTools

    Boolean: (Default: True)

    Methods

    AddOptions(message, session)

    Adds options to the message for the API request.

    Parameter
    Type
    Description

    message

    The message to be sent to the API.

    session

    The current session context.

    Sets the temperature to 0.0 and max tokens to the value of MaxOutputTokens.

    BuildEmbeddingsPayload(inputs)

    Builds the payload for an embeddings request.

    Parameter
    Type
    Description

    inputs

    The input strings to be embedded.

    Returns: Object. The constructed payload for the embeddings request.

    Throws:

    • ArgumentNullException Thrown when the inputs are null.

    BuildMessage(message)

    Builds the message payload for the API request.

    Parameter
    Type
    Description

    message

    The message object containing the content to be sent.

    Returns: Object. The constructed message payload.

    Throws:

    • ArgumentNullException Thrown when the message is null.

    GetApiURL()

    Constructs the API URL for chat completions.

    Returns: String. The full API URL for chat completions.

    GetEmbeddingsURL()

    Constructs the API URL for embeddings.

    Returns: String. The full API URL for embeddings.

    ReadEmbeddingsResponse(response)

    Reads the embeddings from the API response.

    Parameter
    Type
    Description

    response

    The response received from the API.

    Returns: Single[][]. An array of float arrays representing the embeddings.

    Throws:

    • ArgumentNullException Thrown when the response is null.

    Inherited By

    Name
    Description

    Represents a connection to Cerebras endpoints, inheriting from OpenAIEndpoint.

    Represents a connection to DeepSeek endpoints, inheriting from OpenAIEndpoint.

    https://console.groq.com/docs/openai

    Represents a connection to HuggingFace serverless endpoints for model inference and embeddings.

    Represents a connection to LocalAI endpoints, providing access to various AI models and services.

    Represents a connection to NVIDIA AI endpoints, providing access to various AI models and services.

    SmartEndpoint
    SmartHttpEndpoint

    OpenAIRealtime

    https://openai.com/

    1, 5, 6

    NVIDIA

    https://www.nvidia.com/en-us/ai/

    2, 3, 4

    Azure AI

    https://portal.azure.com/#home

    1, 2, 3, 4, 5, 6, 7

    Ollama

    https://ollama.com/

    2, 3, 4

    Anthropic

    https://www.anthropic.com/

    1, 3, 4

    GoogleAi

    https://aistudio.google.com/

    1, 2, 3, 4

    HuggingFace

    https://huggingface.co/

    2, 3, 4

    SambaNova

    https://sambanova.ai/

    2, 4

    Together.AI

    https://www.together.ai/

    2, 3, 4

    X.AI

    https://x.ai/

    1, 4

    Cerebras

    https://cerebras.ai/

    2, 4

    GroqCloud

    https://groq.com/groqcloud/

    2

    GroqCloudWhisper

    https://groq.com/groqcloud/

    1, 6

    Amazon Bedrock

    https://aws.amazon.com/bedrock

    2, 3, 4

    LocalAI

    https://localai.io/

    2, 3, 4, 7

    LocalAITTS

    https://localai.io/

    2, 5

    LocalAIWhisper

    https://localai.io/

    2, 6

    LocalAIImageGen

    https://localai.io/

    2, 7

    https://openai.com/
    https://openai.com/
    https://openai.com/
    https://openai.com/

    SmartDocumentAdapter

    Wisej.AI.Adapters.SmartDocumentAdapter

    Namespace: Wisej.AI.Adapters

    Assembly: Wisej.AI (3.5.0.0)

    • SmartAdapter

      • SmartDocumentAdapter

    Represents a document adapter that can perform AI tasks using a document as a data source and interact with the user through a ChatBox control.

    public class SmartDocumentAdapter : SmartAdapter

    This class integrates with the to search within the document being managed. It provides properties to configure the bot's appearance and document handling, and events to manage responses.

    Constructors

    SmartDocumentAdapter()

    Initializes a new instance of the class.

    Properties

    AutoReset

    : Gets or sets a value indicating whether the history of the conversation is cleared after each response. (Default: False)

    BotAvatar

    : Gets or sets the avatar image source of the bot. (Default: "resource.wx/Wisej.AI/Icons/wisej-avatar.svg")

    BotName

    : Gets or sets the name of the bot. (Default: "Wisej.AI")

    ChatBox

    : Gets the associated ChatBox control.

    ConversionService

    : Gets or sets the document conversion service used for converting documents to text.

    FilePath

    : Gets or sets the file path of the document. (Default: null)

    FileType

    : Gets or sets the file type. i.e. .docx, .pdf, .txt. If null it will be detected automatically. (Default: null)

    MaxClusters

    : Get or sets the maximum number of vector clusters to generate when performing summarization tasks. (Default: 5)

    MinSimilarity

    : Gets or sets the minimum similarity threshold. (Default: 0.25)

    Stream

    : Gets or sets the file path of the document. (Default: null)

    TextSplitterService

    : Gets or sets the text splitter service used for splitting text into smaller chunks.

    TopN

    : Gets or sets the number of top results to retrieve. (Default: 10)

    User

    : Gets the user representing the bot.

    Methods

    AskAsync(question)

    Parameter
    Type
    Description

    Returns: .

    Throws:

    • When question is null.

    OnAnswerReceived(e)

    Raises the event.

    Parameter
    Type
    Description

    OnControlCreated(control)

    Parameter
    Type
    Description

    OnControlDisposed(control)

    Parameter
    Type
    Description

    ParseAnswer(text)

    Parameter
    Type
    Description

    Returns: .

    ParseSourceText(text)

    Parameter
    Type
    Description

    Returns: .

    ResetSession(removeMessages)

    Resets the conversation history.

    Parameter
    Type
    Description

    RunAsyncCore(control)

    Executes the core logic asynchronously.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    Events

    AnswerReceived

    Occurs when an answer is received.

    Implements

    Name
    Description

    SmartPrompt

    Wisej.AI.SmartPrompt

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    • SmartObject

      • SmartPrompt

    Represents a smart prompt component that can process and manage prompts with tools and parameters.

    public class SmartPrompt : SmartObject, IToolProvider, ICloneable

    The class provides functionality to manage prompts, tools, and parameters. It supports cloning and asynchronous operations to ask questions using a smart hub or endpoint.

    Constructors

    SmartPrompt(text)

    Initializes a new instance of the class with the specified text.

    Name
    Type
    Description

    Properties

    PromptDictionaries

    : Gets the collection of prompt dictionaries.

    The prompt dictionaries are loaded from the AI directory and embedded resources.

    Text

    : Gets or sets the text of the smart prompt. (Default: null)

    The text is resolved using the method.

    Methods

    AskAsync(hub, question, image)

    Asynchronously asks a question using the specified smart hub.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with a result.

    Throws:

    • Thrown when the hub or question is null.

    AskAsync(endpoint, question, image)

    Asynchronously asks a question using the specified smart endpoint.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with a result.

    Throws:

    • Thrown when the endpoint or question is null.

    Clone()

    Creates a new instance of the class that is a copy of the current instance.

    Returns: . A new object that is a copy of this instance.

    RemoveTool(tool)

    Removes a tool from the smart prompt.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Throws:

    • Thrown when the tool is null.

    RemoveTools(target)

    Removes the tools from the specified object.

    Parameter
    Type
    Description

    Returns: . The current instance.

    ResolvePrompt(key)

    Resolves the prompt text for the specified key.

    Parameter
    Type
    Description

    Returns: . The resolved prompt text, or the key if not found.

    SavePrompts(filePath)

    Saves the prompts to the specified file path.

    Parameter
    Type
    Description

    UseTool(tool)

    Adds a tool to the smart prompt.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Throws:

    • Thrown when the tool is null.

    UseTools(target)

    Uses the tools from the specified target object.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Inherited By

    Name
    Description

    Implements

    Name
    Description

    GoogleAIEndpoint

    Wisej.AI.Endpoints.GoogleAIEndpoint

    Namespace: Wisej.AI.Endpoints

    Assembly: Wisej.AI (3.5.0.0)

    • SmartEndpoint

      • SmartHttpEndpoint

    Represents a connection to Google AI endpoints for generating content and embeddings.

    This class is used to interact with Google AI services, allowing for content generation and text embeddings. It extends the to provide specific functionality for Google AI.

    Constructors

    GoogleAIEndpoint()

    Initializes a new instance of the class with default settings.

    Properties

    Authentication

    : Gets or sets the authentication token for accessing the Google AI endpoint. (Default: null)

    EmbeddingModel

    : Gets or sets the model used for text embeddings. (Default: "text-embedding-004")

    Model

    : Gets or sets the model used for content generation. (Default: "gemini-1.5-pro-latest")

    URL

    : Gets or sets the base URL for the Google AI endpoint. (Default: "https://generativelanguage.googleapis.com/v1beta/models")

    Methods

    AddMessages(payload, session, messages)

    Adds messages to the payload for processing.

    Parameter
    Type
    Description

    Throws:

    • Thrown when session , payload , or messages is null.

    AddOptions(message, session)

    Adds options to the message for content generation.

    Parameter
    Type
    Description

    This method configures the generation parameters such as temperature and max output tokens. It also incorporates any additional model options from the session.

    BuildEmbeddingsPayload(inputs)

    Builds the payload for embedding requests.

    Parameter
    Type
    Description

    Returns: . The constructed payload object for embedding requests.

    Throws:

    • Thrown when inputs is null.

    GetApiURL()

    Constructs the API URL for content generation requests.

    Returns: . The constructed API URL as a string.

    GetEmbeddingsURL()

    Constructs the API URL for embedding requests.

    Returns: . The constructed embeddings URL as a string.

    ReadAssistantMessage(response, message)

    Reads the assistant's message from the response.

    Parameter
    Type
    Description

    Throws:

    • Thrown when response or message is null.

    ReadEmbeddingsResponse(response)

    Reads the embeddings response and extracts the embedding vectors.

    Parameter
    Type
    Description

    Returns: . An array of float arrays representing the embedding vectors.

    Throws:

    • Thrown when response is null.

    ReadUsage(message, reply)

    Reads the usage data from the reply and updates the message usage.

    Parameter
    Type
    Description

    Vector Databases

    How to use vector storage and queries

    Overview

    Wisej.AI can seamlessly integrate with any vector database through the service implementation of the IEmbeddingStorageService interface. While you don't need to interact with this interface directly in your code, any Wisej.AI tools or methods that require a vector database will automatically retrieve the current implementation of IEmbeddingStorageService.

    Specifically, both the DocumentSearchTool and the SmartyHub.IngestDocumentAsync()

    SmartObjectAdapter

    Wisej.AI.Adapters.SmartObjectAdapter

    Namespace: Wisej.AI.Adapters

    Assembly: Wisej.AI (3.5.0.0)

    Converts unstructured text into a structured .NET object.

    SmartParallelPrompt

    Wisej.AI.SmartParallelPrompt

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    question

    String

    e

    AnswerReceivedArgs

    The AnswerReceivedArgs instance containing the event data.

    control

    Control

    control

    Control

    text

    String

    text

    String

    removeMessages

    Boolean

    Indicates whether all messages from the ChatBox control should also be removed.

    control

    Control

    The control associated with the operation.

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartDocumentAdapter
        Inherits SmartAdapter
    IEmbeddingStorageService
    SmartDocumentAdapter
    Boolean
    String
    String
    ChatBox
    IDocumentConversionService
    String
    String
    Int32
    Single
    Stream
    ITextSplitterService
    Int32
    User
    Task<String>
    ArgumentNullException
    AnswerReceived
    String
    String
    Task<Message>
    AnswerReceivedHandler
    SmartPrompt
    AnswerReceivedEventArgs
    AnswerReceivedEventArgs
    EventArgs
    EventArgs
    EventArgs
    EventArgs
    EventArgs
    EventArgs
    TranscriptionReceivedEventArgs
    TranscriptionReceivedEventArgs
    IToolProvider
    InvokeToolEventArgs
    InvokeToolEventArgs
    MessagesEventArgs
    MessagesEventArgs
    InvokeToolEventArgs
    InvokeToolEventArgs
    MessagesEventArgs
    MessagesEventArgs
    ConvertParameterEventArgs
    ConvertParameterEventArgs
    EventArgs
    EventArgs
    ErrorEventArgs
    ErrorEventArgs
    MessagesEventArgs
    MessagesEventArgs
    EventArgs
    EventArgs
    SmartAgentPrompt
    SmartParallelPrompt
    SmartHub
    SmartPrompt
    SmartRealtimeSession
    SmartSession

    SambaNovaEndpoint

    Represents a connection to SambaNova endpoints, inheriting from OpenAIEndpoint.

    TogetherAIEndpoint

    Represents a connection to TogetherAI endpoints, providing access to various AI models and services.

    XAIEndpoint

    Represents a connection to X.AI endpoints, extending the functionality of OpenAIEndpoint.

    Object
    SmartSession
    String[]
    Message
    Response
    CerebrasEndpoint
    DeepSeekEndpoint
    GroqCloudEndpoint
    HuggingFaceEndpoint
    LocalAIEndpoint
    NvidiaAIEndpoint

    payload

    Object

    The payload to which messages are added.

    session

    SmartSession

    The current session.

    messages

    IList<Message>

    The list of messages to be processed.

    message

    Object

    The message to which options are added.

    session

    SmartSession

    The current session containing model options.

    inputs

    String[]

    The array of input strings to be embedded.

    response

    Response

    The response containing the assistant's message.

    message

    Message

    The message object to populate with the assistant's response.

    response

    Response

    The response containing the embeddings data.

    message

    Message

    The message to update with usage data.

    reply

    Object

    The reply containing usage metadata.

    GoogleAIEndpoint
    Public Class GoogleAIEndpoint
        Inherits SmartHttpEndpoint
    SmartHttpEndpoint
    GoogleAIEndpoint
    String
    String
    String
    String
    ArgumentNullException
    Object
    ArgumentNullException
    String
    String
    ArgumentNullException
    Single[][]
    ArgumentNullException
    public class GoogleAIEndpoint : SmartHttpEndpoint
    method utilize this service.

    Collections

    An important concept in vector databases is "collections." Wisej.AI utilizes collections to organize embedded documents into logical groups, akin to how tables are used in databases. Additionally, the name of a document may include a virtual path, similar to a namespace, preceding the document's name.

    For instance, to store two documents with the same name but in different "folders," you can use a naming convention like this:

    If the code does not specify a collection name, Wisej.AI defaults to using the name "default" (in lowercase). The example below illustrates how to store documents in different collections.

    Metadata

    Vector databases typically manage text chunks along with their corresponding vectors, while any additional information is stored in a general metadata field. Wisej.AI automatically extracts specific values when converting documents using the IDocumentConversionService. However, you can add additional custom fields by passing a Metadata object to the IngestDocument method.

    The conversion service automatically adds several fields, depending on the document type: "Title," "Author," "Subject," "Pages," and "Description." For more details, refer to the IDocumentConversionService page. In addition to these fields, the IngestDocument method adds: "FilePath", "CreationDate", "ModifiedDate", "FileSize".

    The following code demonstrates how to add custom metadata to an ingested document:

    All metadata fields are made available to the AI as part of the RAG retrieval process when using DocumentSearchTools. If you use the IEmbeddingStorageService directly, you will find the metadata object as a property of the EmbeddedDocument instance.

    Built-In

    Unless you register a specific provider, Wisej.AI defaults to using the built-in FileSystemEmbeddingStorageService. This implementation saves vectors in the file system at the location specified by FileSystemEmbeddingStorageService.StoragePath. The default path is set to "~\AI\Embeddings".

    An easy alternative is the MemoryEmbeddingStorageService, which stores vectors in memory.

    However, both implementations are intended for development purposes only and should not be used in production environments.

    Chroma DB

    You can run Chroma either locally or on a virtual machine (VM) in a data center. The simplest way to run it is by using the Docker image. For installation instructions, please refer to this link.

    With Chroma, you don't need to pre-create the index. Wisej.AI will automatically create the index if it doesn't already exist.

    Currently, there isn't a well-established UI for Chroma. However, you can try some available options on GitHub for free. One such option we have used is fengzhichao/chromadb-admin. This tool only allows you to view the collections created by Wisej.AI. For any administrative functions, you'll need to use tools like CURL or Postman.

    Pinecone

    When working with Pinecone, you need to create an index to be used with Wisej.AI through the Pinecone dashboard. When setting up a new index, you only need to define the vector size and the metric. Always use "cosine" as the metric. The vector size is determined by the embedding model you plan to use.

    Embedding models are not interchangeable. Therefore, once you create an index, it can only be used with the embedding model for which it was initially configured. In Wisej.AI, the default embedding model is text-embedding-3-small, which requires a vector with 1,536 dimensions.

    To use Pinecone with Wisej.AI, you can register the service as follows:

    The endpoint URL is the service index host address as shown by Pinecone.

    Azure AI Search

    When utilizing Azure AI Search with Wisej.AI, you must first create the index you'll be working with. Since Azure AI Search starts with a blank schema, you need to define all the necessary fields. Refer to the table and JSON file below for a comprehensive list of required fields.

    Name
    Type
    Features

    🔑

    id

    Edm.String

    Retrievable, Filterable

    master

    Edm.Boolean

    Retrievable, Filterable

    documentName

    Edm.String

    Download the JSON definition below to create the index.

    The field that requires particular attention is the vector, where embeddings are stored and searched. When defining this field, select Collection(Edm.Single) and ensure that both the Retrievable and Searchable options are enabled. Additionally, you must specify the Dimensions, which indicate the size of the array based on the embedding model used.

    Embedding models are not interchangeable. Therefore, once you create an index, it can only be used with the embedding model for which it was initially configured. In Wisej.AI, the default embedding model is text-embedding-3-small, which requires a vector with 1,536 dimensions.

    This is what a created index looks like:

    To use Azure AI Search with Wisej.AI, you can register the service as follows:

    The endpoint URL is the service endpoint concatenated with /indexes/<index name>. For example, our tests use `https://aisearchwisej.search.windows.net/indexes/wisejtest`.

    Qdrant

    Qdrant offers flexibility in its deployment options by allowing you to run it locally or utilize Qdrant Cloud. They provide a user-friendly Docker image for local installations and offer a cloud service option. The cloud service includes a free tier hosted on Amazon AWS or Google Cloud, making it accessible and convenient for a variety of use cases.

    With Qdrant, you don't need to pre-create the collection. Wisej.AI will automatically create it, if it doesn't already exist.

    Qdrant Cloud offers an intuitive control panel that allows users to inspect their collections and execute queries directly within the interface.

    Custom Implementation

    To utilize a different vector database with Wisej.AI, you have two options: you can use the database directly, or you can implement the IEmbeddingStorageService interface and register your vector database connection as a Wisej.NET service. When you register your database this way, it will be seamlessly integrated and utilized by the DocumentSearchTools and the SmartHub.IngestDocument() implementations.

    You can use any of the following implementations as a reference or starting point for integrating additional providers and developing your own custom IEmbeddingStorageService implementation. These examples demonstrate the recommended structure and key considerations when extending Wisej.AI with custom storage service integrations.

    Embedding Generation

    The generation of embeddings for chunks of text is handled by the IEmbeddingGenerationService. However, you have the option to generate embeddings directly using any other system or by replacing the service.

    It's crucial to understand that embeddings generated with one model are not compatible with those generated by another model. Consequently, if you store documents and embeddings using a specific model and later change the IEmbeddingGenerationService or the model itself, all previously stored embeddings will become unusable for queries with a different embedding model. This necessitates careful consideration when altering the embedding generation approach to ensure compatibility and continuity.

    This is why Wisej.AI registers a single shared IEmbeddingGenerationService with a default implementation that uses the OpenAIEndpoint and the "text-embedding-3-small" model. We recommend installing a single service implementation at startup and consistently using the same one.

    For instance, if you want to change the model used by the OpenAIEndpoint or utilize your own embedding server, refer to the following example:

    Regarding the IEmbeddingStorageService, Wisej.AI provides several built-in implementations for the IEmbeddingGenerationService. Additionally, you have the flexibility to create your own custom implementations to suit your specific requirements. The built-in services include:

    Name
    Description

    This implementation utilizes the embedding endpoint of any SmartEndpoint that supports embedding functionality. By default, it is configured to use the OpenAIEndpoint. Please note, however, that not all AI providers offer embedding endpoints, so compatibility may vary depending on the provider you choose.

    This implementation leverages the to generate embeddings. You can easily deploy this server locally by using the provided Docker container, allowing for flexible and scalable embedding generation within your own infrastructure.

    Use the code below as a starting point to accelerate the development of your own custom service implementation. This example demonstrates the essential structure and key elements needed to create a new service that integrates seamlessly with the Wisej.AI framework.

    Both implementations also demonstrate how to handle parallel requests. This approach allows your service to process multiple embedding requests concurrently.

    4KB
    AzureAISearch.json
    Open
    21KB
    AzureAISearchEmbeddingStorageService.cs
    Open
    Azure AI Search
    19KB
    ChromaEmbeddingStorageService.cs
    Open
    Chroma DB
    20KB
    PineconeEmbeddingStorageService.cs
    Open
    Pinecone
    5KB
    DefaultEmbeddingGenerationService.cs
    Open
    Uses SmartEndpoints
    6KB
    HuggingFaceEmbeddingGenerationService.cs
    Open
    Uses HF Text Embedding Inference
    Public Class SmartObjectAdapter
        Inherits SmartAdapter

    This class provides methods to convert text, images, streams, and clipboard content into .NET objects. It supports OCR for image processing and can handle multiple iterations to resolve missing values.

    Constructors

    SmartObjectAdapter()

    Initializes a new instance of the SmartObjectAdapter class.

    SmartObjectAdapter(container)

    Initializes a new instance of the SmartObjectAdapter class with the specified container.

    Name
    Type
    Description

    container

    An that represents the container of the component.

    Properties

    MaxIterations

    Int32: Gets or sets the maximum number of times the adapter will try to use the available tools to complete the missing values. (Default: 2)

    If the adapter was not provided any tool, this property is ignored since it will not try to resolve missing values.

    UseOCR

    Boolean: Gets or sets a value indicating whether OCR should be used for image processing. (Default: False)

    Methods

    Dispose(disposing)

    Releases the unmanaged resources used by the SmartObjectAdapter and optionally releases the managed resources.

    Parameter
    Type
    Description

    disposing

    true to release both managed and unmanaged resources; false to release only unmanaged resources.

    FromClipboardAsync<T>()

    Converts the clipboard content to an object of type T .

    Parameter
    Type
    Description

    T

    The type of the object to return.

    Returns: Task<T>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromClipboardAsync(objectType)

    Converts the clipboard content to an object of the specified type.

    Parameter
    Type
    Description

    objectType

    The type of the object to return.

    Returns: Task<Object>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromImageAsync<T>(image)

    Converts the specified image to an object of type T .

    Parameter
    Type
    Description

    T

    The type of the object to return.

    image

    The image to convert.

    Returns: Task<T>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromImageAsync(image, objectType)

    Converts the specified image to an object of the specified type.

    Parameter
    Type
    Description

    image

    The image to convert.

    objectType

    The type of the object to return.

    Returns: Task<Object>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromStreamAsync<T>(stream, streamType)

    Converts the specified stream to an object of type T .

    Parameter
    Type
    Description

    T

    The type of the object to return.

    stream

    The stream to convert.

    streamType

    The type of the stream. Default is null.

    Returns: Task<T>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromStreamAsync(stream, objectType, streamType)

    Converts the specified stream to an object of the specified type.

    Parameter
    Type
    Description

    stream

    The stream to convert.

    objectType

    The type of the object to return.

    streamType

    The type of the stream. Default is null.

    Returns: Task<Object>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromTextAsync<T>(text)

    Converts the specified text to an object of type T .

    Parameter
    Type
    Description

    T

    The type of the object to return.

    text

    The text to convert.

    Returns: Task<T>. A task that represents the asynchronous operation. The task result contains the converted object.

    FromTextAsync(text, objectType)

    Converts the specified text to an object of the specified type.

    Parameter
    Type
    Description

    text

    The text to convert.

    objectType

    The type of the object to return.

    Returns: Task<Object>. A task that represents the asynchronous operation. The task result contains the converted object.

    OnObjectParsed(args)

    Raises the ObjectParsed event.

    Parameter
    Type
    Description

    args

    The instance containing the event data.

    RunAsyncCore(control)

    Executes the core logic of the adapter asynchronously.

    Parameter
    Type
    Description

    control

    The control to use for the operation.

    Returns: Task<Message>. A task that represents the asynchronous operation. The task result contains the response message.

    Events

    ObjectParsed

    ObjectParsedEventHandler Occurs when an object is parsed.

    Implements

    Name
    Description

    Represents a provider that supplies tools.

    SmartAdapter
    SmartObjectAdapter
    public class SmartObjectAdapter : SmartAdapter
    SmartParallelPrompt

    Represents a smart parallel prompt that can execute multiple tasks concurrently.

    public class SmartParallelPrompt : SmartPrompt
    Public Class SmartParallelPrompt
        Inherits SmartPrompt

    This class extends the SmartPrompt class and provides functionality to run multiple prompts in parallel.

    Constructors

    SmartParallelPrompt(text)

    Initializes a new instance of the SmartParallelPrompt class with optional text.

    Name
    Type
    Description

    text

    The text associated with the prompt. Default is null.

    Methods

    AskAsync(hub, inputs)

    Executes the prompt tasks asynchronously in parallel.

    Parameter
    Type
    Description

    hub

    The smart hub used for executing the tasks.

    inputs

    An array of input prompts to process in parallel.

    Returns: Task<Message[]>. A task that represents the asynchronous operation. The task result contains an array of Message objects.

    This method runs each input through the AskAsync method and tracks the progress using the CurrentIndex property.

    Throws:

    • ArgumentNullException Thrown when hub is null.

    • ArgumentNullException Thrown when inputs is null.

    AskAsync(hub, inputs, images)

    Executes the prompt tasks asynchronously in parallel.

    Parameter
    Type
    Description

    hub

    The smart hub used for executing the tasks.

    inputs

    An array of input prompts to process in parallel.

    images

    An array of input images to process in parallel.

    Returns: Task<Message[]>. A task that represents the asynchronous operation. The task result contains an array of Message objects.

    This method runs each input through the AskAsync method and tracks the progress using the CurrentIndex property.

    Throws:

    • ArgumentNullException Thrown when hub is null.

    • ArgumentNullException Thrown when inputs is null.

    • ArgumentNullException Thrown when images is null.

    AskAsync(endpoint, inputs)

    Executes the prompt tasks asynchronously in parallel.

    Parameter
    Type
    Description

    endpoint

    The endpoint used for executing the tasks.

    inputs

    An array of input prompts to process in parallel.

    Returns: Task<Message[]>. A task that represents the asynchronous operation. The task result contains an array of Message objects.

    This method runs each input through the AskAsync method and tracks the progress using the CurrentIndex property.

    Throws:

    • ArgumentNullException Thrown when inputs is null.

    AskAsync(endpoint, inputs, images)

    Executes the prompt tasks asynchronously in parallel.

    Parameter
    Type
    Description

    endpoint

    The endpoint used for executing the tasks.

    inputs

    An array of input prompts to process in parallel.

    images

    An array of input images to process in parallel.

    Returns: Task<Message[]>. A task that represents the asynchronous operation. The task result contains an array of Message objects.

    This method runs each input through the AskAsync method and tracks the progress using the CurrentIndex property.

    Throws:

    • ArgumentNullException Thrown when inputs is null.

    OnProgress(args)

    Raises the Progress event.

    Parameter
    Type
    Description

    args

    The event data.

    Events

    Progress

    ProgressEventHandler Occurs when progress is made in the execution of the parallel tasks.

    Implements

    Name
    Description

    Represents a provider that supplies tools.

    SmartObject
    SmartPrompt

    text

    String

    The initial text for the prompt. Default is null.

    hub

    SmartHub

    The smart hub to use.

    question

    String

    The question to ask.

    image

    Image

    An optional image to include in the question. Default is null.

    endpoint

    SmartEndpoint

    The smart endpoint to use.

    question

    String

    The question to ask.

    image

    Image

    An optional image to include. Default is null.

    tool

    Delegate

    The tool to remove.

    target

    Object

    The target object containing tools.

    key

    String

    The key to resolve.

    filePath

    String

    The file path to save the prompts to.

    tool

    Delegate

    The tool to add.

    target

    Object

    The target object containing tools.

    SmartAgentPrompt

    TODO:

    SmartParallelPrompt

    Represents a smart parallel prompt that can execute multiple tasks concurrently.

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartPrompt
        Inherits SmartObject
        Implements IToolProvider, ICloneable
    SmartPrompt
    SmartPrompt
    IList<IDictionary<String, String>>
    String
    ResolvePrompt
    Task<Message>
    Message
    ArgumentNullException
    Task<Message>
    Message
    ArgumentNullException
    SmartPrompt
    SmartPrompt
    SmartPrompt
    SmartPrompt
    SmartPrompt
    ArgumentNullException
    SmartPrompt
    SmartPrompt
    String
    SmartPrompt
    SmartPrompt
    ArgumentNullException
    SmartPrompt
    SmartPrompt

    Extensibility

    How to Extend and Integrate Wisej.AI

    Overview

    Wisej.AI offers unparalleled flexibility, ensuring that you are not limited by its predefined features. The system is designed to be open and highly extensible. In fact, the majority of the components have virtual members, allowing you to override nearly any functionality. You have the ability to customize all built-in prompts and connect to a wide range of events at various levels, providing a seamless integration experience.

    Considering the architecture of Wisej.AI, you have several options for overriding its built-in functionality and integrating any other AI library of your choice.

    SmartEndpoint

    You can override any of the built-in SmartEndpoints to reuse the existing functionality as needed. Alternatively, you can create a brand-new endpoint by extending either the base or . For instance, if you want to integrate a third-party client for OpenAI (or any other provider) into the Wisej.AI system, you can do so by extending and implementing at least the abstract methods. This approach allows you to customize and tailor the integration according to your specific requirements.

    Many AI providers have standardized their APIs based on the OpenAI API. In such cases, you can use the OpenAIEndpoint within Wisej.AI and modify parameters like the URL, model, and authentication as needed. Alternatively, you can extend the to integrate different properties and adjust any variances specific to your provider. This flexibility allows for seamless adaptation to various AI service requirements.

    SmartAdapter

    To enhance any control with AI features in Wisej.AI, you can create custom adapters. Start by deriving your adapter from SmartAdapter and place your implementation in the RunAsyncCore() method. Within this method, you are responsible for interacting with the AI service and parsing its response. Notably, you are not required to use any of the SmartEndpoints within this process.

    For example, if you want to create an adapter that populates a ComboBox with individual text items generated from an AI prompt, for simplicity you can use the property of the enhanced control to store the prompt. This approach provides a straightforward way to integrate AI-driven functionality into your applications.

    If you wish to enhance the functionality of a control by adding a new property, you can make your adapter implement the interface. This allows the adapter to introduce new properties to the controls it augments. By implementing this interface, you can dynamically extend the capabilities of the associated controls, offering a more sophisticated level of customization.

    After creating the MyComboBoxAdapter as outlined above, follow these steps to integrate it into your project:

    1. Add a SmartHub and SmartEndpoint to your project.

    2. Select your MyComboBoxAdapter.

    3. Drag and drop your adapter onto the open form designer.

    4. Associate the adapter with an existing ComboBox in your interface.

    Once the adapter is linked to the ComboBox, it will automatically add the ItemsPrompt property to the ComboBox. Set this property to something like "European countries" or "US states" and run the application to see it in action. This will allow the ComboBox to populate dynamically based on the AI prompt specified in the ItemsPrompt property, or the Tag property if you didn't extend the IExtenderProvider interface.

    SmartTool

    One of the most powerful features in Wisej.AI is the system. You have the flexibility to utilize or extend any built-in tool, or you can create a new tool from scratch. The system is designed to make this process extremely straightforward and user-friendly, allowing developers to easily customize and extend their application's capabilities.

    You can provide tools to the AI in multiple ways and at different levels within the Wisej.AI framework. For instance, if you annotate a method on the control being designed with the [SmartTool.Tool] attribute and have a component in place, the SmartHub will automatically include this method in the tools available to the AI. This inclusion is independent of the adapter, prompt, or endpoint being used. In essence, once a tool is added to a SmartHub, it is consistently made available to the AI model, ensuring seamless integration and accessibility.

    Ways to provide tools to the AI:

    • To turn a method into a tool within the Wisej.AI system, annotate it with the [SmartTool.Tool] attribute. This method will be available as a tool if it is declared within a container that's associated with a SmartHub. Alternatively, the method can become a tool if it is part of an object that is passed to the UseTools() method of a , , , or . This flexible integration ensures that your tools can be widely accessible across different components of your application.

    • You can directly provide a specific method to the SmartHub, SmartPrompt, SmartAdapter, or SmartSession components by using the UseTool() method. For example, to pass a method such as get_customer_id to a SmartHub, you would use the following code: smartHub1.UseTool(this.get_customer_id);. This approach allows you to easily leverage specific methods as tools without needing to encapsulate them within a class or container.

    For instance, if you want to enable the AI to send an email while performing other tasks, you can create a tools class with two methods. One method can be designed to send the email, while the other can be developed to find the recipient's email address, adding an intelligent layer to the process. By integrating this tools class into the Wisej.AI framework, you can provide the AI with advanced capabilities for handling emails efficiently as part of its operations.

    You can enhance the usability and clarity of the tools within Wisej.AI by using the Description attribute to annotate various components. You can annotate the tools container class, each method, and each parameter with this attribute. These additional annotations provide the AI with detailed information, allowing it to utilize the tools more effectively and accurately, ensuring that each tool is used correctly within your application.

    This is an example of the built-in annotation for the DatabaseTools bulilt-in tools container:

    Using an INI file offers several advantages when working with prompts in Wisej.AI. It allows you to craft clearer and more complex prompts and gives you the flexibility to fine-tune these prompts externally, without needing to modify your application's code. This external configuration capability enhances maintainability and adaptability, enabling you to adjust prompts as needed without redeploying your application.

    In Wisej.AI, a tool can modify its own prompt by programmatically replacing placeholders like {{server-type}} and {{database-schema}} with specific values relevant to the tool itself. This can be achieved by implementing logic within the tool's initialization or execution process to dynamically insert the appropriate values into the prompt.

    For instance, you can define a method within the tool that retrieves the required information—for example, the server type or database schema—and injects these values into the prompt before it is processed. This approach ensures that the prompt is precisely tailored based on the tool's configuration or current state, maintaining the flexibility and relevance of the information provided to the AI.

    To enable a tool to modify its own prompt with specific values for placeholders, your tools container class should either implement the interface or extend the class. By leveraging these options, you can incorporate the necessary logic to dynamically replace placeholders in prompts with context-specific information. This allows for greater customization and flexibility when configuring how tools interact with the AI in Wisej.AI.

    If you modify the MyEmailTools example to include a placeholder in the tool's prompt, it might look something like this:

    By using placeholders in prompts and implementing the logic to replace them with actual data dynamically, you can create flexible and context-aware tools in Wisej.AI.

    Here are some functionalities you can use as inspiration for developing your tools:

    • Search the database

    • Search the file system

    • Search a document storage

    • Search the web

    When augmented with sophisticated tools, there is virtually no limit to what an AI system can achieve.

    Services

    Wisej.AI's internal implementation leverages a variety of for its adapters, tools, embeddings, and other AI functionalities. As a developer, you have the flexibility to override these built-in implementations or replace them with your own, including the use of alternative AI frameworks.

    Using Semantic Kernel

    If your code relies on Semantic Kernel (SK), you can seamlessly integrate it into the Wisej.AI system at various points and execution levels. This flexibility allows you to enhance functionality and tailor the system to your specific needs.

    As mentioned earlier, Wisej.AI functions at a higher level compared to foundational libraries like Semantic Kernel. While both Wisej.AI and SK offer similar basic functionalities, Wisej.AI provides a more integrated and advanced set of features designed for complex application development. To illustrate this, here is a comparison using a simple :

    If you wish to integrate Semantic Kernel with Wisej.AI, you certainly can:

    • You can implement a new SKEndpoint derived from SmartEndpoint and use the SK's clients.

    • You can override the RunAsyncCore() in any of the existing adapters and use SK's plugin system, clients, embedding system, etc. Or you can implement it like this from the start in new adapters.

    • You can re-implement any of the that Wisej.AI uses in various places to use SK's vector storage support, document conversion, tokenization, chunking, etc.

    Using Custom Libraries

    While there may not be other directly comparable .NET libraries in the space that Wisej.AI occupies, the concept of integrating other libraries, like Semantic Kernel, applies broadly. You can seamlessly incorporate any other compatible library into your Wisej.AI applications. This approach allows you to extend the capabilities of your applications by combining the specific features and strengths of other libraries with the robust, high-level functionalities provided by Wisej.AI.

    Architecture

    Detailed description of the Wisej.AI architecture and all its components.

    Overview

    Wisej.AI is specifically designed with developers in mind to seamlessly integrate AI systems into business applications.

    High Level Wisej.AI Architecture

    The system fundamentally operates by utilizing the application's controls and code to construct sophisticated prompts. These prompts are then sent to the AI provider, and the response is parsed in accordance with the requirements of the controls and code.

    Wisej.AI is composed of these key components:

    • SmartEndpoint

    • SmartPrompt

    • SmartAdapter

    • SmartTool

    • SmartSession

    • SmartHub

    In developing Wisej.AI, several fundamental principles were adopted: maintaining simplicity, avoiding over-engineering, delivering real value to developers, and ensuring the system is self-contained with minimal dependencies.

    Wisej.AI supports .NET Core, .NET Framework, C#, and VB.NET.

    To maintain simplicity and minimize dependencies, Wisej.AI does not utilize libraries such as Newtonsoft, Semantic Kernel, or any REST clients.

    SmartEndpoint

    As the name implies, the components are responsible for managing all communications between an endpoint and the rest of the system. An endpoint refers to the URL of the AI engine where the Large Language Model (LLM) is running. This can be hosted on a local server on-premises, a private server in a data center, at any public AI providers, or even in your browser as a JavaScript worker.

    SmartEndpoint components are designed to support any AI provider and handle various payload types, including binary data and images. They define numerous properties and methods specifically tailored to handle inference and embedding requests efficiently.

    SmartPrompt

    The component manages both system and user prompts. It resolves prompt text from INI files, replaces placeholders with parameter values, and offers a straightforward method for interacting with the AI.

    For instance, using Wisej.AI in its simplest form requires just an endpoint. Here's an example:

    An even simpler approach, requiring fewer lines of code, is available by using the . However, regardless of the method chosen, an endpoint is always necessary.

    Prompts can either be written directly in code or referenced using a key string enclosed in square brackets. SmartPrompt will locate the key and read the corresponding prompt from any .ini file stored in the /AI folder. See for more information on INI files.

    Prompts can also include placeholders, or parameters, which are replaced at runtime. These placeholders must be enclosed within {{ }}. However, when setting a parameter value, you should specify the parameter name without the curly brackets.

    Parameters are always replaced before submitting a question but only within the initial System Prompt and the current user prompt. The earlier example using parameters might look like this:

    SmartAdapter

    act as mediators between the application and the AI, adapting data and processes to fit specific needs. Each adapter has a distinct role and set of features. For instance, the SmartDataEntryAdapter extracts structured data from unstructured sources and updates Wisej.NET controls with the relevant information. Similarly, the SmartObjectAdapter performs this function by setting properties of .NET objects instead of updating controls. Another example is the SmartChartAdapter, which creates charts from unstructured data.

    A SmartAdapter operates by leveraging an instance of the SmartHub, which in turn requires an instance of the SmartEndpoint. When using a SmartAdapter, you're essentially working within the structure outlined in the diagram at the top of this page.

    Once the adapter is properly configured, the following example demonstrates the powerful capabilities of the SmartObjectAdapter:

    With just one line of code, we accomplish a task that would be nearly impossible to achieve using standard programming methods.

    SmartTool

    are integral to the Wisej.AI architecture. By utilizing SmartTools, you can "compose" powerful AI systems that deliver significant value to your applications. A SmartTool, at its core, is a function—code that executes, accepts parameters, and returns a result.

    In Wisej.AI, having an exceptionally powerful tools system is a core feature. SmartTools in Wisej.AI go beyond simple method callbacks or the plugin systems found in Semantic Kernel. They are designed to offer rich, extensible functionalities, providing developers with advanced capabilities to enhance and augment their applications seamlessly.

    These functions (tools) operate within the context in which they were created, allowing them to:

    • Keep state information

    • Update controls on the screen

    • Work within the user session

    • Access any resource available to the application

    Wisej.AI offers a unique capability to interact seamlessly with the user interface (UI) without limitations. Unlike Wisej.AI, Microsoft Semantic Kernel plugins are not integrated with any specific UI framework, which restricts their ability to perform such interactions. In any event, achieving this level of UI interaction would be extremely challenging with templating frameworks like Blazor, Angular, React, or other templating frameworks.

    Since code often speaks louder than words, here is a very simple example to illustrate how SmartTools function:

    Initially, the AI has responded that it cannot provide the current time. This is accurate, as AI models do not have the capability to gather real-time information outside of what is encoded in their neural network weights.

    After incorporating prompt.UseTool(GetCurrentTime), the AI became capable of returning the current time. Essentially, we provided the AI with a tool, enabling it with a new capability. By programming such tools—be they small functions or more complex ones—we extend the AI's functionality.

    In Wisej.AI, the interaction between a "new feature" (the tools) and the AI is handled effectively by the system. Essentially, every interaction is managed by an agent, ensuring seamless integration and functionality.

    Wisej.AI employs its own tool definition prompting, rather than using the default defined by the AI model in use. This approach provides greater control over tool usage, reduces token consumption, and enables the use of tools even with models that were not originally trained with such capabilities.

    Note that the AddTool() and AddTools() methods support call chaining:

    Keep in mind that tools can also be implemented as asynchronous methods. This allows the code within these tools to interact with the user through the Wisej.NET user interface. Additionally, it enables the invocation of other services. Through the use of asynchronous methods, your application can handle long-running operations without blocking the user interface.

    In addition to async tools, Wisej.AI also supports anonymous tools:

    Being a lamba method, it runs in context allowing the code in the lamba to reference local variables declared in the containing code.

    SmartSession

    As explained on the General Concepts page, LLMs do not possess any memory, do not remember past interactions, and are inherently stateless. Each time you ask a question, it is akin to talking to .

    Dory is a fictional blue tang fish and a major character of Pixar's animated film series Finding Nemo. She suffers from short-term memory loss.

    The Wisej.AI agent system operates within the SmartSession. This is where Wisej.AI constructs the prompts, invokes the tools, and repeats the process until the LLM has completed the requested task. Additionally, the SmartSession in Wisej.AI is capable of managing message length when the context window is exceeded by either trimming or summarizing previous messages.

    Every interaction with the LLM involves an instance of the SmartSession component. Even for a single prompt, Wisej.AI always creates and disposes of a session internally. This ensures that every request can utilize tools and operate within the boundaries set by Wisej.AI.

    You can use the SmartSession, or a custom-derived class, to maintain the state of the interaction with the LLM and preserve the context effectively.

    The example above demonstrates a session with two interactions with the LLM. In the first interaction, an image and a prompt are submitted. In the second interaction, you can refer to the image without resubmitting it, as it is part of the session and will be automatically included.

    Interactions that include images are only compatible with models that have vision capabilities. Adapters that work with images have the UseOCR property allowing the usage the and extract text from the image (without relying on the model's vision) before sending it to the AI.

    SmartHub

    The final component is the . As the name suggests, it functions as a central hub, connecting an endpoint, multiple adapters, custom tools, and your Wisej.NET application.

    With the SmartHub, you can manage messages, errors, and parameters related to all the adapters connected to both the SmartHub and the endpoint. A SmartHub always requires one endpoint, but it can be associated with multiple adapters.

    In addition to centralizing events and connecting adapters to an endpoint, the SmartHub offers a variety of higher-level functions that leverage all the built-in services in Wisej.AI. Essentially, it provides developers with a high-level interface to interact with the AI.

    When the SmartHub is placed onto a designer surface of a component, it automatically binds to the top-level component and registers all methods marked with the [SmartTool.Tool] attribute as tools.

    In all code snippets when an endpoint is created without an api key, the assumption is that you have the ApiKeys.json file in /AI, see .

    Events

    In Wisej.AI, the majority of objects are designed to trigger various events, enabling applications to interact with AI processes at multiple stages. While individual SmartAdapters may offer their own unique events, three key components—, , and —uniformly raise a standardized set of events. This consistent event pattern facilitates seamless integration and enhances the interactivity between the application and Wisej.AI functionalities.

    Name
    Description

    Events are typically triggered in the following sequence:

    1. SmartSession

    2. SmartPrompt

    3. SmartHub

    When event arguments are derived from HandledEventArgs, listeners have the option to set the Handled property to true. This signals that the event has already been addressed by the listener. For instance, when handling the BeforeInvokeTool event, if you set e.Handled to true, the system will not proceed to invoke the tool, as it will presume that your code has already taken care of the necessary actions.

    This feature allows you to intercept a tool call and carry out additional operations either before, after, or instead of executing the tool. This capability provides flexibility in customizing the behavior of your application, enabling you to implement complex logic or alternative workflows as needed.

    internal static class Program
    {
      static Program()
      {
        Application.Services
          .AddOrReplaceService<IEmbeddingStorageService>(
            new PineconeEmbeddingStorageService("<endpoint url>"));
      }
    }
    Module Program
      Shared Sub New()
        Application.Services.AddOrReplaceService( _
          Of IEmbeddingStorageService)( _
            New PineconeEmbeddingStorageService("<endpoint url>"))
      End Sub
    End Module
    internal static class Program
    {
      static Program()
      {
        Application.Services
          .AddOrReplaceService<IEmbeddingStorageService>(
            new AzureAISearchEmbeddingStorageService("<endpoint url>"));
      }
    }
    Module Program
      Shared Sub New()
        Application.Services.AddOrReplaceService( _
          Of IEmbeddingStorageService)( _
            New AzureAISearchEmbeddingStorageService("<endpoint url>"))
      End Sub
    End Module
    static class Program
    {
        static Program()
        {
            Application.Services
                .AddOrReplaceService<IEmbeddingGenerationService>(
                    new DefaultEmbeddingGenerationService(
                        new OpenAIEndpoint{ EmbeddingModel = "text-embedding-3-large" }));
            // Or   
            Application.Services
                .AddOrReplaceService<IEmbeddingGenerationService>(
                    new HuggingFaceEmbeddingGenerationService("http://ollama.myserver.com:8090"));
        
            // Or
            Application.Services
                .AddOrReplaceService<IEmbeddingGenerationService>(
                    new DefaultEmbeddingGenerationService(
                        new TogetherAIEndpoint()));
        }
    }
    Module Program
    
        Sub New()
            Application.Services.AddOrReplaceService(Of IEmbeddingGenerationService)(
                New DefaultEmbeddingGenerationService(
                    New OpenAIEndpoint With {.EmbeddingModel = "text-embedding-3-large"}))
    
            ' Or
            Application.Services.AddOrReplaceService(Of IEmbeddingGenerationService)(
                New HuggingFaceEmbeddingGenerationService("http://ollama.myserver.com:8090"))
    
            ' Or
            Application.Services.AddOrReplaceService(Of IEmbeddingGenerationService)(
                New DefaultEmbeddingGenerationService(
                    New TogetherAIEndpoint()))   
        End Sub
    
    End Module
    await this.smartHub1.IngestDocumentAsync(
        "C:\\Files\\2024\\AAPL-10K.pdf"), "10Ks\\2024\\AAPL-10K.pdf");
    await this.smartHub1.IngestDocumentAsync(
        "C:\\Files\\2023\\AAPL-10K.pdf"), "10Ks\\2023\\AAPL-10K.pdf");
    await this.smartHub1.IngestDocumentAsync(
        "C:\\Files\\2024\\AAPL-10K.pdf"), "10Ks\\2024\\AAPL-10K.pdf", "Apple Docs");
    await this.smartHub1.IngestDocumentAsync(
        "C:\\Files\\Logs\\ServiceLogs.txt"), "ServiceLogs.txt", "Logs");
    var metadata = Metadata();
        metadata["ServiceName"] = "W3WP-1";
    await this.smartHub1.IngestDocumentAsync(
        "C:\\Files\\Logs\\ServiceLogs.txt"), "ServiceLogs.txt", "Logs", true, metadata);
    
    var smartPrompt = new SmartParallelPrompt();
    var messages = await smartPrompt.RunAsync(hub, new string[] { "input1", "input2" });
    
    
    var smartPrompt = new SmartParallelPrompt();
    var messages = await smartPrompt.RunAsync(hub, new string[] { "input1", "input2" });
    
    
    var smartPrompt = new SmartParallelPrompt();
    var messages = await smartPrompt.RunAsync(hub, new string[] { "input1", "input2" });
    
    
    var smartPrompt = new SmartParallelPrompt();
    var messages = await smartPrompt.RunAsync(hub, new string[] { "input1", "input2" });
    
    
    SmartPrompt prompt = new SmartPrompt("You are a weather expert");
    prompt.Start += (s, e) => Console.WriteLine("Processing started.");
    prompt.Done += (s, e) => Console.WriteLine("Processing done.");
    await prompt.AskAsync(new OpenAIEndpoint(), "What is the weather today?");
    
    IContainer
    IContainer
    Boolean
    Type
    Image
    Image
    Type
    Stream
    String
    Stream
    Type
    String
    String
    String
    Type
    ObjectParsedEventArgs
    ObjectParsedEventArgs
    Control
    IToolProvider
    String
    SmartHub
    String[]
    SmartHub
    String[]
    Image[]
    SmartEndpoint
    String[]
    SmartEndpoint
    String[]
    Image[]
    ProgressEventArgs
    IToolProvider

    Retrievable, Filterable

    âš¡

    vector

    Collection(Edm.Single)

    Retrievable, Searchable

    collectionName

    Edm.String

    Retrievable, Filterable

    metadata

    Edm.String

    Retrievable, Filterable

    chunk

    Edm.String

    Retrievable, Filterable

    DefaultEmbeddingGenerationService
    HuggingFaceEmbeddingGenerationService
    HuggingFace Text Embedding Inference server
    Interact with Office 365 using Microsoft Graph
  • Read incoming emails

  • Send emails

  • Read signals in a SCADA system

  • SmartEndpoint
    SmartHttpEndpoint
    SmartEndpoint
    OpenAIEndpoint
    Tag
    Wisej.Web.ComboBox
    IExtenderProvider
    SmartTool
    SmartHub
    SmartHub
    SmartPrompt
    SmartAdapter
    SmartSession
    IToolsContainer
    ToolsContainer
    services
    tool example
    services
    [Extends(typeof(ComboBox), allowMultiple: true)]
    public class MyComboBoxAdapter : SmartAdapter
    {
       SmartPrompt _prompt;
       public MyComboBoxAdapter()
       {
           _prompt = new SmartPrompt(
             "Your job is to create a comma separated list " + 
             "of the items described by the user.");
       }
    
       protected override async Task<SmartSession.Message> RunAsyncCore(
           Control control)
       {
           var comboBox = control as ComboBox;
           if (comboBox == null)
               return null;
    
           var question = control.Tag as string;
           if (String.IsNullOrEmpty(question))
               return null;
    
           var response = await _prompt.AskAsync(this.Hub, question);
           comboBox.Items.Clear();
           comboBox.Items.AddRange(
               response.Text.Split(',')
                            .Select(t => t.Trim())
                            .ToArray());
    
           return response;
       }
    }
    Asynchronously interact with external systems, i.e. databases, search engines, vector database
  • Provide parameters that alter their own prompt

  • Interact with the calling context and callers

  • Interact with the user through the Wisej.NET UI

  • Return synchronous and asynchronous values

  • BeforeInvokeTool

    Occurs before a tool is invoked.

    AfterInvokeTool

    Occurs after a tool is invoked.

    PrepareMessages

    Occurs after the messages have been prepared and before they are send to the AI.

    Start

    Occurs when the session starts processing a question.

    Done

    Occurs when the session is done processing a question.

    Error

    Occurs when an error is encountered.

    BeforeSendRequest

    Occurs before a request is sent.

    AfterResponseReceived

    Occurs after a response is received.

    ConvertParameter

    Occurs when a parameter needs to be converted.

    SmartEndpoint
    SmartPrompt
    SmartHub
    SmartPrompt INI
    SmartAdapters
    SmartTools
    Dory the fish from Finding Nemo
    IOCRService
    SmartHub
    SmartPrompt
    SmartSession
    SmartHub
    ApiKeys.json File
    <Extends(GetType(ComboBox), AllowMultiple:=True)>
    Public Class MyComboBoxAdapter
        Inherits SmartAdapter
    
        Private _prompt As SmartPrompt
    
        Public Sub New()
            _prompt = New SmartPrompt( _
                "Your job is to create a comma " & _
                "separated list of the items described by the user.")
        End Sub
    
        Protected Overrides Async Function RunAsyncCore(control As Control) 
        As Task(Of SmartSession.Message)
            Dim comboBox = TryCast(control, ComboBox)
            If comboBox Is Nothing Then
                Return Nothing
            End If
    
            Dim question = TryCast(control.Tag, String)
            If String.IsNullOrEmpty(question) Then
                Return Nothing
            End If
    
            Dim response = Await _prompt.AskAsync(Me.Hub, question)
            comboBox.Items.Clear()
            comboBox.Items.AddRange(response.Text.Split(","c).
                                    Select(Function(t) t.Trim()).
                                    ToArray())
            Return response
        End Function
    End Class
    [ProvideProperty("ItemsPrompt", typeof(ComboBox))]
    [Extends(typeof(ComboBox), allowMultiple: true)]
    public class MyComboBoxAdapter : SmartAdapter, IExtenderProvider
    {
    	// Same as above
    
    	[Category("AI Features")]
    	public string GetItemsPrompt(Control control)
    	{
    		return control.UserData.ItemsPrompt as string;
    	}
    
    	public void SetItemsPrompt(Control control, string text)
    	{
    		control.UserData.ItemsPrompt = text;
    	}
    
    	bool IExtenderProvider.CanExtend(object extendee)
    	{
    		var control = extendee as Control;
    		if (IsAssociatedWith(control))
    			return control is ComboBox;
    
    		return false;
    	}
    }
    <ProvideProperty("ItemsPrompt", GetType(ComboBox))>
    <Extends(GetType(ComboBox), allowMultiple:=True)>
    Public Class MyComboBoxAdapter
        Inherits SmartAdapter
        Implements IExtenderProvider
        
        '' Same as above
    
        <Category("AI Features")>
        Public Function GetItemsPrompt(control As Control) As String
            Return TryCast(control.UserData.ItemsPrompt, String)
        End Function
    
        Public Sub SetItemsPrompt(control As Control, text As String)
            control.UserData.ItemsPrompt = text
        End Sub
    
        Private Function CanExtend(extendee As Object) As Boolean 
        Implements IExtenderProvider.CanExtend
            Dim control As Control = TryCast(extendee, Control)
            If IsAssociatedWith(control) Then
                Return TypeOf control Is ComboBox
            End If
            Return False
        End Function
    
    End Class
    [Description("[MyEmailTools]")]
    public class MyEmailTools
    {
     [SmartTool.Tool]
     private string find_email_address(string name)
     {
         var emailAddress = "[email protected]";
         return emailAddress;
     }
    
     [SmartTool.Tool]
     private bool send_email(string emailAddress, string subject, string body)
     {
         var email = new Emailer();
         return email.SendEmail(emailAddress, subject, body);
     }
    }
    
    ...
    
    this.smartDataEntryAdapter1.UseTools(new MyEmailsTools());
    MyPrompts.ini file
    # Prompt for MyEmailTools
    [MyEmailTools]
    Use this tool to send an email to the account manager assigned 
    to the new case entered into the system. The subject should be the 
    case number followed by a - and a short summary of the case. The body
    should contain all the data of the case in a table.
    <Description("[MyEmailTools]")>
    Public Class MyEmailTools
        <SmartTool.Tool>
        Private Function find_email_address(name As String) As String
            Dim emailAddress = "[email protected]"
            Return emailAddress
        End Function
    
        <SmartTool.Tool>
        Private Function send_email(
        emailAddress As String, subject As String, body As String) As Boolean
            Dim email = New Emailer()
            Return email.SendEmail(emailAddress, subject, body)
        End Function
    End Class
    
    ...
    
    Me.smartAdapter1.UseTools(New MyEmailTools())
    MyPrompts.ini file
    # Prompt for MyEmailTools
    [MyEmailTools]
    Use this tool to send an email to the account manager assigned 
    to the new case entered into the system. The subject should be the 
    case number followed by a - and a short summary of the case. The body
    should contain all the data of the case in a table.
    #
    # DatabaseTools
    #
    [DatabaseTools]
    Provides tools to access the database.
    Unless instructed otherwise, use it before the web search tools.
    
    Instructions:
    - Use only the tables defined in the Database Schema.
    - The generated SQL statement MUST be valid for "{{server-type}}".
    - Define column aliases within single quotes.
    - Enclose column names in [].
    
    ```Database Schema
    {{database-schema}}
    ```
    
    [DatabaseTools.select]
    Executes a SQL SELECT command on the database to retrieve the specified data.
    
    [DatabaseTools.select.sql]
    A well-formed SQL SELECT statement using the tables and 
    columns defined in the Database Schema.
    MyPrompts.ini file
    # Prompt for MyEmailTools
    [MyEmailTools]
    Use this tool to send an email to the {{recipient_types}} assigned 
    to the new case entered into the system. The subject should be the 
    case number followed by a - and a short summary of the case. The body
    should contain all the data of the case in a table.
    public MyEmailTools(bool notifySupervisor)
    {
     if (!notifySupervisor)
         this.Parameters.Add("recipient_types", "Account Manager");
     else
         this.Parameters.Add("recipient_types", "Account Manager and Supervisor");
    }
    
    ...
    
    this.smartDataEntryAdapter1.UseTools(new MyEmailsTools(true));
    MyPrompts.ini file
    # Prompt for MyEmailTools
    [MyEmailTools]
    Use this tool to send an email to the {{recipient_types}} assigned 
    to the new case entered into the system. The subject should be the 
    case number followed by a - and a short summary of the case. The body
    should contain all the data of the case in a table.
    Public Sub New(notifySupervisor As Boolean)
        If Not notifySupervisor Then
            Me.Parameters.Add("recipient_types", "Account Manager")
        Else
            Me.Parameters.Add("recipient_types", "Account Manager and Supervisor")
        End If
    End Sub
    
    ...
    
    Me.smartDataEntryAdapter1.UseTools(New MyEmailTools(True))
    using Wisej.AI;
    using Wisej.AI.Endpoints;
    
    // Create a smart prompt with a plugin (defined elsewhere)
    var prompt = new SmartPrompt().UseTool(new LigthsPlugin());
    
    // Create the AzureAI endpoint
    var endpoint = new AzureAIEndpoint { URL = url };
    
    // Ask the question and get the answer from the AI
    var answer = prompt.AskAsync(endpoint, "Please turn on the lamp");
    
    // Print the results
    Console.WriteLine("Assistant > " + answer);
    using Microsoft.SemanticKernel;
    using Microsoft.SemanticKernel.ChatCompletion;
    using Microsoft.SemanticKernel.Connectors.OpenAI;
    
    // Create a kernel with Azure OpenAI chat completion
    var builder = Kernel.CreateBuilder().AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
    
    // Build the kernel
    Kernel kernel = builder.Build();
    var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
    
    // Add a plugin (the LightsPlugin class is defined elsewhere)
    kernel.Plugins.AddFromType<LightsPlugin>("Lights");
    
    // Enable planning
    OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new() 
    {
        FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
    };
    
    // Create a history store the conversation
    var history = new ChatHistory();
    history.AddUserMessage("Please turn on the lamp");
    
    // Get the response from the AI
    var result = await chatCompletionService.GetChatMessageContentAsync(
       history,
       executionSettings: openAIPromptExecutionSettings,
       kernel: kernel);
    
    // Print the results
    Console.WriteLine("Assistant > " + result);
    
    // Add the message from the agent to the chat history
    history.AddAssistantMessage(result);
    var prompt = new SmartPrompt();
    var endpoint = new OpenAIEndpoint() { ApiKey = "..." };
    var response = await prompt.AskAsync(
        endpoint, 
        "Tell me a fun short story about a bee in less than 50 words.");
    
    Console.WriteLine(response.Text);
    Dim prompt As New SmartPrompt()
    Dim endpoint As New OpenAIEndpoint() With {.ApiKey = "..."}
    Dim response = Await prompt.AskAsync( _
        endpoint, _
        "Tell me a fun short story about a bee in less than 50 words.")
    
    Console.WriteLine(response.Text)
    var prompt = new SmartPrompt();
    var endpoint = new OpenAIEndpoint() { ApiKey = "..." };
    
    prompt.Parameters.Add("word-count", 50);
    var response = await prompt.AskAsync(
       endpoint, 
       "Tell me a fun short story about a bee in less than {{word-count}} words.");
    
    Console.WriteLine(response.Text);
    Dim prompt As New SmartPrompt()
    Dim endpoint As New OpenAIEndpoint() With {.ApiKey = "..."}
    
    prompt.Parameters.Add("word-count", 50)
    Dim response = Await prompt.AskAsync( _
        endpoint, _
        "Tell me a fun short story about a bee in less than {{word-count}} words.")
    
    Console.WriteLine(response.Text)
    public class Person
    {
      [Description("First name")]
      public string FirstName { get; set; }
    
      [Description("Surname")]
      public string Surname { get; set; }
    
      [Description("Job title")]
      public string Title { get; set; }
    
      [Description("Extract list of personal interests from the text, summarize in 1-3 words maximum and change to title case")]
      public string[] Interests { get; set; }
    
      [Description("Person Address")]
      public string Address { get; set; }
    }
    
    var adapter = new SmartObjectAdapter()
    {
      Hub = new SmartHub()
      {
        Endpoint = new OpenAIEndpoint()
        {
          ApiKey = "..."
        }
      }
    };
    
    // Extract the field values described above from resume.pdf.
    var person = await adapter.FromStreamAsync<Person>(File.OpenRead("resume.pdf"));
    
    // Or
    var person = await adapter.FromImageAsync<Person>(businessCardImage);
    Public Class Person
        <Description("First name")> _
        Public Property FirstName As String
    
        <Description("Surname")> _
        Public Property Surname As String
    
        <Description("Job title")> _
        Public Property Title As String
    
        <Description("Extract list of personal interests from the text, summarize in 1-3 words maximum and change to title case")> _
        Public Property Interests As String()
    
        <Description("Person Address")> _
        Public Property Address As String
    End Class
    
    Dim adapter = New SmartObjectAdapter() With { _
        .Hub = New SmartHub() With { _
            .Endpoint = New OpenAIEndpoint() With { _
                .ApiKey = "..." _
            } _
        } _
    }
    
    ' Extract the field values described above from resume.pdf.
    Dim person = Await adapter.FromStreamAsync(Of Person)(File.OpenRead("resume.pdf"))
    
    ' Or
    Dim person = Await adapter.FromImageAsync(Of Person)(businessCardImage)
    var prompt = new SmartPrompt();
    var endpoint = new OpenAIEndpoint();
    var response = await prompt.AskAsync(endpoint, "What time is it?");
    Console.WriteLine(response.Text);
    
    // output:
    // I'm sorry, but I don't have the capability to 
    // provide real-time information such as the current time.
    
    prompt.UseTool(GetCurrentTime);
    response = await prompt.AskAsync(endpoint, "What time is it?");
    Console.WriteLine(response.Text);
    
    // output:
    // The current time is 4:51:38 PM.
    
    ...
    private static string GetCurrentTime()
        => DateTime.Now.ToLongTimeString()
    Dim prompt As New SmartPrompt()
    Dim endpoint As New OpenAIEndpoint()
    Dim response = Await prompt.AskAsync(endpoint, "What time is it?")
    Console.WriteLine(response.Text)
    
    ' output:
    ' I'm sorry, but I don't have the capability to
    ' provide real-time information such as the current time.
    
    prompt.UseTool(AddressOf GetCurrentTime)
    response = Await prompt.AskAsync(endpoint, "What time is it?")
    Console.WriteLine(response.Text)
    
    ' output:
    ' The current time is 4:51:38 PM.
    
    ...
    
    Private Shared Function GetCurrentTime() As String
        Return DateTime.Now.ToLongTimeString()
    End Function
    this.smartObjectAdapter
        .UseTools(new WebSearchTools())
        .UseTools(new MathTools())
        .UseTool(TurnLightsOnOff);
    prompt.UseTool(
        [Description("Returns the current date/time")]
        () => DateTime.Now);
    using (var session = new SmartSession(new OpenAIEndpoint()))
    {
      var response = await session.AskAsync(
        "Extract the emails in the image.",
        screenshot);
        
      Console.WriteLine(response.Text);
      
      response = await session.AskAsync("Extract all the dates.");
      
      Console.WriteLine(response.Text);
    }
    
     Using session As New SmartSession(New OpenAIEndpoint())
       Dim response = Await session.AskAsync( _
         "Extract the emails in the image.", _
         screenshot)
         
       Console.WriteLine(response.Text)
    
       response = Await session.AskAsync("Extract all the dates.")
       
       Console.WriteLine(response.Text)
    End Using
    var hub = new SmartHub();
    hub.Endpoint = new OpenAIEndpoint();
    
    // Splits the pdf into chunks using IDocumentConversionService and ITextSplitterService
    // Generates the embeddings for each chunk using IEmbeddingGenerationService
    // Stores the chunks and the embeddings in a vector DB using IEmbeddingStorageService
    await hub.IngestDocumentAsync("JP-CV.pdf", "jp-cv-00012.pdf");
    
    // Generates the embedding using IEmbeddingGenerationService
    var query = await hub.EmbedAsync("Experience");
    
    // Finds the 1 chunk that is most relevant to "Wisej.NET" and
    // has a similarity of at least 0.2.
    var topChunks = await hub.SimilarityQueryAsync(
    	"Wisej.NET",
    	new[] { "Wisej.NET is...", "Bananas are not apples..." },
    	1,
    	0.2f);
    Dim hub As New SmartHub()
    hub.Endpoint = New OpenAIEndpoint()
    
    ' Splits the PDF into chunks using IDocumentConversionService and ITextSplitterService
    ' Generates the embeddings for each chunk using IEmbeddingGenerationService
    ' Stores the chunks and the embeddings in a vector DB using IEmbeddingStorageService
    Await hub.IngestDocumentAsync("JP-CV.pdf", "jp-cv-00012.pdf")
    
    ' Generates the embedding using IEmbeddingGenerationService
    Dim query = Await hub.EmbedAsync("Experience")
    
    ' Finds the 1 chunk that is most relevant to "Wisej.NET" and
    ' has a similarity of at least 0.2.
    Dim topChunks = Await hub.SimilarityQueryAsync(
        "Wisej.NET",
        New String() { "Wisej.NET is...", "Bananas are not apples..." },
        1,
        0.2F)

    SmartDataEntryAdapter

    Wisej.AI.Adapters.SmartDataEntryAdapter

    Namespace: Wisej.AI.Adapters

    Assembly: Wisej.AI (3.5.0.0)

    • SmartAdapter

      • SmartDataEntryAdapter

    Enhances all the controls in the associated container with the AI-powered capability to extract structured data from unstructured text.

    public class SmartDataEntryAdapter : SmartAdapter, IExtenderProvider

    Works with:

    • AzureAI/OpenAI gpt-4

    • AzureAI/OpenAI gpt-4o

    • AzureAI/OpenAI gpt-3.5

    • AzureAI/Anthropic Claude

    Supports several types of sources for the input text: Clipboard (text or image), PDF stream, Text, Word, Excel. Uses the extension to run the OCR text extraction on the user's browser in JavaScript.

    Constructors

    SmartDataEntryAdapter()

    Initializes a new instance of the class.

    SmartDataEntryAdapter(container)

    Initializes a new instance of the class with the specified container.

    Name
    Type
    Description

    Properties

    ExcludeReadOnly

    : Gets or sets a value indicating whether read-only controls should be excluded. (Default: False)

    MaxIterations

    : Gets or sets the maximum number of times the adapter will try to use the available tools to complete the missing values. (Default: 2)

    If the adapter was not provided any tool, this property is ignored since it will not try to resolve missing values.

    UseOCR

    : Gets or sets a value indicating whether OCR should be used for image processing. (Default: False)

    Methods

    Dispose(disposing)

    Releases the unmanaged resources used by the and optionally releases the managed resources.

    Parameter
    Type
    Description

    FromClipboardAsync()

    Asynchronously processes data from the clipboard and extracts structured data.

    Returns: . A task representing the asynchronous operation.

    Throws:

    • Thrown when the SmartAdapter is busy.

    FromImageAsync(image)

    Asynchronously processes the provided image and extracts structured data.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    Throws:

    • Thrown when the image is null.

    • Thrown when the SmartAdapter is busy.

    FromStreamAsync(stream, streamType)

    Asynchronously processes the provided stream and extracts text and image data. If an image is detected without associated text, the method attempts to perform OCR to extract text.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    Throws:

    • Thrown when the stream is null.

    • Thrown when the SmartAdapter is busy.

    FromTextAsync(text)

    Asynchronously processes the provided text and extracts structured data.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    Throws:

    • Thrown when the text is null.

    • Thrown when the SmartAdapter is busy.

    GetFieldName(component)

    Gets the name of the field to extract for the specified component.

    Parameter
    Type
    Description

    Returns: . The name of the field to extract.

    Throws:

    • Thrown when the component is null.

    GetFieldPrompt(component)

    Parameter
    Type
    Description

    Returns: .

    GetFieldRectangle(component)

    Gets the rectangle that defines the area of the field to extract for the specified component.

    Parameter
    Type
    Description

    Returns: . The rectangle that defines the area of the field to extract.

    Throws:

    • Thrown when the component is null.

    OnParseValue(e)

    Raises the event.

    Parameter
    Type
    Description

    OnUpdateField(e)

    Raises the event.

    Parameter
    Type
    Description

    RunAsyncCore(control)

    Asynchronously runs the core logic of the adapter on the specified control.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    SetFieldName(component, value)

    Sets the name of the field to extract for the specified component.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the component is null.

    SetFieldPrompt(component, value)

    Sets the prompt to instruct the AI on how to extract the value for the field for the specified component.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the component is null.

    SetFieldRectangle(component, value)

    Sets the rectangle that defines the area of the field to extract for the specified component.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the component is null.

    Events

    ParseValue

    Occurs when a value is parsed from the input data.

    UpdateField

    Occurs when a field is updated with a new value.

    Implements

    Name
    Description

    SmartTextBoxAdapter

    Wisej.AI.Adapters.SmartTextBoxAdapter

    Namespace: Wisej.AI.Adapters

    Assembly: Wisej.AI (3.5.0.0)

    • SmartAdapter

      • SmartTextBoxAdapter

    Enhances a TextBox control with several AI features, including suggestions, translation, and auto-correction.

    public class SmartTextBoxAdapter : SmartAdapter, IExtenderProvider

    This class extends the functionality of a standard TextBox by providing AI-driven features such as text suggestions, automatic translation between specified languages, and auto-correction of text input. It uses SmartPrompt sessions to interact with AI services.

    Constructors

    SmartTextBoxAdapter()

    Initializes a new instanced of .

    Properties

    AcceptIconSource

    : Gets or sets the source of the icon displayed when a suggestion is accepted. (Default: null)

    ProcessingIconSource

    : Gets or sets the source of the icon displayed during processing. (Default: "resource.wx/Wisej.AI/Icons/processing.svg")

    SuggestionDelay

    : Gets or sets the delay in milliseconds before suggestions are shown. (Default: 250)

    SuggestionStyle

    : Gets or sets the CSS style applied to suggestions. (Default: "opacity:0.4")

    Methods

    GetEnableAutoCorrection(control)

    Determines whether the auto-correction feature is enabled for the specified control.

    Parameter
    Type
    Description

    Returns: . True if auto-correction is enabled; otherwise, false.

    Throws:

    • Thrown when the control is null.

    GetEnableSuggestions(control)

    Determines whether the suggestions feature is enabled for the specified control.

    Parameter
    Type
    Description

    Returns: . True if suggestions are enabled; otherwise, false.

    Throws:

    • Thrown when the control is null.

    GetEnableTranslation(control)

    Determines whether the translation feature is enabled for the specified control.

    Parameter
    Type
    Description

    Returns: . True if translation is enabled; otherwise, false.

    Throws:

    • Thrown when the control is null.

    GetTranslateFromLanguage(control)

    Gets the source language for the translation feature associated with the specified control.

    Parameter
    Type
    Description

    Returns: . The source language as a string.

    Throws:

    • Thrown when the control is null.

    GetTranslateToLanguage(control)

    Gets the target language for the translation feature associated with the specified control.

    Parameter
    Type
    Description

    Returns: . The target language as a string.

    Throws:

    • Thrown when the control is null.

    GetUserPhrases(control)

    Gets the user-provided phrases associated with the specified control.

    Parameter
    Type
    Description

    Returns: . An array of user phrases.

    Throws:

    • Thrown when the control is null.

    GetUserRole(control)

    Gets the user role associated with the specified control.

    Parameter
    Type
    Description

    Returns: . The user role as a string.

    Throws:

    • Thrown when the control is null.

    OnControlCreated(control)

    Parameter
    Type
    Description

    OnControlDisposed(control)

    Parameter
    Type
    Description

    RunAsyncCore(control)

    Parameter
    Type
    Description

    Returns: .

    SetEnableAutoCorrection(control, value)

    Parameter
    Type
    Description

    SetEnableSuggestions(control, value)

    Parameter
    Type
    Description

    SetEnableTranslation(control, value)

    Parameter
    Type
    Description

    SetTranslateFromLanguage(control, value)

    Sets the source language for the translation feature associated with the specified control.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the control is null.

    SetTranslateToLanguage(control, value)

    Sets the target language for the translation feature associated with the specified control.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the control is null.

    SetUserPhrases(control, phrases)

    Parameter
    Type
    Description

    SetUserRole(control, value)

    Parameter
    Type
    Description

    Implements

    Name
    Description

    control

    Control

    The control to check.

    control

    Control

    The control to check.

    control

    Control

    The control to check.

    control

    Control

    The control from which to retrieve the source language.

    control

    Control

    The control from which to retrieve the target language.

    control

    Control

    The control from which to retrieve the user phrases.

    control

    Control

    The control from which to retrieve the user role.

    control

    Control

    control

    Control

    control

    Control

    control

    Control

    value

    Boolean

    control

    Control

    value

    Boolean

    control

    Control

    value

    Boolean

    control

    Control

    The control to associate with the source language.

    value

    String

    The source language as a string.

    control

    Control

    The control to associate with the target language.

    value

    String

    The target language as a string.

    control

    Control

    phrases

    String[]

    control

    Control

    value

    String

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartTextBoxAdapter
        Inherits SmartAdapter
        Implements IExtenderProvider
    SmartTextBoxAdapter
    String
    String
    Int32
    String
    Boolean
    ArgumentNullException
    Boolean
    ArgumentNullException
    Boolean
    ArgumentNullException
    String
    ArgumentNullException
    String
    ArgumentNullException
    String[]
    ArgumentNullException
    String
    ArgumentNullException
    Task<Message>
    ArgumentNullException
    ArgumentNullException
    Google Gemini
  • Llama3:8b and 70b

  • container

    IContainer

    An IContainer that represents the container of the component.

    disposing

    Boolean

    true to release both managed and unmanaged resources; false to release only unmanaged resources.

    image

    Image

    The image to be processed.

    stream

    Stream

    The stream containing the input data.

    streamType

    String

    An optional string that specifies the type of data being processed. If not provided, a default value is used.

    text

    String

    The text to be processed.

    component

    IWisejComponent

    The component for which to get the field name.

    component

    IWisejComponent

    component

    IWisejComponent

    The component for which to get the field rectangle.

    e

    ParseValueArgs

    The ParseValueArgs instance containing the event data.

    e

    UpdateFieldArgs

    The UpdateFieldArgs instance containing the event data.

    control

    Control

    The control to process.

    component

    IWisejComponent

    The component for which to set the field name.

    value

    String

    The name of the field to extract.

    component

    IWisejComponent

    The component for which to set the field prompt.

    value

    String

    The prompt to instruct the AI on how to extract the value for the field.

    component

    IWisejComponent

    The component for which to set the field rectangle.

    value

    Nullable<Rectangle>

    The rectangle that defines the area of the field to extract.

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartDataEntryAdapter
        Inherits SmartAdapter
        Implements IExtenderProvider
    Tesseract
    SmartDataEntryAdapter
    SmartDataEntryAdapter
    Boolean
    Int32
    Boolean
    SmartDataEntryAdapter
    Task
    InvalidOperationException
    Task
    ArgumentNullException
    InvalidOperationException
    Task
    ArgumentNullException
    InvalidOperationException
    Task
    ArgumentNullException
    InvalidOperationException
    String
    ArgumentNullException
    String
    Nullable<Rectangle>
    ArgumentNullException
    ParseValue
    UpdateField
    Task<Message>
    ArgumentNullException
    ArgumentNullException
    ArgumentNullException
    ParseValueEventHandler
    UpdateFieldEventHandler

    OpenAIEndpointRealtime

    Wisej.AI.Endpoints.OpenAIEndpointRealtime

    Namespace: Wisej.AI.Endpoints

    Assembly: Wisej.AI (3.5.0.0)

    • SmartEndpoint

      • SmartHttpEndpoint

    Represents a component that manages communication with OpenAI's real-time API endpoints.

    provides a convenient way to connect to and interact with OpenAI's real-time endpoints within a Wisej application. It extends , inheriting HTTP communication capabilities and adding specialized logic for real-time data exchange with OpenAI services. This component can be used to send prompts, receive streaming responses, and manage session state with OpenAI's real-time APIs.

    Constructors

    OpenAIEndpointRealtime()

    Initializes a new instance of the class with default settings.

    Properties

    Model

    : Gets or sets the model used for chat completions. (Default: "gpt-4o-realtime-preview")

    TranscriptionModel

    : Gets or sets the model used for the audio transcription. (Default: "gpt-4o-transcribe")

    URL

    : Gets or sets the base URL for the OpenAI API. (Default: "https://api.openai.com/v1")

    UseNativeTools

    : (Default: True)

    Methods

    AddOptions(message, session)

    Adds options to the message payload.

    Parameter
    Type
    Description

    Sets default values for temperature and max tokens in the message payload.

    BuildInstructions(session)

    Constructs the instruction string for the OpenAI real-time API endpoint based on the current session context.

    Parameter
    Type
    Description

    Returns: . A string containing the fully constructed instructions for the OpenAI real-time API endpoint.

    This method generates the instruction prompt by extracting the system message from the session, incorporating tool prompts, and replacing template placeholders such as {{tools}}, {{today}}, and {{language}} with their corresponding values. The resulting instruction string is then processed to replace any additional session parameters. Override this method to customize how instructions are built for the OpenAI endpoint.

    BuildToolsPayload(session)

    Builds the tools payload based on the session context.

    Parameter
    Type
    Description

    Returns: . A JSON object representing the tools payload.

    Throws:

    • Thrown when the session is null.

    CreateConfiguration(session)

    Creates the configuration payload for the OpenAI real-time API session.

    Parameter
    Type
    Description

    Returns: . A dynamic object representing the configuration payload for the session.

    This method builds a dynamic configuration object that includes options, tools, instructions, and modalities required by the OpenAI realtime API. If audio transcription is enabled, the configuration will also include the transcription model. The transcription_enabled property is removed from the final configuration payload.

    Disable()

    Disables the OpenAIEndpointRealtime component, stopping it from processing or sending further requests.

    This method deactivates the component, preventing any further communication with the OpenAI Realtime API endpoint until is called.

    Dispose(disposing)

    Releases the unmanaged resources used by the component and optionally releases the managed resources.

    Parameter
    Type
    Description

    Enable()

    Enables the OpenAIEndpointRealtime component, allowing it to process and send requests.

    This method activates the component, allowing it to resume communication with the OpenAI Realtime API endpoint after being disabled.

    GetApiURL()

    Constructs the API URL for the real time api.

    Returns: . The full API URL for the real time api..

    GetEphemeralTokenAsync(session)

    Asynchronously retrieves an ephemeral token for the specified session from the OpenAI realtime API endpoint.

    Parameter
    Type
    Description

    Returns: . A task that represents the asynchronous operation. The task result contains a dynamic object representing the ephemeral token response from the API.

    This method constructs a request to the OpenAI real-time API endpoint to obtain a temporary (ephemeral) token associated with the provided session. The token is typically used for short-lived authentication or authorization purposes during real-time communication. The method sends a POST request with the session configuration and parses the response as a dynamic object.

    Mute()

    Mutes the OpenAIEndpointRealtime component, suppressing any audio or notification output.

    Use this method to temporarily silence the component without disabling its core functionality. To restore audio or notifications, call .

    OnFunctionCall(e)

    Raises the event.

    Parameter
    Type
    Description

    This method is called to notify subscribers that a function call has been detected in the AI's response. Override this method to provide custom handling for function calls.

    OnResponseCreated(e)

    Raises the event.

    Parameter
    Type
    Description

    OnResponseDone(e)

    Raises the event.

    Parameter
    Type
    Description

    OnTranscriptionCompleted(e)

    Raises the event.

    Parameter
    Type
    Description

    ReadUsage(message, reply)

    Reads and updates the usage statistics from the OpenAI real-time API reply.

    Parameter
    Type
    Description

    SendMessages(messages)

    Sends an array of messages to the OpenAI Realtime API endpoint for processing.

    Parameter
    Type
    Description

    Use this method to transmit one or more messages to the OpenAI Realtime API endpoint. Each message should conform to the expected structure required by the endpoint.

    StartListening(session)

    Initiates listening for real-time events from the OpenAI endpoint using the specified session.

    Parameter
    Type
    Description

    This method establishes a connection to the OpenAI real-time API endpoint by obtaining an ephemeral token for the provided session and starting the listening process. It also triggers the OnStart event for the session and updates the associated component in the Wisej application. If session is null, an is thrown.

    StopListening(session)

    Stops listening for real-time events from the OpenAI endpoint for the specified session.

    Parameter
    Type
    Description

    This method terminates the connection to the OpenAI real-time API endpoint for the given session. It also triggers the OnDone event for the session to indicate that listening has stopped. If session is null, an is thrown.

    Unmute()

    Unmutes the OpenAIEndpointRealtime component, restoring audio or notification output.

    This method re-enables audio or notifications that were previously suppressed by .

    Events

    FunctionCall

    Occurs when a function call is detected in the response from the OpenAI Realtime API.

    This event is triggered when the SmartRealtimeAdapter identifies a function call in the AI's response, allowing the application to handle or execute the function as needed.

    ResponseCreated

    Occurs when a new response is created by the OpenAI real-time endpoint.

    ResponseDone

    Occurs when the response from the OpenAI real-time endpoint has been fully received and processing is complete.

    TranscriptionCompleted

    Occurs when a transcription operation has completed.

    message

    Object

    The message payload to modify.

    session

    SmartSession

    The current session context.

    session

    SmartSession

    The SmartSession instance containing the session context and parameters used to build the instruction string.

    session

    SmartSession

    The session context.

    session

    SmartSession

    The SmartSession instance containing session-specific options and settings.

    disposing

    Boolean

    true to release both managed and unmanaged resources; false to release only unmanaged resources.

    session

    SmartSession

    The SmartSession instance representing the current user session for which the ephemeral token is requested.

    e

    FunctionCallEventArgs

    A FunctionCallEventArgs instance containing the event data.

    e

    EventArgs

    An EventArgs instance containing the event data.

    e

    ResponseDoneEventArgs

    A ResponseDoneEventArgs instance containing the event data for the completed response.

    e

    TranscriptionCompletedEventArgs

    A TranscriptionCompletedEventArgs instance containing the event data for the completed transcription.

    message

    Message

    The message object to update with usage data.

    reply

    Object

    The dynamic object containing the API response, expected to include input_tokens and output_tokens properties.

    messages

    Object[]

    An array of dynamic message objects to be sent to the OpenAI endpoint.

    session

    SmartSession

    The SmartSession instance representing the current user session. This parameter cannot be null.

    session

    SmartSession

    The SmartSession instance representing the current user session. This parameter cannot be null.

    OpenAIEndpointRealtime
    Public Class OpenAIEndpointRealtime
        Inherits SmartHttpEndpoint
    OpenAIEndpointRealtime
    SmartHttpEndpoint
    OpenAIEndpoint
    String
    String
    String
    Boolean
    String
    Object[]
    ArgumentNullException
    Object
    Enable
    String
    Task<Object>
    Unmute
    FunctionCall
    ResponseCreated
    ResponseDone
    TranscriptionCompleted
    ArgumentNullException
    ArgumentNullException
    Mute
    FunctionCallEventHandler
    EventHandler
    ResponseDoneEventHandler
    TranscriptionCompletedEventHandler
    public class OpenAIEndpointRealtime : SmartHttpEndpoint

    SmartAdapter

    Wisej.AI.SmartAdapter

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    Represents an abstract base class for creating smart adapters that interact with AI endpoints.

    public class SmartAdapter : Component, IToolProvider
    Public Class SmartAdapter
        Inherits Component
        Implements IToolProvider

    Constructors

    SmartAdapter()

    Initializes a new instance of the class.

    SmartAdapter(container)

    Initializes a new instance of the class attached to an implementation to allow for disposing the SmartAdapter when the service container is disposed.

    Name
    Type
    Description

    Properties

    Agents

    : Gets the collection of agents associated with this adapter.

    AutoRun

    : Gets or sets a value indicating whether the adapter should automatically run. (Default: True)

    AutoUpdate

    : Gets or sets a value indicating whether the adapter should automatically update the browser when is done processing (requires a working WebSocket connection). (Default: True)

    Busy

    : Gets or sets a value indicating whether the adapter is busy. (Default: False)

    Controls

    : Gets the list of controls associated with this adapter.

    HasTools

    : Gets a value indicating whether the adapter has any tools.

    Hub

    : Gets or sets the associated with this adapter.

    Name

    : Gets or sets the name of the adapter.

    Parameters

    : Gets the collection of parameters associated with this adapter.

    Session

    : Gets the in use by the adapter.

    SystemPrompt

    : Gets or sets the system prompt used by the adapter. (Default: "")

    Tools

    : Gets the collection of tools associated with this adapter.

    Usage

    : Gets the usage metrics for the session.

    Methods

    ClearTools()

    Clears all tools from the adapter.

    CreateSession(prompt)

    Creates a new session with an optional prompt.

    Parameter
    Type
    Description

    Returns: . A new instance.

    CreateSession<T>(systemPrompt)

    Creates a new session of a specified type with an optional prompt.

    Parameter
    Type
    Description

    Returns: . A new session of type T .

    Dispose(disposing)

    Releases the unmanaged resources used by the and optionally releases the managed resources.

    Parameter
    Type
    Description

    GetJSON(message)

    Returns the JSON string returned in the message by stripping the enclosing markers (json and ) if present.

    Parameter
    Type
    Description

    Returns: . JSON string.

    IsAssociatedWith(control)

    Determines whether a control is associated with the adapter.

    Parameter
    Type
    Description

    Returns: . True if the control is associated; otherwise, false.

    NotifyAgentsAsync(message)

    Notifies all agents asynchronously with a message.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    OnBusyChanged(e)

    Raises the event.

    Parameter
    Type
    Description

    OnControlCreated(control)

    Called when a control is created.

    Parameter
    Type
    Description

    OnControlDisposed(control)

    Called when a control is disposed.

    Parameter
    Type
    Description

    OnDone(e)

    Raises the event.

    Parameter
    Type
    Description

    OnStart(e)

    Raises the event.

    Parameter
    Type
    Description

    RegisterControl(control)

    Registers a control with the adapter.

    Parameter
    Type
    Description

    RemoveTool(tool)

    Removes a tool from the adapter.

    Parameter
    Type
    Description

    Returns: .

    RemoveTools(target)

    Removes the tools from the specified object.

    Parameter
    Type
    Description

    Returns: . The current instance.

    RunAsync(control)

    Runs the adapter asynchronously.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation.

    UnregisterControl(control)

    Unregisters a control from the adapter.

    Parameter
    Type
    Description

    UseTool(tool)

    Adds a tool to the adapter.

    Parameter
    Type
    Description

    Returns: .

    UseTools(target)

    Adds multiple tools to the adapter from a target object.

    Parameter
    Type
    Description

    Returns: .

    Events

    BusyChanged

    Occurs when the busy state of the adapter changes.

    Done

    Occurs when the adapter has completed processing.

    Start

    Occurs when the adapter starts processing.

    Inherited By

    Name
    Description

    Implements

    Name
    Description

    Adds semantic filtering to the auto-complete functionality.

    Turns the control into a AI-powered assistant. It can control and navigate an application, click menu items, navigation bar items, buttons, etc. It can also invoke methods in your applications as needed (see ).

    Enhances all the controls in the associated container with the AI-powered capability to extract structured data from unstructured text.

    Represents a document adapter that can perform AI tasks using a document as a data source and interact with the user through a ChatBox control.

    Converts unstructured text into a structured .NET object.

    Represents an adapter for a PictureBox that generates images based on a description using the OpenAI DALL-E endpoint.

    Represents an adapter that generates a data set from a database schema and a user-provided description.

    Represents a smart adapter that provides real-time data processing capabilities for use with the endpoint.

    Enhances the ChatBox control to allow seamless PDF report queries using an AI provider.

    Enhances a TextBox control with several AI features, including suggestions, translation, and auto-correction.

    container

    IContainer

    An IContainer that represents the container of the component.

    prompt

    SmartPrompt

    The prompt to use for the session.

    T

    The type of session to create.

    systemPrompt

    SmartPrompt

    The system prompt to use for the session.

    disposing

    Boolean

    True to release both managed and unmanaged resources; false to release only unmanaged resources.

    message

    Message

    Message with the response text that may be a JSON string.

    control

    Control

    The control to check.

    message

    Message

    The message to notify agents with.

    e

    EventArgs

    An EventArgs that contains the event data.

    control

    Control

    The control that was created.

    control

    Control

    The control that was disposed.

    e

    EventArgs

    An EventArgs that contains the event data.

    e

    EventArgs

    An EventArgs that contains the event data.

    control

    Control

    The control to register.

    tool

    Delegate

    The tool to remove.

    target

    Object

    The target object containing tools.

    control

    Control

    The control to run the adapter on.

    control

    Control

    The control to unregister.

    tool

    Delegate

    The tool to add.

    target

    Object

    The target object containing tools.

    SmartAudioTTSAdapter

    Converts the Text of the associated Audio control into lifelike speech.

    SmartAudioWhisperAdapter

    Transcribes the audio file of the of the associated Audio control to its Text property in the original language of the audio. speech-to-text

    SmartCalendarAdapter

    Represents a smart calendar adapter that extends the functionality of a SmartAdapter.

    SmartChartAdapter

    Represents an adapter that enhances a chart control with AI features.

    SmartChartJS3Adapter

    Represents an adapter that enhances a ChartJS control with several AI features.

    SmartChatBoxAdapter

    Turns the ChatBox control into a AI-powered bot. It can answer any question (depending on the AI model being used) and can invoke methods in your applications as needed (see SmartTool).

    IToolProvider

    Represents a provider that supplies tools.

    SmartAdapter
    SmartAdapter
    IContainer
    AgentCollection
    Boolean
    Boolean
    Boolean
    IList<Control>
    Boolean
    SmartHub
    SmartHub
    String
    ParameterCollection
    SmartSession
    SmartSession
    String
    ToolCollection
    Metrics
    SmartSession
    SmartSession
    T
    SmartAdapter
    String
    Boolean
    Task
    BusyChanged
    Done
    Start
    SmartAdapter
    SmartAdapter
    SmartAdapter
    Task<Message>
    SmartAdapter
    SmartAdapter
    EventHandler
    EventHandler
    EventHandler

    SmartEndpoint

    Wisej.AI.SmartEndpoint

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    Represents an abstract base class for a smart endpoint component that interacts with AI models.

    This class provides properties and methods to configure and interact with AI models, including handling messages, building payloads, and managing tool invocations.

    SmartSession

    Wisej.AI.SmartSession

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    Represents a session that manages interactions with a smart hub and endpoint, handling prompts, messages, and tools within the session context.

    SmartComboBoxAdapter
    ComboBox
    SmartCopilotAdapter
    ChatBox
    SmartTool
    SmartDataEntryAdapter
    SmartDocumentAdapter
    SmartFullCalendarAdapter
    SmartObjectAdapter
    SmartPictureBoxAdapter
    SmartQueryAdapter
    SmartRealtimeAdapter
    OpenAIEndpointRealtime
    SmartReportAdapter
    SmartTextBoxAdapter
    Constructors

    SmartEndpoint()

    Initializes a new instance of the SmartEndpoint class.

    Properties

    ContextWindow

    Int32: Gets or sets the size of the context window in tokens. (Default: 32000)

    EmbeddingModel

    String: Gets or sets the embedding model used by the endpoint. (Default: null)

    MaxOutputTokens

    Int32: Gets or sets the maximum number of output tokens. (Default: 4096)

    Model

    String: Gets or sets the model used by the endpoint. (Default: null)

    ModelOptions

    Object: Gets the model options for the endpoint.

    Name

    String: Gets or sets the name of the endpoint.

    SystemPrompt

    String: Gets or sets the system prompt for the endpoint.

    Warning, setting this property entirely overrides the internal system prompt.

    ToolsPrompt

    String: Gets or sets the tools prompt for the endpoint.

    Warning, setting this property entirely overrides the internal tools prompt.

    Usage

    Metrics: Gets the usage metrics for the endpoint.

    UseNativeTools

    Boolean: Gets or sets a value indicating that the endpoint should use the native tools payload when adding tools to the request. (Default: False)

    Methods

    AddMessages(payload, session, messages)

    Adds messages to the payload object.

    Parameter
    Type
    Description

    payload

    The payload object to update.

    session

    The session context.

    messages

    The list of messages to add.

    Throws:

    • ArgumentNullException Thrown when the session, payload, or messages are null.

    AddOptions(message, session)

    Adds model options to the message object.

    Parameter
    Type
    Description

    message

    The message object to update.

    session

    The session context.

    Throws:

    • ArgumentNullException Thrown when the message is null.

    AskAsync(session, messages)

    Asynchronously sends a message to the AI model and returns the response.

    Parameter
    Type
    Description

    session

    The session context.

    messages

    The list of messages to send.

    Returns: Task<Message>. A task representing the asynchronous operation, with a Message as the result.

    This method must be implemented by derived classes to handle the specific logic for sending messages to the AI model.

    The implementation of this method should call session.Usage.Add(assistantMessage.Usage) to keep track if the input and output tokens utilized at the session level.

    AskEmbeddingsAsync(inputs)

    Asynchronously requests embeddings for the given inputs.

    Parameter
    Type
    Description

    inputs

    The array of input strings.

    Returns: Task<Embedding>. A task representing the asynchronous operation, with an Embedding as the result.

    Throws:

    • NotImplementedException Thrown when the method is not implemented.

    BuildAssistantMessage(response)

    Builds an assistant Message from the given response.

    Parameter
    Type
    Description

    response

    The response to build from.

    Returns: Message. A Message representing the assistant's response.

    Throws:

    • ArgumentNullException Thrown when the response is null.

    BuildEmbeddingsPayload(inputs)

    Builds a payload for requesting embeddings.

    Parameter
    Type
    Description

    inputs

    The array of input strings.

    Returns: Object. An object representing the embeddings payload.

    Throws:

    • NotImplementedException Thrown when the method is not implemented.

    BuildMessage(message)

    Builds a message object from the given Message.

    Parameter
    Type
    Description

    message

    The message to build from.

    Returns: Object. An object representing the built message.

    Throws:

    • ArgumentNullException Thrown when the message is null.

    BuildNativeToolsPrompt(session)

    Builds the tools namespace prompt based on the session context.

    Parameter
    Type
    Description

    session

    The session context.

    Returns: String. A string representing the tools prompt.

    Throws:

    • ArgumentNullException Thrown when the session is null.

    BuildParameters(parameters)

    Builds a string representation of tool parameters.

    Parameter
    Type
    Description

    parameters

    The array of parameters to build from.

    Returns: String. A string representing the tool parameters.

    BuildPayload(session, messages)

    Builds a payload object for the given Session and Message.

    Parameter
    Type
    Description

    session

    The session context.

    messages

    The list of messages to include in the payload.

    Returns: Object. An object representing the built payload.

    Throws:

    • ArgumentNullException Thrown when the session or messages are null.

    BuildToolResults(toolResults)

    Builds the messages containing tool results.

    Parameter
    Type
    Description

    toolResults

    Returns: Message[]. An array of Message representing the tool results.

    BuildToolResultsMessage(toolResults)

    Builds a message containing tool results.

    Parameter
    Type
    Description

    toolResults

    The array of tools with results.

    Returns: Message. A Message representing the tool results.

    BuildToolsPayload(session)

    Builds the tools payload based on the session context.

    Parameter
    Type
    Description

    session

    The session context.

    Returns: Object[]. A JSON object representing the tools payload.

    Throws:

    • ArgumentNullException Thrown when the session is null.

    BuildToolsPrompt(session)

    Builds the tools prompt based on the session context.

    Parameter
    Type
    Description

    session

    The session context.

    Returns: String. A string representing the tools prompt.

    Throws:

    • ArgumentNullException Thrown when the session is null.

    GetCurrentLanguage(session)

    Gets the current language based on the session context.

    Parameter
    Type
    Description

    session

    The session context.

    Returns: String. A string representing the current language.

    GetTodayDescription()

    Gets a description of the current date.

    Returns: String. A string representing the current date.

    GetToolsToInvoke(session, message)

    Gets the tools to invoke based on the session and message context.

    Parameter
    Type
    Description

    session

    The session context.

    message

    The message context.

    Returns: ToolContext[]. An array of ToolContext representing the tools to invoke.

    Throws:

    • ArgumentNullException Thrown when the session or message is null.

    ReadAssistantMessage(response, message)

    Reads the assistant message from the response and updates the message object.

    Parameter
    Type
    Description

    response

    The response containing the assistant message.

    message

    The message object to update.

    The implementation of this method should call ReadUsage to keep track if the input and output tokens utilized.

    ReadEmbeddingsResponse(response)

    Reads the embeddings response and returns the embeddings data.

    Parameter
    Type
    Description

    response

    The response containing embeddings data.

    Returns: Single[][]. A jagged array of floats representing the embeddings.

    Throws:

    • NotImplementedException Thrown when the method is not implemented.

    ReadUsage(message, reply)

    Reads the usage information from reply.

    Parameter
    Type
    Description

    message

    The message containing usage information.

    reply

    The reply object to update with usage information.

    Inherited By

    Name
    Description

    Represents an endpoint for connecting to Amazon Bedrock services.

    Represents an endpoint for connecting to Anthropic services.

    Represents an endpoint for connecting to Azure AI services, specifically designed to interact with OpenAI models.

    Represents a connection to Cerebras endpoints, inheriting from OpenAIEndpoint.

    Represents a connection to DeepSeek endpoints, inheriting from OpenAIEndpoint.

    Represents a connection to Google AI endpoints for generating content and embeddings.

    Public Class SmartEndpoint
        Inherits Component
    public class SmartEndpoint : Component
    Public Class SmartSession
        Inherits SmartObject

    The SmartSession class is responsible for managing the lifecycle of a session, including initialization, message handling, and tool usage. It supports asynchronous operations for asking questions and processing responses, and it can handle context overflow through truncation or summarization strategies.

    Constructors

    SmartSession(hub, systemPrompt)

    Initializes a new instance of the SmartSession class with the specified hub and optional system prompt.

    Name
    Type
    Description

    hub

    The smart hub associated with the session.

    systemPrompt

    The optional system prompt for the session. Default is null.

    Throws:

    • ArgumentNullException Thrown when the hub is null.

    SmartSession(endpoint, systemPrompt)

    Initializes a new instance of the SmartSession class with the specified endpoint and optional system prompt.

    Name
    Type
    Description

    endpoint

    The smart endpoint associated with the session.

    systemPrompt

    The optional system prompt for the session. Default is null.

    Throws:

    • ArgumentNullException Thrown when the endpoint is null.

    Properties

    Endpoint

    SmartEndpoint: Gets the smart endpoint associated with the session.

    HasModelOptions

    Boolean: Gets a value indicating whether the session has model options.

    Hub

    SmartHub: Gets the smart hub associated with the session.

    IsDisposed

    Boolean: Gets a value indicating whether the session has been disposed.

    Messages

    MessageCollection: Gets the collection of messages in the session.

    ModelOptions

    Object: Gets or sets the model options for the session.

    Response

    Message: Gets the last response message from the assistant.

    SystemPrompt

    SmartPrompt: Gets the system prompt for the session.

    Methods

    AskAsync(question, image)

    Asynchronously asks a question and returns the response message.

    Parameter
    Type
    Description

    question

    The question to ask.

    image

    An optional image associated with the question. Default is null.

    Returns: Task<Message>. A task representing the asynchronous operation, with a Message as the result.

    Throws:

    • ObjectDisposedException Thrown when the session is disposed.

    • ArgumentNullException Thrown when the question is null.

    AskAsync(message)

    Asynchronously asks a question using a message and returns the response message.

    Parameter
    Type
    Description

    message

    The message containing the question.

    Returns: Task<Message>. A task representing the asynchronous operation, with a Message as the result.

    Throws:

    • ObjectDisposedException Thrown when the session is disposed.

    • ArgumentNullException Thrown when the message is null.

    AskAsyncCore(question)

    Asynchronously sends a question to the AI and processes the response.

    Parameter
    Type
    Description

    question

    The message containing the question to be sent to the AI.

    Returns: Task<Message>. A task representing the asynchronous operation, with a Message as the result containing the AI's response.

    This method handles the communication with the AI, including managing the session's message context, handling tool calls, and processing AI responses. It ensures that the session is not disposed and that the question is not null before proceeding. The method also manages the context window size and handles exceptions such as token limit exceedance.

    ConvertParameter(value)

    Raises the ConvertParameter event.

    Parameter
    Type
    Description

    value

    Returns: String.

    Dispose()

    Releases all resources used by the SmartSession.

    GetParameterValue(parameter)

    Gets the value of a parameter.

    Parameter
    Type
    Description

    parameter

    The parameter to get the value for.

    Returns: String. The value of the parameter as a string.

    IsTerminated()

    Returns: Boolean.

    PrepareSessionMessages(messages)

    Prepares session messages by replacing parameters in the system and user messages.

    Parameter
    Type
    Description

    messages

    The collection of messages to prepare.

    RemoveTool(tool)

    Removes a tool from the smart session.

    Parameter
    Type
    Description

    tool

    The tool to remove.

    Returns: SmartSession. The current SmartSession instance.

    Throws:

    • ArgumentNullException Thrown when the tool is null.

    ReplaceParameters(prompt)

    Replaces parameters in the given prompt with their values.

    Parameter
    Type
    Description

    prompt

    The prompt containing parameters to replace.

    Returns: String. The prompt with parameters replaced by their values.

    TrimMessagesAsync(messages)

    Trims messages in the session based on the specified truncation strategy.

    Parameter
    Type
    Description

    messages

    The collection of messages to trim.

    Returns: Task.

    UseTool(tool)

    Registers a tool using a delegate.

    Parameter
    Type
    Description

    tool

    The delegate representing the tool to register.

    Returns: SmartSession. The current SmartSession instance.

    Throws:

    • ArgumentNullException Thrown when the tool is null.

    UseTools(target)

    Registers the tools declared on the target.

    Parameter
    Type
    Description

    target

    The target object containing tools to register.

    Returns: SmartSession. The current SmartSession instance.

    Inherited By

    Name
    Description

    SmartObject
    SmartSession
    public class SmartSession : SmartObject

    MarkupExtensions

    Wisej.AI.MarkupExtensions

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    Provides extension methods for configuring and handling events on SmartEndpoint, SmartHttpEndpoint, SmartHub, and SmartSession objects.

    public class MarkupExtensions
    Public Class MarkupExtensions

    The MarkupExtensions class offers a fluent API for setting properties and subscribing to events on various smart endpoint and session types. These extension methods enable concise and readable configuration of endpoints and event handlers.

    Methods

    ApiKey<T>(endpoint, value)

    Sets the API key for the specified HTTP endpoint.

    Parameter
    Type
    Description

    Returns: . The configured HTTP endpoint instance.

    Authentication<T>(endpoint, value)

    Sets the authentication string for the specified HTTP endpoint.

    Parameter
    Type
    Description

    Returns: . The configured HTTP endpoint instance.

    ContextWindow<T>(endpoint, value)

    Sets the context window size for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    EmbeddingModel<T>(endpoint, value)

    Sets the embedding model for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    Headers<T>(endpoint, value)

    Sets the HTTP headers for the specified HTTP endpoint.

    Parameter
    Type
    Description

    Returns: . The configured HTTP endpoint instance.

    MaxOutputTokens<T>(endpoint, value)

    Sets the maximum number of output tokens for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    Model<T>(endpoint, value)

    Sets the model name for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    Name<T>(endpoint, value)

    Sets the name for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    OnAfterInvokeTool<T>(object, action)

    Subscribes to the AfterInvokeTool event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnAfterResponseReceived<T>(object, action)

    Subscribes to the AfterResponseReceived event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnBeforeInvokeTool<T>(object, action)

    Subscribes to the BeforeInvokeTool event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnBeforeSendRequest<T>(object, action)

    Subscribes to the BeforeSendRequest event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnConvertParameter<T>(object, action)

    Subscribes to the ConvertParameter event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnDone<T>(object, action)

    Subscribes to the Done event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnError<T>(object, action)

    Subscribes to the Error event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnPrepareMessages<T>(object, action)

    Subscribes to the PrepareMessage event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    OnStart<T>(object, action)

    Subscribes to the Start event on the specified object.

    Parameter
    Type
    Description

    Returns: . The configured instance.

    RetryDelay<T>(endpoint, value)

    Sets the retry delay (in milliseconds) for the specified HTTP endpoint.

    Parameter
    Type
    Description

    Returns: . The configured HTTP endpoint instance.

    SystemPrompt<T>(endpoint, value)

    Sets the system prompt for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    Text<T>(prompt, value)

    Sets the Text for the specified SmartPrompt.

    Parameter
    Type
    Description

    Returns: . The configured SmartPrompt instance.

    URL<T>(endpoint, value)

    Sets the URL for the specified HTTP endpoint.

    Parameter
    Type
    Description

    Returns: . The configured HTTP endpoint instance.

    UseNativeTools<T>(endpoint, value)

    Specifies whether to use native tools for the specified endpoint.

    Parameter
    Type
    Description

    Returns: . The configured endpoint instance.

    SmartHttpEndpoint

    Wisej.AI.Endpoints.SmartHttpEndpoint

    Namespace: Wisej.AI.Endpoints

    Assembly: Wisej.AI (3.5.0.0)

    • SmartEndpoint

      • SmartHttpEndpoint

    Represents an abstract base class for a smart HTTP endpoint, providing common functionality for HTTP-based communication.

    public class SmartHttpEndpoint : SmartEndpoint

    This class is designed to facilitate communication with HTTP endpoints by managing authentication, headers, and retry logic. It provides methods for sending requests and handling responses, including error detection and retry mechanisms.

    Constructors

    SmartHttpEndpoint()

    Initializes a new instance of the class.

    Properties

    ApiKey

    : Gets or sets the API key used for authentication. (Default: null)

    Authentication

    : Gets or sets the authentication scheme used for requests. (Default: "Bearer")

    Headers

    : Gets or sets the collection of additional headers to be included in requests.

    MaxRetries

    : Gets or sets the maximum number of retry attempts for failed requests. (Default: 10)

    RetryDelay

    : Gets or sets the delay between retry attempts in milliseconds. (Default: 10000)

    URL

    : Gets or sets the base URL of the endpoint. (Default: null)

    The URL should not end with a trailing slash. If a trailing slash is present, it will be removed.

    Methods

    AskAsync(session, messages)

    Asynchronously sends a request to the endpoint and returns the response message.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with a as the result.

    The implementation of this method should call session.Usage.Add(assistantMessage.Usage) to keep track of the input and output tokens utilized at the session level.

    **Throws:** * [ArgumentNullException](https://docs.microsoft.com/dotnet/api/system.argumentnullexception) Thrown when *session* or *messages* is null.

    AskEmbeddingsAsync(inputs)

    Asynchronously requests embeddings for the specified inputs.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an as the result.

    This method sends the inputs to the embeddings endpoint and returns the resulting embeddings.Throws:

    • Thrown when inputs is null.

    • Thrown when the embedding model is not defined.

    BuildPayload(session, messages)

    Builds the payload for the request.

    Parameter
    Type
    Description

    Returns: . The constructed payload object.

    Throws:

    • Thrown when session or messages is null.

    CreateContent(data)

    Creates the HTTP content from the given data.

    Parameter
    Type
    Description

    Returns: . The created .

    DetectContextLimitExceeded(response)

    Detects if the context limit has been exceeded in the response.

    Parameter
    Type
    Description

    Returns: . true if the context limit is exceeded; otherwise, false.

    DetectRateLimitExceeded(response)

    Detects if the rate limit has been exceeded in the response.

    Parameter
    Type
    Description

    Returns: . true if the rate limit is exceeded; otherwise, false.

    GetApiKey()

    Gets the API key for the endpoint.

    Returns: . The API key as a string.

    GetApiURL()

    Gets the API URL for the endpoint.

    Returns: . The API URL as a string.

    GetEmbeddingsURL()

    Gets the URL for embeddings.

    Returns: . The embeddings URL as a string.

    Throws:

    • Thrown when the method is not implemented.

    PostAsync(url, data)

    Asynchronously sends a POST request to the specified URL with the given data.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with a as the result.

    This method handles retries and error detection, including token and rate limit exceeded exceptions.Throws:

    • Thrown when the token limit is exceeded.

    • Thrown when the rate limit is exceeded.

    • Thrown when the response status code is not OK.

    ReadAssistantMessage(response, message)

    Reads the assistant's message from the API response.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the response or message is null.

    ReadUsage(message, reply)

    Reads the usage statistics from the API response.

    Parameter
    Type
    Description

    Inherited By

    Name
    Description
    
    // Example usage:
    SmartEndpoint endpoint = new CustomSmartEndpoint();
    var response = await endpoint.AskAsync(session, messages);
    
    
    // Example usage:
    var response = await endpoint.AskAsync(session, messages);
    
    
    var response = await AskAsyncCore(new Message { Text = "What is the weather today?" });
    Console.WriteLine(response.Text);
    

    T

    A type derived from SmartHttpEndpoint.

    endpoint

    T

    The HTTP endpoint to configure.

    value

    String

    The API key.

    T

    A type derived from SmartHttpEndpoint.

    endpoint

    T

    The HTTP endpoint to configure.

    value

    String

    The authentication string.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    Int32

    The context window size.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    String

    The embedding model name.

    T

    A type derived from SmartHttpEndpoint.

    endpoint

    T

    The HTTP endpoint to configure.

    value

    NameValueCollection

    A NameValueCollection containing the headers.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    Int32

    The maximum number of output tokens.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    String

    The model name to assign.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    String

    The name to assign.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<InvokeToolEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<MessagesEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<InvokeToolEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<MessagesEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<ConvertParameterEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<ErrorEventArgs>

    The action to invoke when the event is raised.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action<MessagesEventArgs>

    The action to invoke when the event is raised, receiving the event arguments.

    T

    A type derived from SmartObject.

    object

    T

    The SmartObject to subscribe to.

    action

    Action

    The action to invoke when the event is raised.

    T

    A type derived from SmartHttpEndpoint.

    endpoint

    T

    The HTTP endpoint to configure.

    value

    Int32

    The retry delay in milliseconds.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    String

    The system prompt text.

    T

    A type derived from SmartPrompt.

    prompt

    T

    The SmartPrompt to configure.

    value

    String

    The text string.

    T

    A type derived from SmartHttpEndpoint.

    endpoint

    T

    The HTTP endpoint to configure.

    value

    String

    The URL to assign.

    T

    A type derived from SmartEndpoint.

    endpoint

    T

    The endpoint to configure.

    value

    Boolean

    True to use native tools; otherwise, false.

    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T
    T

    GroqCloudEndpoint

    https://console.groq.com/docs/openai

    GroqCloudEndpointWhisper

    Represents a connection to GroqCloud speech endpoints for audio transcription.

    HuggingFaceEndpoint

    Represents a connection to HuggingFace serverless endpoints for model inference and embeddings.

    HuggingFaceJavaScriptEndpoint

    Represents an endpoint that uses the transformers.js module in the user's browser to provide AI services to Wisej.AI components.

    LocalAIEndpoint

    Represents a connection to LocalAI endpoints, providing access to various AI models and services.

    LocalAIEndpointImageGen

    Represents an endpoint for connecting to LocalAI Image Generation services.

    LocalAIEndpointTTS

    Represents an endpoint for connecting to LocalAI's speech services.

    LocalAIEndpointWhisper

    Represents an endpoint for connecting to LocalAI's Whisper model for speech-to-text transcriptions.

    NvidiaAIEndpoint

    Represents a connection to NVIDIA AI endpoints, providing access to various AI models and services.

    OllamaEndpoint

    Represents an endpoint that connects to Ollama services, providing functionalities for chat and embeddings.

    OpenAIEndpoint

    Represents an endpoint for connecting to OpenAI services.

    OpenAIEndpointDallE

    Represents an endpoint for connecting to OpenAI DallE services.

    OpenAIEndpointRealtime

    Represents a component that manages communication with OpenAI's real-time API endpoints.

    OpenAIEndpointTTS

    Represents an endpoint for connecting to OpenAI's speech services.

    OpenAIEndpointWhisper

    Represents an endpoint for connecting to OpenAI's Whisper model for speech-to-text transcriptions.

    SambaNovaEndpoint

    Represents a connection to SambaNova endpoints, inheriting from OpenAIEndpoint.

    SmartHttpEndpoint

    Represents an abstract base class for a smart HTTP endpoint, providing common functionality for HTTP-based communication.

    TogetherAIEndpoint

    Represents a connection to TogetherAI endpoints, providing access to various AI models and services.

    XAIEndpoint

    Represents a connection to X.AI endpoints, extending the functionality of OpenAIEndpoint.

    Object
    SmartSession
    IList<Message>
    Object
    SmartSession
    SmartSession
    IList<Message>
    String[]
    Response
    String[]
    Message
    SmartSession
    Parameter[]
    SmartSession
    IList<Message>
    ToolContext[]
    ToolContext[]
    SmartSession
    SmartSession
    SmartSession
    SmartSession
    Message
    Response
    Message
    Response
    Message
    Object
    AmazonBedrockEndpoint
    AnthropicEndpoint
    AzureAIEndpoint
    CerebrasEndpoint
    DeepSeekEndpoint
    GoogleAIEndpoint
    SmartHub
    SmartPrompt
    SmartEndpoint
    SmartPrompt
    String
    Image
    Message
    Message
    Object
    Parameter
    MessageCollection
    Delegate
    String
    MessageCollection
    Delegate
    Object
    SmartRealtimeSession

    https://console.groq.com/docs/openai

    Represents a connection to GroqCloud speech endpoints for audio transcription.

    Represents a connection to HuggingFace serverless endpoints for model inference and embeddings.

    Represents a connection to LocalAI endpoints, providing access to various AI models and services.

    Represents an endpoint for connecting to LocalAI Image Generation services.

    Represents an endpoint for connecting to LocalAI's speech services.

    Represents an endpoint for connecting to LocalAI's Whisper model for speech-to-text transcriptions.

    Represents a connection to NVIDIA AI endpoints, providing access to various AI models and services.

    Represents an endpoint that connects to Ollama services, providing functionalities for chat and embeddings.

    Represents an endpoint for connecting to OpenAI services.

    Represents an endpoint for connecting to OpenAI DallE services.

    Represents a component that manages communication with OpenAI's real-time API endpoints.

    Represents an endpoint for connecting to OpenAI's speech services.

    Represents an endpoint for connecting to OpenAI's Whisper model for speech-to-text transcriptions.

    Represents a connection to SambaNova endpoints, inheriting from OpenAIEndpoint.

    Represents a connection to TogetherAI endpoints, providing access to various AI models and services.

    Represents a connection to X.AI endpoints, extending the functionality of OpenAIEndpoint.

    session

    SmartSession

    The session managing the AI interaction.

    messages

    IList<Message>

    The list of messages to be sent.

    inputs

    String[]

    The array of input strings for which embeddings are requested.

    session

    SmartSession

    The session managing the AI interaction.

    messages

    IList<Message>

    The list of messages to be included in the payload.

    data

    Object

    The data to be serialized into the content.

    response

    HttpResponseMessage

    The HTTP response message.

    response

    HttpResponseMessage

    The HTTP response message.

    url

    String

    The URL to send the request to.

    data

    Object

    The data to be sent in the request body.

    response

    Response

    The response received from the API.

    message

    Message

    The message object to populate with the response content.

    message

    Message

    The message object to update with usage data.

    reply

    Object

    The dynamic object containing the API response data.

    AmazonBedrockEndpoint

    Represents an endpoint for connecting to Amazon Bedrock services.

    AnthropicEndpoint

    Represents an endpoint for connecting to Anthropic services.

    AzureAIEndpoint

    Represents an endpoint for connecting to Azure AI services, specifically designed to interact with OpenAI models.

    CerebrasEndpoint

    Represents a connection to Cerebras endpoints, inheriting from OpenAIEndpoint.

    DeepSeekEndpoint

    Represents a connection to DeepSeek endpoints, inheriting from OpenAIEndpoint.

    GoogleAIEndpoint

    Represents a connection to Google AI endpoints for generating content and embeddings.

    Public Class SmartHttpEndpoint
        Inherits SmartEndpoint
    SmartHttpEndpoint
    String
    String
    NameValueCollection
    Int32
    Int32
    String
    Task<Message>
    Message
    Task<Embedding>
    Embedding
    ArgumentNullException
    NotSupportedException
    Object
    ArgumentNullException
    HttpContent
    HttpContent
    Boolean
    Boolean
    String
    String
    String
    NotImplementedException
    Task<Response>
    Response
    TokenLimitExceededException
    RateLimitExceededException
    Exception
    ArgumentNullException

    SmartHub

    Wisej.AI.SmartHub

    Namespace: Wisej.AI

    Assembly: Wisej.AI (3.5.0.0)

    • SmartObject

      • SmartHub

    Represents a SmartHub component that provides AI capabilities to controls within a container.

    public class SmartHub : SmartObject, IExtenderProvider, IToolProvider

    The SmartHub class is an extender provider that allows controls to be extended with AI functionalities. It manages various services and tools to facilitate AI operations, such as embedding generation, document conversion, and similarity queries.

    Constructors

    SmartHub()

    Initializes a new instance of the class.

    SmartHub(containerControl)

    Initializes a new instance of the class with a specified container control.

    Name
    Type
    Description

    Throws:

    • Thrown when the containerControl is null.

    SmartHub(container)

    Initializes a new instance of the class attached to an implementation.

    Name
    Type
    Description

    Properties

    BindingContext

    : Gets the binding context for the SmartHub.

    ContainerControl

    : Returns or sets the container that provides the for binding to the interface implemented by a . (Default: null)

    Culture

    : Gets or sets the culture information for the SmartHub. (Default: null)

    DataSource

    : Gets or sets a data source that can be used to resolve prompt parameters. (Default: null)

    Endpoint

    : Gets or sets the default endpoint. (Default: null)

    IsDisposed

    : Gets a value indicating whether the SmartHub is disposed.

    Methods

    AskAsync(question, image, systemPrompt)

    Asynchronously asks a question and returns a response message.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with a as the result.

    Throws:

    • Thrown when the question is null.

    Dispose(disposing)

    Releases the unmanaged resources used by the and optionally releases the managed resources.

    Parameter
    Type
    Description

    EmbedAsync(text)

    Asynchronously generates an embedding for a specified text.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an as the result.

    EmbedAsync(chunks)

    Asynchronously generates an embedding for a specified array of text chunks.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an as the result.

    Throws:

    • Thrown when the chunks array is null.

    GetAdapter(control)

    Gets the adapter associated with a specified control.

    Parameter
    Type
    Description

    Returns: . The associated with the control, or null if none exists.

    Throws:

    • Thrown when the control is null.

    GetAdapter<T>(control)

    Gets the adapter of a specified type associated with a specified control.

    Parameter
    Type
    Description

    Returns: . The adapter of type T associated with the control, or null if none exists.

    Throws:

    • Thrown when the control is null.

    GetAI(control)

    Gets the AI properties for a specified control.

    Parameter
    Type
    Description

    Returns: . The associated with the control.

    GetParameterValue(parameter)

    Gets the value of a specified parameter.

    Parameter
    Type
    Description

    Returns: . The value of the parameter as a string.

    Throws:

    • Thrown when the parameter is null.

    IngestDocumentAsync(filePath, documentName, collectionName, metadata, overwrite)

    Asynchronously ingests a document from a specified file path.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an as the result.

    This method utilizes several services to perform its operations: , and , and , and .Throws:

    • Thrown when the filePath or documentName is null.

    IngestDocumentAsync(stream, documentName, collectionName, overwrite, metadata)

    Asynchronously ingests a document from a specified stream.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an as the result.

    This method utilizes several services to perform its operations: , and , and , and .Throws:

    • Thrown when the stream or documentName is null.

    RemoveAdapter(adapter)

    Removes a specified adapter from the SmartHub.

    Parameter
    Type
    Description

    Throws:

    • Thrown when the adapter is null.

    RemoveTool(tool)

    Removes a tool from the SmartHub.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Throws:

    • Thrown when the tool is null.

    SimilarityQueryAsync(query, chunks, topN, minSimilarity, computeSimilarity)

    Asynchronously performs a similarity query on a specified query and text chunks.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an array of strings as the result.

    Throws:

    • Thrown when the query or chunks are null.

    SimilarityQueryAsync(query, chunks, vectors, topN, minSimilarity, computeSimilarity)

    Asynchronously performs a similarity query on a specified query, text chunks, and vectors.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an array of strings as the result.

    Throws:

    • Thrown when the query, chunks, or vectors are null.

    SimilarityScoreAsync(query, chunks, computeSimilarity)

    Asynchronously calculates similarity scores for a specified query and text chunks.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an array of floats as the result.

    Throws:

    • Thrown when the query or chunks are null.

    SimilarityScoreAsync(query, chunks, embeddings, computeSimilarity)

    Asynchronously calculates similarity scores for a specified query, text chunks, and embeddings.

    Parameter
    Type
    Description

    Returns: . A task representing the asynchronous operation, with an array of floats as the result.

    Throws:

    • Thrown when the query, chunks, or embeddings are null.

    UseTool(tool)

    Adds a tool to the SmartHub.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Throws:

    • Thrown when the tool is null.

    UseTools(target)

    Uses tools from a specified target.

    Parameter
    Type
    Description

    Returns: . The current instance.

    Implements

    Name
    Description
    GroqCloudEndpoint
    GroqCloudEndpointWhisper
    HuggingFaceEndpoint
    LocalAIEndpoint
    LocalAIEndpointImageGen
    LocalAIEndpointTTS
    LocalAIEndpointWhisper
    NvidiaAIEndpoint
    OllamaEndpoint
    OpenAIEndpoint
    OpenAIEndpointDallE
    OpenAIEndpointRealtime
    OpenAIEndpointTTS
    OpenAIEndpointWhisper
    SambaNovaEndpoint
    TogetherAIEndpoint
    XAIEndpoint

    overwrite

    Whether to overwrite an existing document. Default is false.

    metadata

    The metadata for the document. Default is null.

    computeSimilarity

    The function to compute similarity. Default is null.

    minSimilarity

    The minimum similarity threshold.

    computeSimilarity

    The function to compute similarity. Default is null.

    containerControl

    ContainerControl

    The container control to which the SmartHub is attached.

    container

    IContainer

    An IContainer that represents the container of the SmartHub extender.

    question

    String

    The question to ask.

    image

    Image

    An optional image to include in the question. Default is null.

    systemPrompt

    String

    Option system prompt.

    disposing

    Boolean

    true to release both managed and unmanaged resources; false to release only unmanaged resources.

    text

    String

    The text to embed.

    chunks

    String[]

    The text chunks to embed.

    control

    Control

    The control for which to get the adapter.

    T

    The type of the adapter.

    control

    Control

    The control for which to get the adapter.

    control

    Control

    The control for which to get the AI properties.

    parameter

    Parameter

    The parameter for which to get the value.

    filePath

    String

    The file path of the document to ingest.

    documentName

    String

    The name of the document.

    collectionName

    String

    The name of the collection. Default is null.

    metadata

    Metadata

    The metadata for the document. Default is null.

    stream

    Stream

    The stream of the document to ingest.

    documentName

    String

    The name of the document.

    collectionName

    String

    The name of the collection. Default is null.

    overwrite

    Boolean

    Whether to overwrite an existing document. Default is false.

    adapter

    SmartAdapter

    The adapter to remove.

    tool

    Delegate

    The tool to remove.

    query

    String

    The query text.

    chunks

    String[]

    The text chunks to compare against.

    topN

    Int32

    The number of top results to return.

    minSimilarity

    Single

    The minimum similarity threshold.

    query

    String

    The query text.

    chunks

    String[]

    The text chunks to compare against.

    vectors

    Single[][]

    The vectors to compare against.

    topN

    Int32

    The number of top results to return.

    query

    String

    The query text.

    chunks

    String[]

    The text chunks to compare against.

    computeSimilarity

    Func<Single[], Single[][], Single[]>

    The function to compute similarity. Default is null.

    query

    String

    The query text.

    chunks

    String[]

    The text chunks to compare against.

    embeddings

    Single[][]

    The embeddings to compare against.

    computeSimilarity

    Func<Single[], Single[][], Single[]>

    The function to compute similarity. Default is null.

    tool

    Delegate

    The tool to add.

    target

    Object

    The target from which to use tools.

    IToolProvider

    Represents a provider that supplies tools.

    Public Class SmartHub
        Inherits SmartObject
        Implements IExtenderProvider, IToolProvider
    SmartHub
    SmartHub
    ArgumentNullException
    SmartHub
    IContainer
    BindingContext
    Control
    Control
    BindingContext
    IDataErrorInfo
    DataSource
    CultureInfo
    Object
    SmartEndpoint
    Boolean
    Task<Message>
    Message
    ArgumentNullException
    SmartHub
    Task<Embedding>
    Embedding
    Task<Embedding>
    Embedding
    ArgumentNullException
    SmartAdapter
    SmartAdapter
    ArgumentNullException
    T
    ArgumentNullException
    Properties
    Properties
    Object
    ArgumentNullException
    Task<EmbeddedDocument>
    EmbeddedDocument
    ITextSplitterService
    IDocumentConversionService
    IEmbeddingGenerationService
    IEmbeddingStorageService
    ArgumentNullException
    Task<EmbeddedDocument>
    EmbeddedDocument
    ITextSplitterService
    IDocumentConversionService
    IEmbeddingGenerationService
    IEmbeddingStorageService
    ArgumentNullException
    ArgumentNullException
    SmartHub
    SmartHub
    ArgumentNullException
    Task<String[]>
    ArgumentNullException
    Task<String[]>
    ArgumentNullException
    Task<Single[]>
    ArgumentNullException
    Task<Single[]>
    ArgumentNullException
    SmartHub
    SmartHub
    ArgumentNullException
    SmartHub
    SmartHub
    Boolean
    Metadata
    Func<Single[], Single[][], Single[]>
    Single
    Func<Single[], Single[][], Single[]>