Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Diagnostics;
- using System.ComponentModel;
- using System.Text.RegularExpressions;
- using InterActor;
- namespace GPTAgent
- {
- public partial class MainWindow : Window, INotifyPropertyChanged
- {
- private bool isAutoGPTConnected = false;
- private string conversationHistoryFilePath = @"C:\Users\post\Auto-GPT\auto_gpt_workspace\ai\ai_conv.txt";
- private AutoGPT _autoGpt;
- private ConversationHistory conversationHistory = new ConversationHistory(@"C:\Users\post\Auto-GPT\auto_gpt_workspace\ai\ai_conv.txt");
- private ObservableCollection<string> statusList = new ObservableCollection<string>();
- private string _connectionText;
- public event PropertyChangedEventHandler PropertyChanged;
- protected void OnPropertyChanged(string propertyName)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- private void SetConnectionText(string value)
- {
- _connectionText = value;
- OnPropertyChanged(nameof(ConnectionText));
- }
- private Process autoGPTProcess;
- public bool IsConnected
- {
- get { return isAutoGPTConnected; }
- set { isAutoGPTConnected = value; }
- }
- public ObservableCollection<string> StatusList
- {
- get { return statusList; }
- set { statusList = value; }
- }
- public string ConnectionText { get; set; }
- public MainWindow()
- {
- InitializeComponent();
- // Set the DataContext of the MainWindow to itself so that the data bindings work
- DataContext = this;
- AddStatusOutput(conversationHistory.ConnectionStatus);
- // Load the conversation history from the file and add it to the ObservableCollection
- var previousHistory = "";
- if (File.Exists(conversationHistoryFilePath))
- {
- string[] lines = File.ReadAllLines(conversationHistoryFilePath);
- foreach (string line in lines)
- {
- previousHistory = conversationHistory.Add(line);
- }
- if (previousHistory != "")
- {
- previousHistory = "Previous session======================================================================================" + "\n"
- + previousHistory + "\n"
- + "====================================================================================================" + "\n";
- conversationHistory.AddPrevious(previousHistory);
- var temp = "";
- var status = conversationHistory.Get(ref temp);
- tbConversationHistory.Text = temp;
- AddStatusOutput(status);
- }
- }
- // make initial connection
- ConnectionText = "";
- ConnectToAutoGPT();
- conversationHistory.Add(ConnectionText);
- // Subscribe to the MainWindow_Closing event
- Closing += MainWindow_Closing;
- }
- private async Task ConnectToAutoGPT()
- {
- string connectionText = "Connecting to Auto-GPT...";
- conversationHistory.Add(connectionText);
- // Start the Auto-GPT process
- _autoGpt = new AutoGPT(@"C:\Users\post\Auto-GPT\scripts", "main.py");
- _autoGpt.Connect();
- string output = "";
- bool isNewSpeaker = true;
- string speaker = "Auto-GPT: ";
- while (!_autoGpt.GetOutput().Contains(_autoGpt.GetPrompt()))
- {
- output = _autoGpt.GetOutput();
- tbConversationHistory.Text = conversationHistory.Add(output, speaker);
- if (isNewSpeaker)
- {
- isNewSpeaker = false;
- speaker = "";
- }
- await Task.Delay(100);
- }
- ConnectionText = "Auto-GPT connected.";
- OnPropertyChanged(nameof(ConnectionText));
- }
- //private async Task<string> WaitForAutoGPTConnection()
- //{
- // string connectionText = "";
- // while (connectionText == "")
- // {
- // connectionText = await GetAutoGPTResponse("");
- // }
- // return connectionText;
- //}
- private async Task ReadFromAutoGPTProcess()
- {
- while (true)
- {
- string output = await autoGPT.GetOutputAsync();
- if (string.IsNullOrEmpty(output))
- {
- break;
- }
- conversationHistory.Add("Auto-GPT: " + output);
- }
- }
- private static string RemoveEscapeCodes(string input)
- {
- return Regex.Replace(input, @"\x1B\[[^@-~]*[@-~]", "");
- }
- private void AddStatusOutput(string text)
- {
- string cleanText = RemoveEscapeCodes(text);
- Application.Current.Dispatcher.Invoke(() =>
- {
- StatusList.Add(cleanText);
- OnPropertyChanged(nameof(StatusList));
- });
- }
- private Process StartAutoGPTProcess()
- {
- AddStatusOutput("Starting the Auto-GPT process");
- Process process = new Process();
- process.StartInfo.FileName = "python";
- process.StartInfo.Arguments = @"C:\Users\post\Auto-GPT\scripts\main.py";
- process.StartInfo.WorkingDirectory = @"C:\Users\post\Auto-GPT\scripts";
- process.StartInfo.RedirectStandardInput = true;
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.CreateNoWindow = true;
- process.StartInfo.UseShellExecute = false;
- process.EnableRaisingEvents = true;
- process.Exited += Process_Exited;
- process.Start();
- return process;
- }
- private void Process_Exited(object sender, EventArgs e)
- {
- if (autoGPTProcess != null && !autoGPTProcess.HasExited)
- {
- autoGPTProcess.Kill();
- }
- autoGPTProcess?.Dispose();
- autoGPTProcess = null;
- ConnectionText = "Auto-GPT disconnected.";
- AddStatusOutput(ConnectionText);
- }
- private async void btnSubmit_Click(object sender, RoutedEventArgs e)
- {
- // Get the user's input from the text box
- string input = UserInputTextBox.Text.Trim();
- if (!string.IsNullOrEmpty(input))
- {
- // Add the user's input to the conversation history
- tbConversationHistory.Text = conversationHistory.Add(input);
- // Send the input to AutoGPT
- _autoGpt.SendInput(input);
- // Wait for the prompt to appear
- string output = "";
- while (!output.Contains(_autoGpt.GetPrompt()))
- {
- await Task.Delay(100);
- output = _autoGpt.GetOutput();
- }
- // Get the response from AutoGPT
- output = "";
- while (!output.Contains(_autoGpt.GetPrompt()))
- {
- _autoGpt.SendInput("");
- await Task.Delay(100);
- output = _autoGpt.GetOutput();
- }
- string response = output.Replace(_autoGpt.GetPrompt(), "").Trim();
- // Add the Auto-GPT response to the conversation history
- conversationHistory.Add(response);
- // Update the conversation history text box and clear the user's input
- tbConversationHistory.Text = conversationHistory.Get();
- UserInputTextBox.Text = "";
- }
- }
- private async Task<string> ReadFromAutoGPTProcess()
- {
- string response = "";
- while (!autoGPTProcess.StandardOutput.EndOfStream)
- {
- string line = await autoGPTProcess.StandardOutput.ReadLineAsync();
- AddStatusOutput(line);
- response += line + "\n";
- }
- return response;
- }
- private void MainWindow_Closing(object sender, CancelEventArgs e)
- {
- // Write the conversation history to the file
- conversationHistory.Persist();
- }
- }
- }
- using System;
- using System.Diagnostics;
- using System.Threading.Tasks;
- namespace GPTAgent
- {
- public class AutoGPT : IDisposable
- {
- private readonly Process _process;
- private readonly TaskCompletionSource<bool> _processExitedTcs = new TaskCompletionSource<bool>();
- private readonly string _initialPrompt = "Input:";
- private readonly object _outputLock = new object();
- private readonly string[] _outputBuffer = new string[100];
- private int _outputBufferIndex = 0;
- public AutoGPT(string workingDirectory, string command)
- {
- var startInfo = new ProcessStartInfo
- {
- FileName = "python",
- Arguments = command,
- WorkingDirectory = workingDirectory,
- RedirectStandardInput = true,
- RedirectStandardOutput = true,
- CreateNoWindow = true,
- UseShellExecute = false
- };
- _process = new Process { StartInfo = startInfo };
- _process.EnableRaisingEvents = true;
- _process.Exited += Process_Exited;
- }
- public void Connect()
- {
- lock (_outputLock)
- {
- _outputBufferIndex = 0;
- }
- _process.Start();
- // Wait for the process to exit
- _processExitedTcs.Task.Wait();
- // Reset the buffer
- lock (_outputLock)
- {
- _outputBufferIndex = 0;
- }
- }
- public void Dispose()
- {
- _process.Dispose();
- _processExitedTcs.TrySetResult(true);
- }
- public void SendInput(string input)
- {
- _process.StandardInput.WriteLine(input);
- }
- public string GetPrompt()
- {
- return _initialPrompt;
- }
- public string GetOutput()
- {
- lock (_outputLock)
- {
- return string.Join(Environment.NewLine, _outputBuffer);
- }
- }
- private void Process_Exited(object sender, EventArgs e)
- {
- _processExitedTcs.TrySetResult(true);
- }
- private async Task ReadOutputAsync()
- {
- while (!_process.HasExited)
- {
- string output = await _process.StandardOutput.ReadLineAsync();
- if (output == null) break;
- lock (_outputLock)
- {
- _outputBuffer[_outputBufferIndex] = output;
- _outputBufferIndex = (_outputBufferIndex + 1) % _outputBuffer.Length;
- }
- }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using System.Windows;
- namespace InterActor
- {
- public class ConversationHistory
- {
- private string _conversationHistory;
- private string conversationHistoryFilePath;
- private string lastText;
- private string previous;
- private string previousSession;
- public string ConnectionStatus { get; set; }
- public ConversationHistory(string pConversationHistoryFilePath)
- {
- conversationHistoryFilePath = pConversationHistoryFilePath;
- ConnectionStatus = Load(conversationHistoryFilePath);
- }
- //Loads the content of conversationHistoryFilePath into _conversationHistory
- //returns the status of the process
- public string Load(string conversationHistoryFilePath)
- {
- if (File.Exists(conversationHistoryFilePath))
- {
- string[] lines = File.ReadAllLines(conversationHistoryFilePath);
- foreach (string line in lines)
- {
- Add(line);
- }
- }
- else
- {
- return "The Conversation History file does not exist";
- }
- return "Loaded Conversation History";
- }
- //Add - adds new text to the _conversationHistory member however it excludes some newline values such as any of the "thinking" derivatives
- //speaker is an optional when a set of lines begins for a new speaker.
- //returns the _conversationHistory but adding in a value for "thinking" or other discardable values
- //it will be the previous text plus possibly
- public string Add(string newText, string speaker = "")
- {
- lastText = newText;
- var displayText = "";
- if (!string.IsNullOrEmpty(newText))
- {
- if (newText.Contains("| Thinking...") ||
- newText.Contains("\\ Thinking...") ||
- newText.Contains("/ Thinking...") ||
- newText.Contains("- Thinking..."))
- {
- //nothing to add but return
- displayText = _conversationHistory + Environment.NewLine;
- displayText = _conversationHistory + displayText;
- return previous + displayText;
- }
- else
- {
- string cleanText = RemoveEscapeCodes(newText);
- string message;
- if (speaker != "")
- {
- string timestamp = DateTime.Now.ToString("hh:mm:ss tt");
- message = $"{timestamp} {speaker}: {cleanText}";
- }
- else
- {
- message = cleanText;
- }
- message = message.Trim();
- if (message != "")
- {
- _conversationHistory = _conversationHistory + Environment.NewLine;
- _conversationHistory = _conversationHistory + message;
- }
- displayText = _conversationHistory;
- }
- }
- previous = previousSession + Environment.NewLine + _conversationHistory;
- return previous + displayText;
- }
- //AddPrevious - adds new text to the previous member however it excludes some newline values such as any of the "thinking" derivatives
- //Adds boundary lines to distinguish it.
- public void AddPrevious(string newText)
- {
- lastText = newText;
- if (!string.IsNullOrEmpty(newText))
- {
- if (newText.Contains("| Thinking...") ||
- newText.Contains("\\ Thinking...") ||
- newText.Contains("/ Thinking...") ||
- newText.Contains("- Thinking..."))
- {
- // nothing to add, just return
- return;
- }
- else
- {
- string cleanText = RemoveEscapeCodes(newText);
- string message;
- message = cleanText;
- message.Trim();
- if (message != "")
- {
- // add newText to temporary previousSession variable
- previousSession = previousSession + Environment.NewLine + message;
- }
- }
- }
- }
- //returns lastText in order that the "thinking options can be cycled in display but not included in the Get value.
- public string Get(ref string value)
- {
- value = _conversationHistory;
- return lastText;
- }
- public void Persist()
- {
- // Write the message to the conversation history file
- using (StreamWriter writer = File.AppendText(conversationHistoryFilePath))
- {
- writer.WriteLine(_conversationHistory);
- }
- }
- private static string RemoveEscapeCodes(string input)
- {
- return Regex.Replace(input, @"\x1B\[[^@-~]*[@-~]", "");
- }
- }
- }
- <Window x:Class="GPTAgent.MainWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- Title="Auto GPT Agent" Height="950">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="112*"/>
- <ColumnDefinition Width="29*"/>
- <ColumnDefinition Width="83*"/>
- <ColumnDefinition Width="0*"/>
- </Grid.ColumnDefinitions>
- <Grid.RowDefinitions>
- <RowDefinition Height="50"/>
- <RowDefinition Height="150"/>
- <RowDefinition Height="300"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <StackPanel Grid.Row="0" Height="50" Orientation="Horizontal" Grid.ColumnSpan="3">
- <Label Content="Enter your message:" Width="500" VerticalAlignment="Bottom"/>
- <Button x:Name="btnSubmit" Content="Submit" Height="20" Width="147" Click="btnSubmit_Click" />
- <TextBlock x:Name="AutoGPTStatus" Width="400" Margin="10,10"></TextBlock>
- </StackPanel>
- <TextBox x:Name="UserInputTextBox" Grid.Row="1" Height="140" Margin="10,0,10,0" VerticalAlignment="Center" TextWrapping="Wrap" AcceptsReturn="True" AcceptsTab="True" Grid.ColumnSpan="3"/>
- <ScrollViewer Grid.Row="2" Grid.ColumnSpan="3" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
- <TextBox Grid.Row="2" x:Name="tbConversationHistory" Grid.ColumnSpan="3"
- TextWrapping="Wrap" IsReadOnly="True" VerticalScrollBarVisibility="Auto"
- IsReadOnlyCaretVisible="False" />
- </ScrollViewer>
- <ListBox x:Name="StatusListBox" Grid.Row="3" Grid.ColumnSpan="3" ItemsSource="{Binding StatusList}" />
- </Grid>
- </Window>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement