Sunday, 2 February 2025

Building an Agent for Microsoft 365 Copilot: Adding an API plugin

In the previous post, we saw how to get started building agents for Microsoft 365 Copilot. We saw the different agent manifest files and how to configure them. There are some great out of the box capabilities available for agents like using Web search, Code Interpreter and Creating Images.

However, a very common scenario is to bring in data from external systems into Copilot and pass it to the LLM. So in this post, we will have a look at how to connect Copilot with external systems using API Plugins.

In simple terms, API Plugins are AI "wrappers" on existing APIs. We inform the LLM about an API and give it instructions on when to call these APIs and which parameters to pass to them. 

To connect your API to the Copilot agent, we have to create an "Action" and include it in the declarativeAgent.json file we saw in the previous post:

{
"$schema": "https://developer.microsoft.com/json-schemas/copilot/declarative-agent/v1.2/schema.json",
"version": "v1.2",
"name": "MyFirstAgent${{APP_NAME_SUFFIX}}",
"description": "This declarative agent helps you with finding car repair records.",
"instructions": "$[file('instruction.txt')]",
"conversation_starters": [
{
"text": "Show repair records assigned to Karin Blair"
}
],
"actions": [
{
"id": "repairPlugin",
"file": "ai-plugin.json"
}
]
}

The ai-plugin.json file contains information on how the LLM will understand our API. We will come to this file later.

Before that, let's understand how our API looks. We have a simple API that can retrieve some sample data about repairs:

import {
app,
HttpRequest,
HttpResponseInit,
InvocationContext,
} from "@azure/functions";
import repairRecords from "../repairsData.json";
/**
* This function handles the HTTP request and returns the repair information.
*
* @param {HttpRequest} req - The HTTP request.
* @param {InvocationContext} context - The Azure Functions context object.
* @returns {Promise<Response>} - A promise that resolves with the HTTP response containing the repair information.
*/
export async function repairs(
req: HttpRequest,
context: InvocationContext
): Promise<HttpResponseInit> {
context.log("HTTP trigger function processed a request.");
// Initialize response.
const res: HttpResponseInit = {
status: 200,
jsonBody: {
results: repairRecords,
},
};
// Get the assignedTo query parameter.
const assignedTo = req.query.get("assignedTo");
// If the assignedTo query parameter is not provided, return the response.
if (!assignedTo) {
return res;
}
// Filter the repair information by the assignedTo query parameter.
const repairs = repairRecords.filter((item) => {
const fullName = item.assignedTo.toLowerCase();
const query = assignedTo.trim().toLowerCase();
const [firstName, lastName] = fullName.split(" ");
return fullName === query || firstName === query || lastName === query;
});
// Return filtered repair records, or an empty array if no records were found.
res.jsonBody.results = repairs ?? [];
return res;
}
app.http("repairs", {
methods: ["GET"],
authLevel: "anonymous",
handler: repairs,
});
view raw api.ts hosted with ❤ by GitHub

Next, we will need the OpenAI specification for this API

openapi: 3.0.0
info:
title: Repair Service
description: A simple service to manage repairs
version: 1.0.0
servers:
- url: ${{OPENAPI_SERVER_URL}}/api
description: The repair api server
paths:
/repairs:
get:
operationId: listRepairs
summary: List all repairs
description: Returns a list of repairs with their details and images
parameters:
- name: assignedTo
in: query
description: Filter repairs by who they're assigned to
schema:
type: string
required: false
responses:
'200':
description: A list of repairs
content:
application/json:
schema:
type: object
properties:
results:
type: array
items:
type: object
properties:
id:
type: string
description: The unique identifier of the repair
title:
type: string
description: The short summary of the repair
description:
type: string
description: The detailed description of the repair
assignedTo:
type: string
description: The user who is responsible for the repair
date:
type: string
format: date-time
description: The date and time when the repair is scheduled or completed
image:
type: string
format: uri
description: The URL of the image of the item to be repaired or the repair process
view raw openapi.yml hosted with ❤ by GitHub

The OpenAPI specification is important as it describes in detail the exact signatures of our APIs to the LLM.

Finally, we will come to the most important file which is the ai-plugin.json file. It does several things. It informs Copilot which API methods are available, which parameters they expect and when to call them. This is done in simple human readable language so that the LLM can best understand it.

Additionally, it also handles formatting of the data before it's shown to the user in Copilot. Whether we want to use Adaptive Cards to show the data or if we want to run any other processing like removing direct links from the responses.

If you are doing plugin development, chances are that you will be spending most of your time on this file.

