-
-
Notifications
You must be signed in to change notification settings - Fork 629
Expand file tree
/
Copy pathInstructService.Instruct.cs
More file actions
144 lines (122 loc) · 4.97 KB
/
InstructService.Instruct.cs
File metadata and controls
144 lines (122 loc) · 4.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
using BotSharp.Abstraction.Instructs.Options;
using BotSharp.Abstraction.Models;
using BotSharp.Abstraction.Options;
using BotSharp.Abstraction.Settings;
using BotSharp.Abstraction.Templating;
using System.Collections;
using System.Reflection;
namespace BotSharp.Core.Instructs;
public partial class InstructService
{
public async Task<T?> Instruct<T>(string text, InstructOptions? options = null) where T : class
{
var agent = await BuildInnerAgent(options);
var response = await GetAiResponse(text, agent, options);
if (string.IsNullOrWhiteSpace(response.Content)) return null;
var type = typeof(T);
T? result = null;
try
{
var botsharpOptions = _services.GetRequiredService<BotSharpOptions>();
if (IsStringType(type))
{
result = response.Content as T;
}
else if (IsListType(type))
{
var content = response.Content.JsonArrayContent();
if (!string.IsNullOrWhiteSpace(content))
{
result = JsonSerializer.Deserialize<T>(content, botsharpOptions.JsonSerializerOptions);
}
}
else
{
var content = response.Content.JsonContent();
if (!string.IsNullOrWhiteSpace(content))
{
result = JsonSerializer.Deserialize<T>(content, botsharpOptions.JsonSerializerOptions);
}
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, $"Error when getting ai response");
}
return result;
}
private async Task<Agent> BuildInnerAgent(InstructOptions? options)
{
Agent? agent = null;
AgentLlmConfig? llmConfig = null;
string? instruction = null;
if (!string.IsNullOrWhiteSpace(options?.AgentId))
{
var agentService = _services.GetRequiredService<IAgentService>();
agent = await agentService.GetAgent(options.AgentId);
if (!string.IsNullOrWhiteSpace(options?.TemplateName))
{
var template = agent?.Templates?.FirstOrDefault(x => x.Name.IsEqualTo(options.TemplateName));
instruction = BuildInstruction(template?.Content ?? string.Empty, options?.Data ?? []);
var templateLlmConfig = template?.LlmConfig;
if (templateLlmConfig?.IsValid == true)
{
llmConfig = new AgentLlmConfig
{
Provider = templateLlmConfig.Provider,
Model = templateLlmConfig.Model,
MaxOutputTokens = templateLlmConfig.MaxOutputTokens,
ReasoningEffortLevel = templateLlmConfig.ReasoningEffortLevel
};
}
}
}
return new Agent
{
Id = agent?.Id ?? Guid.Empty.ToString(),
Name = agent?.Name ?? "Unknown",
Instruction = instruction,
LlmConfig = llmConfig ?? agent?.LlmConfig ?? new()
};
}
private string BuildInstruction(string instruction, Dictionary<string, object> data)
{
var render = _services.GetRequiredService<ITemplateRender>();
return render.Render(instruction, data ?? new Dictionary<string, object>());
}
private async Task<RoleDialogModel> GetAiResponse(string text, Agent agent, InstructOptions? options)
{
var settingService = _services.GetRequiredService<ISettingService>();
var dialogs = await BuildDialogs(text, options);
var provider = options?.Provider ?? agent?.LlmConfig?.Provider ?? "openai";
var model = options?.Model ?? agent?.LlmConfig?.Model ?? settingService.GetUpgradeModel(Gpt4xModelConstants.GPT_4o);
var completion = CompletionProvider.GetChatCompletion(_services, provider: provider, model: model);
return await completion.GetChatCompletions(agent, dialogs);
}
private async Task<List<RoleDialogModel>> BuildDialogs(string text, InstructOptions? options)
{
var messages = new List<RoleDialogModel>();
if (!string.IsNullOrWhiteSpace(options?.ConversationId))
{
var conv = _services.GetRequiredService<IConversationService>();
var dialogs = await conv.GetDialogHistory();
messages.AddRange(dialogs);
}
if (!string.IsNullOrWhiteSpace(text))
{
messages.Add(new RoleDialogModel(AgentRole.User, text));
}
return messages;
}
private bool IsStringType(Type? type)
{
if (type == null) return false;
return type == typeof(string);
}
private bool IsListType(Type? type)
{
if (type == null) return false;
var interfaces = type.GetTypeInfo().ImplementedInterfaces;
return type.IsArray || interfaces.Any(x => x.Name == typeof(IEnumerable).Name);
}
}