-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
187 lines (151 loc) · 5.58 KB
/
Copy pathProgram.cs
File metadata and controls
187 lines (151 loc) · 5.58 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
using OpenAI;
using OpenAI.Chat;
using Microsoft.Extensions.Configuration;
var configuration = BuildConfiguration();
var apiKey = configuration["OpenAI:ApiKey"];
if (string.IsNullOrWhiteSpace(apiKey))
{
apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
}
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.WriteLine("OpenAI API key not found. Set OpenAI:ApiKey in appsettings.local.json or use OPENAI__APIKEY / OPENAI_API_KEY.");
return;
}
var client = new OpenAIClient(apiKey);
var chatClient = client.GetChatClient("gpt-4.1-mini");
var workspaceRoot = ResolveWorkspaceRoot();
var transcriptLogPath = configuration["Logging:TranscriptPath"];
if (string.IsNullOrWhiteSpace(transcriptLogPath))
{
Console.WriteLine("Transcript log path not configured. Set Logging:TranscriptPath in appsettings.json or use the LOGGING__TRANSCRIPTPATH environment variable.");
return;
}
var resolvedLogPath = Path.GetFullPath(transcriptLogPath);
try
{
Directory.CreateDirectory(resolvedLogPath);
}
catch (Exception ex)
{
Console.WriteLine($"Cannot create transcript log directory '{resolvedLogPath}': {ex.Message}");
return;
}
using var transcript = new TranscriptLogger(resolvedLogPath, workspaceRoot);
var messages = new List<ChatMessage>
{
new SystemChatMessage("""
You are a helpful local AI agent.
Be concise.
Ask clarifying questions only when required.
When the user asks to export, save, or generate a markdown report, create the file with ExportMarkdownReport and then tell the user where it was saved.
""")
};
Console.WriteLine("Simple Agent");
Console.WriteLine("Type 'exit' to quit.");
Console.WriteLine($"Tool access root: {workspaceRoot}");
Console.WriteLine($"Transcript: {transcript.LogFilePath}");
Console.WriteLine();
var options = new ChatCompletionOptions();
foreach (var tool in AgentTools.Definitions)
{
options.Tools.Add(tool);
}
while (true)
{
Console.Write("You: ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
messages.Add(new UserChatMessage(input));
transcript.LogUserInput(input);
try
{
bool requiresAction;
do
{
requiresAction = false;
var response = await chatClient.CompleteChatAsync(messages, options);
var completion = response.Value;
switch (completion.FinishReason)
{
case ChatFinishReason.Stop:
{
var answer = completion.Content.Count > 0
? string.Concat(completion.Content.Select(part => part.Text))
: "I do not have a response.";
Console.WriteLine();
Console.WriteLine($"Agent: {answer}");
Console.WriteLine();
transcript.LogAssistantResponse(answer);
messages.Add(new AssistantChatMessage(completion));
break;
}
case ChatFinishReason.ToolCalls:
{
messages.Add(new AssistantChatMessage(completion));
foreach (var toolCall in completion.ToolCalls)
{
var toolResult = AgentTools.Invoke(toolCall, workspaceRoot);
transcript.LogToolCall(toolCall.FunctionName, toolCall.FunctionArguments.ToString(), toolResult);
messages.Add(new ToolChatMessage(toolCall.Id, toolResult));
}
requiresAction = true;
break;
}
default:
{
Console.WriteLine();
Console.WriteLine($"Agent stopped with reason: {completion.FinishReason}");
Console.WriteLine();
transcript.LogSystemEvent($"Completion finished with reason: {completion.FinishReason}");
messages.Add(new AssistantChatMessage(completion));
break;
}
}
}
while (requiresAction);
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine($"Agent error: {ex.Message}");
Console.WriteLine();
transcript.LogError(ex);
}
TrimConversation(messages, maxNonSystemMessages: 12);
}
static string ResolveWorkspaceRoot()
{
var configuredWorkspace = Environment.GetEnvironmentVariable("AGENT_WORKSPACE_ROOT");
var workspaceRoot = string.IsNullOrWhiteSpace(configuredWorkspace)
? Directory.GetCurrentDirectory()
: configuredWorkspace;
return Path.GetFullPath(workspaceRoot);
}
static IConfiguration BuildConfiguration()
{
return new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: false)
.AddEnvironmentVariables()
.Build();
}
static void TrimConversation(List<ChatMessage> messages, int maxNonSystemMessages)
{
if (messages.Count <= maxNonSystemMessages + 1)
return;
var systemMessage = messages[0];
var startIndex = Math.Max(1, messages.Count - maxNonSystemMessages);
while (startIndex > 1 && messages[startIndex] is ToolChatMessage)
{
startIndex--;
}
var recentMessages = messages.Skip(startIndex).ToList();
messages.Clear();
messages.Add(systemMessage);
messages.AddRange(recentMessages);
}