{
"$schema": "https://developer.microsoft.com/json-schemas/copilot/plugin/v2.2/schema.json",
"schema_version": "v2.2",
"namespace": "repairs",
"name_for_human": "MyFirstAgent${{APP_NAME_SUFFIX}}",
"description_for_human": "Track your repair records",
"description_for_model": "Plugin for searching a repair list, you can search by who's assigned to the repair.",
"functions": [
{
"name": "listRepairs",
"description": "Returns a list of repairs with their details and images",
"capabilities": {
"response_semantics": {
"data_path": "$.results",
"properties": {
"title": "$.title",
"subtitle": "$.description"
},
"static_template": {
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.5",
"body": [
{
"type": "Container",
"$data": "${$root}",
"items": [
{
"type": "TextBlock",
"text": "id: ${if(id, id, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "title: ${if(title, title, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "description: ${if(description, description, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "assignedTo: ${if(assignedTo, assignedTo, 'N/A')}",
"wrap": true
},
{
"type": "TextBlock",
"text": "date: ${if(date, date, 'N/A')}",
"wrap": true
},
{
"type": "Image",
"url": "${image}",
"$when": "${image != null}"
}
]
}
]
}
}
},
"states": {
"reasoning": {
"description": "`listRepairs` returns a list of repairs with their details and images",
"instructions": [
"When generating an answer based on the list of repairs, do not show any direct links or `Read More` links in the text."
]
},
"responding": {
"description": "`listRepairs` will return 200 Success and the list of repair items. It will return an error otherwise.",
"instructions": [
"If no error is returned, show a message to the user that the repairs could not be fetched."
]
}
}
}
],
"runtimes": [
{
"type": "OpenApi",
"auth": {
"type": "None"
},
"spec": {
"url": "apiSpecificationFile/repair.yml",
"progress_style": "ShowUsageWithInputAndOutput"
},
"run_for_functions": ["listRepairs"]
}
]
}
view raw ai-plugin.json hosted with ❤ by GitHub

Once everything is in place, we will run our plugin with simple instructions and this is how it will fetch the data from external database


Hope this helps!

Monday, 6 January 2025

Building an Agent for Microsoft 365 Copilot Chat

Microsoft 365 Copilot Chat is a powerful, general-purpose assistant that greatly improves personal productivity, helping users manage tasks like emails, calendars, document searches, and more.

However, the true potential of M365 Copilot lies in its extensibility. By building specialized "vertical" agents on top of M365 Copilot, you can unlock team productivity as well as automate business processes. These custom agents not only help in individual productivity, but also help in building workflows across groups of people.

Agents for Microsoft 365 Copilot leverage the same robust foundation—its orchestrator, foundation models, and trusted AI services—that powers M365 Copilot itself. This ensures consistency, reliability, and security at scale.

So in this post, let's take a look at how to build Agents on top of Microsoft 365 Copilot. 

We will be building a Declarative Agent with the help of the Teams toolkit. Before we start, we need the following prerequisites:

A Microsoft 365 Copilot license

Teams Toolkit Visual Studio Code extension

Enable side loading of Teams apps

Once everything is in place, we will go to Visual Studio Code 

In the Teams Toolkit extension, To create an agent, we will click on "Create new app"

Then, click on "Agent"


When the agent is created, we see a bunch of files getting created as part of the scaffolding.  So let's take a look the difference moving pieces of the agent:

manifest.json

If you have been doing M365 Apps (and Teams apps) for a while, you are familiar with this file. This is the file which represents our Agent in the M365 App catalog. It contains the various details like name, description and capabilities of the app.

{
"$schema": "https://developer.microsoft.com/json-schemas/teams/v1.19/MicrosoftTeams.schema.json",
"manifestVersion": "1.19",
"version": "1.0.0",
"id": "${{TEAMS_APP_ID}}",
"icons": {
"color": "color.png",
"outline": "outline.png"
},
"name": {
"short": "MyFirstAgent${{APP_NAME_SUFFIX}}",
"full": "Full name for MyFirstAgent"
},
"description": {
"short": "Short description for MyFirstAgent",
"full": "Full description for MyFirstAgent"
},
"accentColor": "#FFFFFF",
"composeExtensions": [],
"permissions": [
"identity",
"messageTeamMembers"
],
"copilotAgents": {
"declarativeAgents": [
{
"id": "declarativeAgent",
"file": "declarativeAgent.json"
}
]
},
"validDomains": []
}

However, you will notice the new property in this file which is "copilotAgents" This property will be pointing to a file containing the description of our new declarative agent. So let's look at how that file looks next:

declarativeAgent.json

{
"$schema": "https://developer.microsoft.com/json-schemas/copilot/declarative-agent/v1.2/schema.json",
"version": "v1.2",
"name": "MyFirstAgent",
"description": "Declarative agent created with Teams Toolkit",
"instructions": "$[file('instruction.txt')]",
"conversation_starters": [
{
"title": "Hi",
"text": "Hello, how are you?"
},
{
"title": "Surprise me",
"text": "Tell me an interesting fact"
}
],
"actions": [
{
"id": "myPlugin",
"file": "ai-plugin.json"
}
],
"capabilities": [
{
"name": "WebSearch"
},
{
"name": "GraphicArt"
},
{
"name": "CodeInterpreter"
}
]
}
Lots of interesting things are happening here. 

 
First the "instructions" property is pointing to a file which will contain the "System prompt" of our agent. We will have a look at this file later. 

Next, the "conversation_starters" property contains ready to go prompts which the user can ask the agent. Our agent will be trained to respond to these prompts. This is so that the user is properly onboarded when they land on our agent.

Finally there will be the actions and capabilities properties: 

Actions property contains connections to external APIs which the agent can invoke.

Capabilities property contains the different out of the box "Tools" which we want to allow in our agent. E.g. SharePoint and OneDrive search, image creation, code interpreter to generate charts etc 

We will talk about both these properties in more details in subsequent blog posts.

instruction.txt

And finally we have the instructions file where we can specify the system prompt for the agent. Here, we can guide the agent and assign it personality. We can make it aware of the tools and capabilities it has available and when the use them. We can provide one shot or few shot examples to "train" the agent on responding to users.

You are a declarative agent and were created with Team Toolkit. You should start every response and answer to the user with "Thanks for using Teams Toolkit to create your declarative agent!\n\n" and then answer the questions and help the user.
view raw instruction.txt hosted with ❤ by GitHub
Once all files are in place, you can click "Provision" from the Teams toolkit extension:

And our new agent will be ready!

Here is how the agent will provide the conversation starters when we first lang on it:


Simple conversation using Web search capability:


Conversation using Web search and Code Interpreter capabilities:



Hope this was helpful! We will explore M365 Copilot Agents more in subsequent blog posts.

Monday, 9 December 2024

Search SharePoint and OneDrive files in natural language with OpenAI function calling and Microsoft Graph Search API

By now, we have seen "Chat with your documents" functionality being introduced in many Microsoft 365 applications. It is typically built by combining Large Language Models (LLMs) and vector databases. 

To make the documents "chat ready", they have to be converted to embeddings and stored in vector databases like Azure AI Search. However, indexing the documents and keeping the index in sync are not trivial tasks. There are many moving pieces involved. Also, many times there is no need for "similarity search" or "vector search" where the search is made based on meaning of the query. 

In such cases, a simple "keyword" search can do the trick. The advantage of using keyword search in Microsoft 365 applications is that the Microsoft Search indexes are already available as part of the service. APIs like the Microsoft Graph Search API and the SharePoint Search REST API give us "ready to consume" endpoints which can be used to query documents across SharePoint and OneDrive. Keeping these search indexes in sync with the changes in the documents is also handled by the Microsoft 365 service itself.

So in this post, let's have a look at how we can combine OpenAI's gpt-4o Large Language Model with Microsoft Graph Search API to query SharePoint and OneDrive documents in natural language. 

On a high level we will be using OpenAI function calling to achieve this. Our steps are going to be:

1. Define an OpenAI function and make it available to the LLM.  


2. During the course of the chat, if the LLM thinks that to respond to the user, it needs to call our function, it will respond with the function name along with the parameters.

3. Call the Microsoft Graph Search API based on the parameters provided by the LLM.

4. Send the results returned from the Microsoft Graph back to the LLM to generate a response in natural language.

So let's see how to achieve this. In this code I have used the following nuget packages:

https://www.nuget.org/packages/Azure.AI.OpenAI/2.1.0

https://www.nuget.org/packages/Microsoft.Graph/5.64.0

The first thing we will look at is our OpenAI function definition:

"functions": [{
"name": "search_microsoft365_documents",
"description": "Search the Microsfot 365 documents from user's SharePoint and OneDrive",
"parameters": {
"type": "object",
"required": ["searchQuery"],
"properties": {
"searchQuery": {
"type": "string",
"description": "the text to search in the documents to get the required information"
}
}
}
}
]
In this function we are informing the LLM that if needs to search any files as part of providing the responses, it can call this function. The function name will be returned in the response and the relevant parameter will be provided as well. Now let's see how our orchestrator function looks:

static async Task Main(string[] args)
{
string endpoint = "<azure-openi-key>";
string key = "<azure-openi-endpoint>";
string deploymentName = "gpt-4o";
var azureOpenAIClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(key));
//get userQuestion from the console
Console.WriteLine("What would you like to search?: ");
string userQuestion = Console.ReadLine();
//1. Call Open AI Chat API with the user's question.
var chatCompletionResponse = await CallOpenAIAPI(userQuestion, deploymentName, azureOpenAIClient);
//2. Check if the Chat API decided that for answering the question, a function call to the MS Graph needs to be made.
if (chatCompletionResponse.Value.FinishReason == ChatFinishReason.ToolCalls)
{
string functionName = chatCompletionResponse.Value.ToolCalls[0].FunctionName;
BinaryData functionArguments = chatCompletionResponse.Value.ToolCalls[0].FunctionArguments;
string toolCallId = chatCompletionResponse.Value.ToolCalls[0].Id;
Console.WriteLine($"Function Name: {functionName}, Params: {functionArguments}");
if (functionName == "search_microsoft365_documents")
{
//3. If the MS Graph function call needs to be made, the Chat API will also provide which parameters need to be passed to the function.
var searchParams = JsonSerializer.Deserialize<M365SearchQueryParams>(functionArguments);
//4. Call the MS Graph with the parameters provided by the Chat API
var functionResponse = await ExecuteMicrosoft365SearchWithGraph(searchParams.searchQuery);
Console.WriteLine($"Graph Response: {functionResponse}");
//5. Call the Chat API again with the function response.
var functionMessages = new List<OpenAI.Chat.ChatMessage>
{
new AssistantChatMessage(new List<ChatToolCall>() { ChatToolCall.CreateFunctionToolCall(toolCallId, functionName, functionArguments) }),
new ToolChatMessage(toolCallId, functionResponse)
};
chatCompletionResponse = await CallOpenAIAPI(userQuestion, deploymentName, azureOpenAIClient, functionMessages);
//6. Print the final response from the Chat API.
Console.WriteLine("------------------");
Console.WriteLine(chatCompletionResponse.Value.Content[0].Text);
}
}
else
{
//If the LLM decided that a function call is not needed, print the final response from the Chat API.
Console.WriteLine(chatCompletionResponse.Value.Content[0].Text);
}
}

There is a lot to unpack here as this function is the one which does the heavy lifting. This code is responsible for handling the chat with OpenAI, calling the MS Graph and also responding back to the user based on the response from the Graph. 

Next, let's have a look at the code which calls the Microsoft Graph based on the parameters provided by the LLM. 

Before executing this code, you will need to have created an App registration. Here is how to do that: https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app 

Since we are calling the Microsoft Graph /search endpoint with delegated permissions, the app registration will need a minimum of the User.Read and Files.Read.All permissions granted. https://learn.microsoft.com/en-us/graph/api/search-query?view=graph-rest-1.0&tabs=http

private static async Task<string> ExecuteMicrosoft365SearchWithGraph(string searchQuery)
{
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
GraphServiceClient graphClient = GetGraphClient(["User.Read", "Files.Read.All"]);
var requestBody = new QueryPostRequestBody
{
Requests = new List<SearchRequest>
{
new SearchRequest
{
EntityTypes = new List<EntityType?>
{
EntityType.DriveItem,
},
Query = new SearchQuery
{
QueryString = searchQuery,
},
From = 0,
Size = 25,
},
},
};
var searchResults = await graphClient.Search.Query.PostAsQueryPostResponseAsync(requestBody);
var result = string.Empty;
foreach (var hit in searchResults.Value[0].HitsContainers[0].Hits)
{
var listItem = hit.Resource as DriveItem;
if (listItem != null)
{
//Using the summary of the search result. In production, it might be the case that the summary is not enough.
//In that situation, the solution could be to fetch the file contents through another graph call
result += hit.Summary;
}
}
return result;
}
This code get the parameters sent from the LLM and uses the Microsoft Graph .NET SDK to call the /search endpoint and fetch the files based on the searchQuery properties. Once the files are returned, their summary value is concatenated into a string and returned to the orchestrator function so that it can be sent again to the LLM. 

Finally, lets have a look at our CallOpenAI function which is responsible for talking to the Open AI chat api.
 
private static async Task<ClientResult<ChatCompletion>> CallOpenAIAPI(string userQuestion, string modelDeploymentName, AzureOpenAIClient azureOpenAIClient, IList<OpenAI.Chat.ChatMessage> functionMessages = null)
{
var chatCompletionOptions = new ChatCompletionOptions();
var messages = new List<OpenAI.Chat.ChatMessage>
{
new SystemChatMessage("You are a search assistant that helps find information. Only use the functions and parameters you have been provided with."),
new UserChatMessage(userQuestion)
};
if (functionMessages != null)
{
foreach (var functionMessage in functionMessages)
{
messages.Add(functionMessage);
}
}
chatCompletionOptions.Tools.Add(ChatTool.CreateFunctionTool(
functionName: "search_microsoft365_documents",
functionDescription: "Search the Microsfot 365 documents from user's SharePoint and OneDrive.",
functionParameters: BinaryData.FromString("{\"type\": \"object\",\"required\": [\"searchQuery\"],\"properties\": {\"searchQuery\": {\"type\": \"string\",\"description\": \"the text to search in the documents to get the required information\"}}}")
));
var chatCompletionResponse = await azureOpenAIClient.GetChatClient(modelDeploymentName).CompleteChatAsync(messages, chatCompletionOptions);
return chatCompletionResponse;
}
This code defines the Open AI function which will be included in our Chat API calls. Also, the user's search query is sent to the API to determine if the function needs to be called. This function is also called again after the response from the Microsoft Graph is fetched. At that time, this function contains the details fetched from the Graph to generate an output in natural language. This way, we can use Open AI function calling together with Microsoft Graph API to search files in SharePoint and OneDrive.

Hope this helps!

Tuesday, 5 November 2024

Working with OpenAI Assistants: Using code interpreter to generate charts

This is the fourth post in the series where we explore the OpenAI Assistants API. In this post, we will be looking at the code interpreter tool which allows us to generate charts based on some data. This is very powerful for scenarios where you have to do data analysis on JSON, csv or Microsoft Excel files and generate charts and reports based on them.

See the following posts for the entire series:

Working with the OpenAI Assistants API: Create a simple assistant

Working with the OpenAI Assistants API: Using file search 

Working with the OpenAI Assistants API: Chat with Excel files using Code interpreter 

Working with the OpenAI Assistants API: Using code interpreter to generate charts (this post) 

The Code Interpreter tool has access to a sandboxed python code execution environment within the Assistants API. This can provide very useful as the Assistants API can iteratively run code against the files provided to it and generate charts!

So in this post, let's see how we can generate charts based on an excel file with the code interpreter tool. The excel file we will be querying will be the same one we used in the last post. It contains details of customers like their name and the licenses purchased of a fictional product by them:

To generate charts using the Code interpreter, we have to use the following moving pieces: 

  • First, we need to upload the excel file using the Open AI File client 
  • Then, we need to connect the uploaded file to the Code Interpreter tool in either an assistant or a thread which would enable the assistant to generate a chart on the document.
For the demo code, we will be using the Azure OpenAI service for working with the OpenAI gpt-4o model and since we will be using .NET code, we will need the Azure OpenAI .NET SDK as well as Azure.AI.OpenAI.Assistants nuget packages.

var azureClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(key));
OpenAIFileClient fileClient = azureClient.GetOpenAIFileClient();
AssistantClient assistantClient = azureClient.GetAssistantClient();
OpenAIFile infoFile = await fileClient.UploadFileAsync("C:\\Users\\vardh\\Documents\\Customers.xlsx", FileUploadPurpose.Assistants);
AssistantCreationOptions assistantOptions = new()
{
Name = "CodeInterpreterProMAX",
Instructions =
"You are an assistant that looks up sales data and helps visualize the information based"
+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
+ " the code interpreter tool to do so.",
Tools =
{
new CodeInterpreterToolDefinition()
},
ToolResources = new()
{
CodeInterpreter = new()
{
FileIds = { infoFile.Id },
}
}
};
Assistant assistant = assistantClient.CreateAssistant(deploymentName, assistantOptions);
ThreadCreationOptions threadOptions = new()
{
InitialMessages = { "Can you plot a bar graph for all customers and their purchases?" },
};
ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
do
{
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.WriteLine($"Thread run status: {threadRun.Status}");
threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
} while (!threadRun.Status.IsTerminal);
CollectionResult<ThreadMessage> messages = assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
foreach (ThreadMessage message in messages)
{
Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
foreach (MessageContent contentItem in message.Content)
{
if (!string.IsNullOrEmpty(contentItem.Text))
{
Console.WriteLine($"{contentItem.Text}");
}
if (!string.IsNullOrEmpty(contentItem.ImageFileId))
{
OpenAIFile imageInfo = fileClient.GetFile(contentItem.ImageFileId);
BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
imageBytes.ToStream().CopyTo(stream);
Console.WriteLine($"<image: {imageInfo.Filename}.png>");
}
}
}

