microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
fix/msal-cache

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.AI/Prompts/ChatPrompt/ChatPrompt.Functions.cs

73lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using Humanizer;
5
6using Json.Schema;
7
8using Microsoft.Teams.AI.Messages;
9
10namespace Microsoft.Teams.AI.Prompts;
11
12public 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 Func<FunctionCall, CancellationToken, Task<object?>> Invoke(FunctionCollection functions)
38 {
39 return async (call, cancellationToken) => await _Invoke(call, functions, cancellationToken).ConfigureAwait(false);
40 }
41
42 private async Task<object?> _Invoke(FunctionCall call, FunctionCollection functions, CancellationToken cancellationToken = default)
43 {
44 var function = functions.Get(call.Name) ?? throw new NotImplementedException();
45 var logger = Logger.Child($"functions.{call.Name}");
46
47 if (function is Function func)
48 {
49 foreach (var plugin in Plugins)
50 {
51 call = await plugin.OnBeforeFunctionCall(this, func, call, cancellationToken).ConfigureAwait(false);
52 }
53
54 var startedAt = DateTime.Now;
55 logger.Debug(call.Arguments);
56
57 var res = await func.Invoke(call).ConfigureAwait(false);
58 var endedAt = DateTime.Now;
59
60 logger.Debug(res);
61 logger.Debug($"elapse time: {(endedAt - startedAt).Humanize(3)}");
62
63 foreach (var plugin in Plugins)
64 {
65 res = await plugin.OnAfterFunctionCall(this, func, call, res, cancellationToken).ConfigureAwait(false);
66 }
67
68 return res;
69 }
70
71 return Task.FromResult<object?>(null);
72 }
73}