Skip to content

Commit

Permalink
updated math bot and order bot
Browse files Browse the repository at this point in the history
  • Loading branch information
singhk97 committed Aug 23, 2024
1 parent 0ef2fa4 commit da62255
Show file tree
Hide file tree
Showing 7 changed files with 100 additions and 19 deletions.
3 changes: 1 addition & 2 deletions dotnet/samples/06.assistants.a.mathBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

if (config.Azure!.OpenAIApiKey != string.Empty)
{
apiKey = config.Azure!.OpenAIApiKey!;
apiKey = config.Azure!.OpenAIApiKey!;
}
else
{
Expand Down Expand Up @@ -76,7 +76,6 @@
newAssistantId = AssistantsPlanner<AssistantsState>.CreateAssistantAsync(tokenCredential!, assistantCreationOptions, "gpt-4o-mini", endpoint!).Result.Id;
}

string newAssistantId = AssistantsPlanner<AssistantsState>.CreateAssistantAsync(apiKey, assistantCreateParams, "gpt-4", endpoint).Result.Id;
Console.WriteLine($"Created a new assistant with an ID of: {newAssistantId}");
Console.WriteLine("Copy and save above ID, and set `OpenAI:AssistantId` in appsettings.Development.json.");
Console.WriteLine("Press any key to exit.");
Expand Down
9 changes: 9 additions & 0 deletions dotnet/samples/06.assistants.b.orderBot/ActionHandlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,14 @@ public async Task<string> OnPlaceOrder([ActionTurnContext] ITurnContext turnCont

return "order placed";
}

[Action(AIConstants.UnknownActionName, false)]
public string UnknownAction([ActionTurnContext] ITurnContext turnContext)
{
ArgumentNullException.ThrowIfNull(turnContext);

// Continues execution of next command in the plan.
return "The predicted function tool call doesn't exist. Please try again.";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static Dictionary<string, object> GetSchema()
},
""kind"": {
""type"": ""string"",
""description"": ""examples: Mack and Jacks, Sierra Nevada Pale Ale, Miller Lite""
""description"": ""Mack and Jacks, Sierra Nevada Pale Ale, Miller Lite""
},
""quantity"": {
""type"": ""number"",
Expand Down
86 changes: 81 additions & 5 deletions dotnet/samples/06.assistants.b.orderBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@
using Azure.Core;
using Azure.Identity;
using System.Runtime.CompilerServices;

using Microsoft.Teams.AI.Application;
using OpenAI.Files;
using OpenAI.VectorStores;
using OpenAI;
using Azure.AI.OpenAI;
using System.ClientModel;

#pragma warning disable OPENAI001
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
Expand Down Expand Up @@ -57,6 +64,59 @@
// Missing Assistant ID, create new Assistant
if (string.IsNullOrEmpty(assistantId))
{
VectorStore store = null!;
try
{
OpenAIClient client;
if (endpoint != null)
{
if (apiKey != null)
{
client = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(apiKey));
}
else
{
client = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
}
}
else
{
client = new OpenAIClient(apiKey!);
}

// Create Vector Store
var storeClient = client.GetVectorStoreClient();
store = storeClient.CreateVectorStore(new VectorStoreCreationOptions());

// Upload file.
var fileClient = client.GetFileClient();
var uploadedFile = fileClient.UploadFile("./assets/menu.pdf", FileUploadPurpose.Assistants);

// Attach file to vector store
var fileAssociation = storeClient.AddFileToVectorStore(store, uploadedFile);

// Poll vector store until file is uploaded
var maxPollCount = 5;
var pollCount = 1;
while (store.FileCounts.Completed == 0 && pollCount <= maxPollCount)
{
// Wait a second
await Task.Delay(1000);
store = storeClient.GetVectorStore(store.Id);
pollCount += 1;
}

if (store.FileCounts.Completed == 0)
{
throw new Exception("Unable to attach file to vector store. Timed out");
}
}
catch (Exception e)
{
throw new Exception("Failed to upload file to vector store.", e.InnerException);
}


AssistantCreationOptions assistantCreationOptions = new()
{
Name = "Order Bot",
Expand All @@ -67,9 +127,14 @@
"If the customer doesn't specify the type of pizza, beer, or salad they want ask them.",
"Verify the order is complete and accurate before placing it with the place_order function."
}),
ToolResources = new ToolResources()
{
FileSearch = new FileSearchToolResources() { VectorStoreIds = new List<string>() { store.Id } }
}
};