[USER]: Can you plot a bar graph for all customers and their purchases?

[ASSISTANT] : Sure, let's first inspect the contents of the uploaded file to understand its structure and extract the necessary data.

[ASSISTANT] : The dataset contains the following columns:

  • Customer Name
  • Email
  • Licenses Purchased
  • Total Amount Paid

To create a bar graph of all customers and their purchases, we will use the "Customer Name" and "Licenses Purchased" columns.

Let's proceed with creating the bar graph.

[ASSISTANT] : <image: ea8db0b2-2f7a-420e-9c77-c081b7bd0132.png>

Here is the bar graph showing the number of licenses purchased by each customer. If you need any further analysis or additional visualizations, please let me know!

view raw output.md hosted with ❤ by GitHub

And this is the file generated by the code interpreter tool:

As you can see the code interpreter tool takes a few passes at the data. It tries to understand the document before generating the chart. This is a really powerful feature and the possibilities are endless! 

Hope this helps.

Monday, 4 November 2024

Working with OpenAI Assistants: Chat with Excel files using Code interpreter

This is the third post in the series where we explore the OpenAI Assistants API. In this post, we will be looking at the code interpreter tool which allows us to upload files to the Assistants API and write python code against them. This is very powerful for scenarios where you have to do data analysis on csv or Microsoft Excel files and generate charts and reports on them.

