microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.AI/Prompts/ChatPrompt/ChatPrompt.Functions.cs
68lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using Humanizer; |
| 5 | |
| 6 | using Json.Schema; |
| 7 | |
| 8 | using Microsoft.Teams.AI.Messages; |
| 9 | |
| 10 | namespace Microsoft.Teams.AI.Prompts; |
| 11 | |
| 12 | public partial class ChatPrompt<TOptions> |
| 13 | { |
| 14 | public ChatPrompt<TOptions> Function(IFunction function) |
| 15 | { |
| 16 | Functions.Add(function); |
| 17 | Logger.Debug($"registered function '{function.Name}'", function.ToString()); |
| 18 | return this; |
| 19 | } |
| 20 | |
| 21 | public ChatPrompt<TOptions> Function(string name, string? description, Delegate handler) |
| 22 | { |
| 23 | var func = new Function(name, description, handler); |
| 24 | Functions.Add(func); |
| 25 | Logger.Debug($"registered function '{func.Name}'", func.ToString()); |
| 26 | return this; |
| 27 | } |
| 28 | |
| 29 | public ChatPrompt<TOptions> Function(string name, string? description, JsonSchema parameters, Delegate handler) |
| 30 | { |
| 31 | var func = new Function(name, description, parameters, handler); |
| 32 | Functions.Add(func); |
| 33 | Logger.Debug($"registered function '{func.Name}'", func.ToString()); |
| 34 | return this; |
| 35 | } |
| 36 | |
| 37 | public async Task<object?> Invoke(FunctionCall call, CancellationToken cancellationToken = default) |
| 38 | { |
| 39 | var function = Functions.Get(call.Name) ?? throw new NotImplementedException(); |
| 40 | var logger = Logger.Child($"Functions.{call.Name}"); |
| 41 | |
| 42 | if (function is Function func) |
| 43 | { |
| 44 | foreach (var plugin in ChatPlugins) |
| 45 | { |
| 46 | call = await plugin.OnBeforeFunctionCall(this, func, call, cancellationToken); |
| 47 | } |
| 48 | |
| 49 | var startedAt = DateTime.Now; |
| 50 | logger.Debug(call.Arguments); |
| 51 | |
| 52 | var res = await func.Invoke(call); |
| 53 | var endedAt = DateTime.Now; |
| 54 | |
| 55 | logger.Debug(res); |
| 56 | logger.Debug($"elapse time: {(endedAt - startedAt).Humanize(3)}"); |
| 57 | |
| 58 | foreach (var plugin in ChatPlugins) |
| 59 | { |
| 60 | res = await plugin.OnAfterFunctionCall(this, func, call, res, cancellationToken); |
| 61 | } |
| 62 | |
| 63 | return res; |
| 64 | } |
| 65 | |
| 66 | return Task.FromResult<object?>(null); |
| 67 | } |
| 68 | } |