assistantCreationOptions.Tools.Add(new FunctionToolDefinition("place_order", "Creates or updates a food order.", new BinaryData(OrderParameters.GetSchema())));
assistantCreationOptions.Tools.Add(new FileSearchToolDefinition());

string newAssistantId = "";
if (apiKey != null)
Expand All @@ -91,8 +156,8 @@

// Prepare Configuration for ConfigurationBotFrameworkAuthentication
builder.Configuration["MicrosoftAppType"] = "MultiTenant";
builder.Configuration["MicrosoftAppId"] = ""; // config.BOT_ID;
builder.Configuration["MicrosoftAppPassword"] = ""; // config.BOT_PASSWORD;
builder.Configuration["MicrosoftAppId"] = config.BOT_ID;
builder.Configuration["MicrosoftAppPassword"] = config.BOT_PASSWORD;

// Create the Bot Framework Authentication to be used with the Bot Adapter.
builder.Services.AddSingleton<BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>();
Expand Down Expand Up @@ -123,11 +188,21 @@
{
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>()!;
IPlanner<AssistantsState> planner = new AssistantsPlanner<AssistantsState>(sp.GetService<AssistantsPlannerOptions>()!, loggerFactory);

TeamsAdapter adapter = sp.GetService<TeamsAdapter>()!;
TeamsAttachmentDownloaderOptions fileDownloaderOptions = new(config.BOT_ID!, adapter);

IInputFileDownloader<AssistantsState> teamsAttachmentDownloader = new TeamsAttachmentDownloader<AssistantsState>(fileDownloaderOptions);

ApplicationOptions<AssistantsState> applicationOptions = new()
{
AI = new AIOptions<AssistantsState>(planner),
AI = new AIOptions<AssistantsState>(planner) { AllowLooping = true },
Storage = sp.GetService<IStorage>(),
LoggerFactory = loggerFactory
LoggerFactory = loggerFactory,
FileDownloaders = new List<IInputFileDownloader<AssistantsState>>() { teamsAttachmentDownloader },
LongRunningMessages = true,
Adapter = sp.GetService<TeamsAdapter>(),
BotAppId = config.BOT_ID
};

Application<AssistantsState> app = new(applicationOptions);
Expand All @@ -153,3 +228,4 @@
app.MapControllers();

app.Run();
#pragma warning restore OPENAI001
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"isNotificationOnly": false,
"supportsCalling": false,
"supportsVideo": false,
"supportsFiles": false
"supportsFiles": true
}
],
"validDomains": [
Expand Down
Binary file not shown.
17 changes: 7 additions & 10 deletions dotnet/samples/06.assistants.b.orderBot/env/.env.local
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
# This file includes environment variables that can be committed to git. It's gitignored by default because it represents your local development environment.

# Built-in environment variables
APP_NAME_SUFFIX=local
TEAMS_APP_ID=ed8ff81d-89ec-4860-9afc-176c268c8434
TEAMS_APP_TENANT_ID=e474fd88-c1e2-4a74-bf7f-ffc1cc00a46c
BOT_ID=43a3a1b5-68a6-4c63-86c7-7ed0e2edeed4
TEAMSFX_ENV=local
TEAMSFX_M365_USER_NAME=[email protected]

# Generated during provision, you can also add your own variables.
BOT_ID=
TEAMS_APP_ID=
BOT_DOMAIN=


APP_NAME_SUFFIX=local
BOT_ENDPOINT=https://9v2ggs46-5130.use.devtunnels.ms
BOT_DOMAIN=9v2ggs46-5130.use.devtunnels.ms

0 comments on commit da62255

Please sign in to comment.