See the following posts for the entire series:

Working with the OpenAI Assistants: Create a simple assistant

Working with the OpenAI Assistants: Using file search 

Working with the OpenAI Assistants: Chat with Excel files using code interpreter (this post) 

Working with OpenAI Assistants: Using code interpreter to generate charts

The Retrieval Augmented Generation (RAG) pattern, which was discussed in previous posts, works great for text based files like Microsoft Word and PDF documents. However, when it comes to structured data files like csv or excel, it comes out short. An this where the Code Interpreter tool can come in very handy. It can repetitively run python code on documents until it is confident that the user's question has been answered.

So in this post, let's see how we can query an excel file with the code interpreter tool. The excel file we will be querying will contain details of customers like their name and the licenses purchased of a fictional product by them:

To upload and analyse documents using the Code interpreter, we have to use the following moving pieces: 

  • First, we need to upload files using the Open AI File client 
  • Then, we need to connect the uploaded file to the Code Interpreter tool in either an assistant or a thread which would enable the assistant to answer questions based on the document.
For the demo code, we will be using the Azure OpenAI service for working with the OpenAI gpt-4o model and since we will be using .NET code, we will need the Azure OpenAI .NET SDK as well as Azure.AI.OpenAI.Assistants nuget packages.

var azureClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(key));
OpenAIFileClient fileClient = azureClient.GetOpenAIFileClient();
AssistantClient assistantClient = azureClient.GetAssistantClient();
OpenAIFile infoFile = await fileClient.UploadFileAsync("C:\\Customers.xlsx", FileUploadPurpose.Assistants);
AssistantCreationOptions assistantOptions = new()
{
Name = "CodeInterpreterProMAX",
Instructions =
"You are an assistant that looks up sales data and helps visualize the information based"
+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
+ " the code interpreter tool to do so.",
Tools =
{
new CodeInterpreterToolDefinition()
},
ToolResources = new()
{
CodeInterpreter = new()
{
FileIds = { infoFile.Id },
}
}
};
Assistant assistant = assistantClient.CreateAssistant(deploymentName, assistantOptions);
ThreadCreationOptions threadOptions = new()
{
InitialMessages = { "Which customer has purchased the most licenses?" },
};
ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
do
{
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.WriteLine($"Thread run status: {threadRun.Status}");
threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
} while (!threadRun.Status.IsTerminal);
CollectionResult<ThreadMessage> messages = assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
foreach (ThreadMessage message in messages)
{
Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
foreach (MessageContent contentItem in message.Content)
{
if (!string.IsNullOrEmpty(contentItem.Text))
{
Console.WriteLine($"{contentItem.Text}");
}
}
}

[USER]: Which customer has purchased the most licenses?

[ASSISTANT]: Let's first take a look at the content of the uploaded file to understand its structure. I'll load the file and inspect the first few rows of data.

[ASSISTANT]: The data contains information about customers, including their names, email addresses, the number of licenses they purchased, and the total amount they paid.

To identify the customer who has purchased the most licenses, we will find the customer with the maximum value in the "Licenses Purchased" column.

[ASSISTANT]: The customer who has purchased the most licenses is Alice Johnson, with a total of 25 licenses purchased.

view raw output.md hosted with ❤ by GitHub

As you can see the code interpreter tool takes a few passes at the data. It tries to understand the document before answering the question. This is a really powerful feature and the possibilities are endless! 

Hope this helps.

Monday, 14 October 2024

Working with OpenAI Assistants: Using file search

This is the second post in the series where we explore the OpenAI Assistants API. In this post, we will be looking at the file search capabilities which allows us to upload files to the Assistants API and chat with them. See the following posts for the entire series:

Working with OpenAI Assistants: Create a simple assistant

Working with OpenAI Assistants: Using file search (this post)

Working with OpenAI Assistants: Chat with Excel files using code interpreter

Working with OpenAI Assistants: Using code interpreter to generate charts

The file search API uses the Retrieval Augmented Generation (RAG) pattern which has been made popular recently. The added advantage of using the Assistants API for this is that the API manages document chunking, vectorizing and indexing for us. Whereas without the Assistants API we would have to use a separate service like Azure AI Search and manage the document indexing ourselves. 

To upload and chat with documents using the Assistants API, we have to use the following moving pieces: 

  • First, we need to create a Vector Store in the Assistants API.
  • Then, we need to upload files using the Open AI File client and add them to the vector store.
  • Finally, we need to connect the vector store to either an assistant or a thread which would enable to assistant to answer questions based on the document.

For the demo code, we will be using the Azure OpenAI service for working with the OpenAI gpt-4o model and since we will be using .NET code, we will need the Azure OpenAI .NET SDK as well as Azure.AI.OpenAI.Assistants nuget packages.

string endpoint = "https://<myopenaiservice>.openai.azure.com/";
string key = "<my-open-ai-service-key>";
string deploymentName = "gpt-4o";
var azureClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(key));
OpenAIFileClient fileClient = azureClient.GetOpenAIFileClient();
AssistantClient assistantClient = azureClient.GetAssistantClient();
VectorStoreClient vectorClient = azureClient.GetVectorStoreClient();
var vectorStore = vectorClient.CreateVectorStore(true, new VectorStoreCreationOptions()
{
Name = "focusworks_ai_vector_store",
//Make the documents expire after 3 days of inactivity.
ExpirationPolicy = new VectorStoreExpirationPolicy() {
Anchor = VectorStoreExpirationAnchor.LastActiveAt,
Days = 3
}
});
//Create and upload sample document
using Stream document = BinaryData.FromBytes(@"Focusworks AI is a versatile productivity tool designed to streamline your workflow and enhance collaboration within Microsoft Teams. With its internet-connected ChatGPT bot, you can engage in insightful conversations on any topic, leveraging a rich knowledge base to gain valuable insights. It also empowers you to create stunning AI-powered images effortlessly, simply by describing what you envision in your own words.
One of the standout features of Focusworks AI is its ability to interact with your data. You can upload documents, ask questions, and have a dynamic conversation with your information, uncovering details and insights you might have missed. The AI is also tailored to help you craft more effective Teams messages, improving communication quality and ensuring your ideas are clearly conveyed. Additionally, it can summarize both your personal and group chats, making it easy to extract key points and stay updated.
Sharing your generated content and insights with colleagues is made seamless through Focusworks AI. You can post directly to Teams channels and group chats, ensuring everyone stays informed. The intuitive dashboard allows you to view all your recently created content and quickly access the relevant chats or channels, keeping your workflow organized and efficient. With Focusworks AI, you can eliminate information overload and enjoy a more productive work environment. Try the app for free and conveniently upgrade to a subscription if it elevates your workflow!"u8.ToArray()).ToStream();
OpenAIFile infoFile = await fileClient.UploadFileAsync(document, "focusworks_ai.txt", FileUploadPurpose.Assistants);
await vectorClient.AddFileToVectorStoreAsync(vectorStore.VectorStoreId, infoFile.Id, true);
AssistantCreationOptions assistantOptions = new()
{
Name = "FileSearchPro",
Instructions =
@"You are FileSearchPro, an intelligent assistant designed to help users locate information within their uploaded files. Your primary function is to search through these documents and provide accurate, concise answers to users' questions. You understand various file types and can extract relevant data, ensuring users get the information they need quickly and efficiently.
Key Features:
Efficiently search all uploaded documents to extract precise information.
Provide clear, straightforward answers directly from the file contents.
Maintain confidentiality and security of all user data.
Offer guidance on effective search queries if needed.
Always strive to deliver accurate and helpful information, enhancing users' ability to access and utilize their stored documents effectively.",
Tools =
{
new FileSearchToolDefinition(),
},
ToolResources = new() //Files can be specified at the assistant level.
{
FileSearch = new()
{
VectorStoreIds = { vectorStore.VectorStoreId },
}
}
};
Assistant assistant = assistantClient.CreateAssistant(deploymentName, assistantOptions);
ThreadCreationOptions threadOptions = new()
{
InitialMessages = { "What is Focusworks AI?" },
//Files can also be specified at the thread level.
//ToolResources = new()
//{
// FileSearch = new()
// {
// VectorStoreIds = { vectorStore.VectorStoreId },
// }
//}
};
ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
do
{
Thread.Sleep(TimeSpan.FromSeconds(1));
threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
} while (!threadRun.Status.IsTerminal);
CollectionResult<ThreadMessage> messages = assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
foreach (ThreadMessage message in messages)
{
Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
foreach (MessageContent contentItem in message.Content)
{
if (!string.IsNullOrEmpty(contentItem.Text))
{
Console.WriteLine($"{contentItem.Text}");
if (contentItem.TextAnnotations.Count > 0)
{
Console.WriteLine();
}
// Include annotations, if any.
foreach (TextAnnotation annotation in contentItem.TextAnnotations)
{
if (!string.IsNullOrEmpty(annotation.InputFileId))
{
Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
}
if (!string.IsNullOrEmpty(annotation.OutputFileId))
{
Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
}
}
}
}
}

[USER]: What is Focusworks AI?

[ASSISTANT]: Focusworks AI is a productivity tool designed to enhance collaboration and streamline workflows within Microsoft Teams. It features an internet-connected ChatGPT bot that allows users to engage in insightful conversations and gain valuable insights from a rich knowledge base. The tool can create AI-powered images by simply describing users' visions. A key feature of Focusworks AI is its ability to interact with users' data, enabling document uploads and dynamic conversations to uncover insights. It also improves communication by helping craft more effective Teams messages and by summarizing both personal and group chats.

  • File citation, file ID: assistant-VVwKBdUixwPyk6RuOEnJpixh
view raw output.md hosted with ❤ by GitHub

Limitations


As per OpenAI docs, there are some limitations for the file search tool:

  • Each vector store can hold up to 10,000 files.
  • The maximum file size of a file which can be uploaded is 512 MB. Each file should contain no more than 5,000,000 tokens per file (computed automatically when you attach a file).

When querying for the documents in the vector store, we have to be aware of the following things which are not possible right now. However, the OpenAI team are working on this and some of these features will be available soon:

  • Support for deterministic pre-search filtering using custom metadata.
  • Support for parsing images within documents (including images of charts, graphs, tables etc.)
  • Support for retrievals over structured file formats (like csv or jsonl).
  • Better support for summarization — the tool today is optimized for search queries.

Current supported files types can be found in the OpenAI docs

Hope this helps!

Monday, 7 October 2024

Working with OpenAI Assistants: Create a simple assistant

With OpenAI's recently released Assistants API, building AI bots becomes a lot easier. Using the API, an assistant can leverage custom instructions, files and tools (previously called functions) and answer user questions based on them.

Before the Assistants API, building such assistants was possible but for a lot of things, we had to use our own services e.g. vector storage for file search, database for maintaining chat history etc.

The Assistants API gives us a handy wrapper on top of all these disparate services and a single endpoint to work with. So in this series of posts, let's have a look at what the Assistants API can do.

Working with OpenAI Assistants: Create a simple assistant (this post)

Working with OpenAI Assistants: Using file search

Working with OpenAI Assistants: Chat with Excel files using code interpreter

Working with OpenAI Assistants: Using code interpreter to generate charts

The first thing we are going to do is build a simple assistant which has a "SharePoint Tutor" personality. It will be used to answer questions for users who are learning to use SharePoint. Before deep diving into the code, lets understand the different moving pieces of the Assistants API: 

An assistant is a container in which all operations between the AI and the user are managed.

A thread is a list of messages which were exchanged between the user and AI. The thread is also responsible for maintaining the conversation history.

A run is a single invocation of an assistant based on the history in the thread as well as the tools available to the assistant. After a run is executed, new messages are generated and added to the thread.

For the demo code, we will be using the Azure OpenAI service for working with the OpenAI gpt-4o model and since we will be using .NET code, we will need the Azure OpenAI .NET SDK as well as Azure.AI.OpenAI.Assistants nuget packages.

string endpoint = "https://<myopenaiservice>.openai.azure.com/";
string key = "<my-open-ai-service-key>";
string deploymentName = "gpt-4o";
//We are using the Azure OpenAI Service so create an Azure OpenAI client
var azureClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(key));
AssistantClient assistantClient = azureClient.GetAssistantClient();
//Create assistant
AssistantCreationOptions assistantOptions = new()
{
Name = "SharePoint Tutor",
Instructions =
"You are SharePoint Tutor, an expert assistant in guiding users through SharePoint. " +
"Your role is to provide clear, step-by-step instructions, troubleshooting tips, and best practices for managing and navigating SharePoint. " +
"Always respond in a friendly, approachable tone, and aim to make even complex tasks easy to understand. " +
"When users ask for help with specific tasks, provide detailed instructions. If they encounter issues, offer practical solutions and guidance. " +
"Ensure your responses are concise yet informative, and be ready to suggest tips that improve the user's overall SharePoint experience."
};
Assistant assistant = assistantClient.CreateAssistant(deploymentName, assistantOptions);
//Create thread
ThreadCreationOptions threadOptions = new()
{
InitialMessages = { "What is a webpart?" }
};
//Create a run
ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions, new RunCreationOptions() { });
do
{
Thread.Sleep(TimeSpan.FromSeconds(1));
threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
} while (!threadRun.Status.IsTerminal);
//Get messages from a thread. This includes the most recent created message as well.
CollectionResult<ThreadMessage> messages = assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
foreach (ThreadMessage message in messages)
{
Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
foreach (MessageContent contentItem in message.Content)
{
if (!string.IsNullOrEmpty(contentItem.Text))
{
Console.WriteLine($"{contentItem.Text}");
if (contentItem.TextAnnotations.Count > 0)
{
Console.WriteLine();
}
}
}
Console.WriteLine();
}

[USER]: What is a webpart?

[ASSISTANT]: A web part is a versatile and reusable building block in SharePoint that allows you to add dynamic content and functionality to your SharePoint pages. You can think of a web part as a widget that you can place on a page to display information or provide certain functionality, such as showing a calendar, a list of documents, news headlines, or even embedding video content.

view raw output.md hosted with ❤ by GitHub
This was a simple assistant creation just to get us familiar with the Assitants API. In the next posts, we will dive deeper into the API and explore the more advanced concepts. Stay tuned!