Advertisement
andyseabrook

GPTAgent

Apr 15th, 2023
998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.74 KB | Source Code | 0 0
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using System.Windows;
  6. using System.Diagnostics;
  7. using System.ComponentModel;
  8. using System.Text.RegularExpressions;
  9.  
  10. using InterActor;
  11.  
  12. namespace GPTAgent
  13. {
  14.     public partial class MainWindow : Window, INotifyPropertyChanged
  15.     {
  16.  
  17.         private bool isAutoGPTConnected = false;
  18.         private string conversationHistoryFilePath = @"C:\Users\post\Auto-GPT\auto_gpt_workspace\ai\ai_conv.txt";
  19.         private AutoGPT _autoGpt;
  20.  
  21.         private ConversationHistory conversationHistory = new ConversationHistory(@"C:\Users\post\Auto-GPT\auto_gpt_workspace\ai\ai_conv.txt");
  22.  
  23.         private ObservableCollection<string> statusList = new ObservableCollection<string>();
  24.  
  25.         private string _connectionText;
  26.  
  27.         public event PropertyChangedEventHandler PropertyChanged;
  28.  
  29.         protected void OnPropertyChanged(string propertyName)
  30.         {
  31.             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  32.         }
  33.  
  34.         private void SetConnectionText(string value)
  35.         {
  36.             _connectionText = value;
  37.             OnPropertyChanged(nameof(ConnectionText));
  38.         }
  39.  
  40.         private Process autoGPTProcess;
  41.  
  42.         public bool IsConnected
  43.         {
  44.             get { return isAutoGPTConnected; }
  45.             set { isAutoGPTConnected = value; }
  46.         }
  47.  
  48.         public ObservableCollection<string> StatusList
  49.         {
  50.             get { return statusList; }
  51.             set { statusList = value; }
  52.         }
  53.  
  54.         public string ConnectionText { get; set; }
  55.  
  56.  
  57.         public MainWindow()
  58.         {
  59.             InitializeComponent();
  60.  
  61.             // Set the DataContext of the MainWindow to itself so that the data bindings work
  62.             DataContext = this;
  63.  
  64.             AddStatusOutput(conversationHistory.ConnectionStatus);
  65.  
  66.             // Load the conversation history from the file and add it to the ObservableCollection
  67.             var previousHistory = "";
  68.             if (File.Exists(conversationHistoryFilePath))
  69.             {
  70.                 string[] lines = File.ReadAllLines(conversationHistoryFilePath);
  71.                 foreach (string line in lines)
  72.                 {
  73.                     previousHistory = conversationHistory.Add(line);
  74.                 }
  75.  
  76.                 if (previousHistory != "")
  77.                 {
  78.                     previousHistory = "Previous session======================================================================================" + "\n"
  79.                         + previousHistory + "\n"
  80.                         + "====================================================================================================" + "\n";
  81.                     conversationHistory.AddPrevious(previousHistory);
  82.                     var temp = "";
  83.                     var status = conversationHistory.Get(ref temp);
  84.                     tbConversationHistory.Text = temp;
  85.                     AddStatusOutput(status);
  86.                 }
  87.             }
  88.  
  89.             // make initial connection
  90.             ConnectionText = "";
  91.             ConnectToAutoGPT();
  92.             conversationHistory.Add(ConnectionText);
  93.  
  94.  
  95.             // Subscribe to the MainWindow_Closing event
  96.             Closing += MainWindow_Closing;
  97.         }
  98.  
  99.         private async Task ConnectToAutoGPT()
  100.         {
  101.             string connectionText = "Connecting to Auto-GPT...";
  102.             conversationHistory.Add(connectionText);
  103.  
  104.             // Start the Auto-GPT process
  105.             _autoGpt = new AutoGPT(@"C:\Users\post\Auto-GPT\scripts", "main.py");
  106.             _autoGpt.Connect();
  107.  
  108.             string output = "";
  109.             bool isNewSpeaker = true;
  110.             string speaker = "Auto-GPT: ";
  111.             while (!_autoGpt.GetOutput().Contains(_autoGpt.GetPrompt()))
  112.             {
  113.                 output = _autoGpt.GetOutput();
  114.                 tbConversationHistory.Text = conversationHistory.Add(output, speaker);
  115.                 if (isNewSpeaker)
  116.                 {
  117.                     isNewSpeaker = false;
  118.                     speaker = "";
  119.                 }
  120.                 await Task.Delay(100);
  121.             }
  122.  
  123.             ConnectionText = "Auto-GPT connected.";
  124.  
  125.             OnPropertyChanged(nameof(ConnectionText));
  126.         }
  127.  
  128.         //private async Task<string> WaitForAutoGPTConnection()
  129.         //{
  130.         //    string connectionText = "";
  131.         //    while (connectionText == "")
  132.         //    {
  133.         //        connectionText = await GetAutoGPTResponse("");
  134.         //    }
  135.         //    return connectionText;
  136.         //}
  137.         private async Task ReadFromAutoGPTProcess()
  138.         {
  139.             while (true)
  140.             {
  141.                 string output = await autoGPT.GetOutputAsync();
  142.                 if (string.IsNullOrEmpty(output))
  143.                 {
  144.                     break;  
  145.                 }
  146.  
  147.                 conversationHistory.Add("Auto-GPT: " + output);
  148.             }
  149.         }
  150.  
  151.         private static string RemoveEscapeCodes(string input)
  152.         {
  153.             return Regex.Replace(input, @"\x1B\[[^@-~]*[@-~]", "");
  154.         }
  155.  
  156.         private void AddStatusOutput(string text)
  157.         {
  158.             string cleanText = RemoveEscapeCodes(text);
  159.  
  160.             Application.Current.Dispatcher.Invoke(() =>
  161.             {
  162.                 StatusList.Add(cleanText);
  163.                 OnPropertyChanged(nameof(StatusList));
  164.             });
  165.         }
  166.         private Process StartAutoGPTProcess()
  167.         {
  168.             AddStatusOutput("Starting the Auto-GPT process");
  169.             Process process = new Process();
  170.             process.StartInfo.FileName = "python";
  171.             process.StartInfo.Arguments = @"C:\Users\post\Auto-GPT\scripts\main.py";
  172.             process.StartInfo.WorkingDirectory = @"C:\Users\post\Auto-GPT\scripts";
  173.             process.StartInfo.RedirectStandardInput = true;
  174.             process.StartInfo.RedirectStandardOutput = true;
  175.             process.StartInfo.CreateNoWindow = true;
  176.             process.StartInfo.UseShellExecute = false;
  177.  
  178.             process.EnableRaisingEvents = true;
  179.             process.Exited += Process_Exited;
  180.  
  181.             process.Start();
  182.  
  183.             return process;
  184.         }
  185.  
  186.         private void Process_Exited(object sender, EventArgs e)
  187.         {
  188.             if (autoGPTProcess != null && !autoGPTProcess.HasExited)
  189.             {
  190.                 autoGPTProcess.Kill();
  191.             }
  192.             autoGPTProcess?.Dispose();
  193.             autoGPTProcess = null;
  194.  
  195.             ConnectionText = "Auto-GPT disconnected.";
  196.             AddStatusOutput(ConnectionText);
  197.         }
  198.  
  199.         private async void btnSubmit_Click(object sender, RoutedEventArgs e)
  200.         {
  201.             // Get the user's input from the text box
  202.             string input = UserInputTextBox.Text.Trim();
  203.  
  204.             if (!string.IsNullOrEmpty(input))
  205.             {
  206.                 // Add the user's input to the conversation history
  207.                 tbConversationHistory.Text = conversationHistory.Add(input);
  208.  
  209.                 // Send the input to AutoGPT
  210.                 _autoGpt.SendInput(input);
  211.  
  212.                 // Wait for the prompt to appear
  213.                 string output = "";
  214.                 while (!output.Contains(_autoGpt.GetPrompt()))
  215.                 {
  216.                     await Task.Delay(100);
  217.                     output = _autoGpt.GetOutput();
  218.                 }
  219.  
  220.                 // Get the response from AutoGPT
  221.                 output = "";
  222.                 while (!output.Contains(_autoGpt.GetPrompt()))
  223.                 {
  224.                     _autoGpt.SendInput("");
  225.                     await Task.Delay(100);
  226.                     output = _autoGpt.GetOutput();
  227.                 }
  228.                 string response = output.Replace(_autoGpt.GetPrompt(), "").Trim();
  229.  
  230.                 // Add the Auto-GPT response to the conversation history
  231.                 conversationHistory.Add(response);
  232.  
  233.                 // Update the conversation history text box and clear the user's input
  234.                 tbConversationHistory.Text = conversationHistory.Get();
  235.                 UserInputTextBox.Text = "";
  236.             }
  237.         }
  238.  
  239.  
  240.  
  241.         private async Task<string> ReadFromAutoGPTProcess()
  242.         {
  243.             string response = "";
  244.  
  245.             while (!autoGPTProcess.StandardOutput.EndOfStream)
  246.             {
  247.                 string line = await autoGPTProcess.StandardOutput.ReadLineAsync();
  248.                 AddStatusOutput(line);
  249.                 response += line + "\n";
  250.             }
  251.  
  252.             return response;
  253.         }
  254.  
  255.         private void MainWindow_Closing(object sender, CancelEventArgs e)
  256.         {
  257.             // Write the conversation history to the file
  258.             conversationHistory.Persist();
  259.         }
  260.  
  261.     }
  262. }
  263.  
  264. using System;
  265. using System.Diagnostics;
  266. using System.Threading.Tasks;
  267.  
  268. namespace GPTAgent
  269. {
  270.     public class AutoGPT : IDisposable
  271.     {
  272.         private readonly Process _process;
  273.         private readonly TaskCompletionSource<bool> _processExitedTcs = new TaskCompletionSource<bool>();
  274.         private readonly string _initialPrompt = "Input:";
  275.  
  276.         private readonly object _outputLock = new object();
  277.         private readonly string[] _outputBuffer = new string[100];
  278.         private int _outputBufferIndex = 0;
  279.  
  280.         public AutoGPT(string workingDirectory, string command)
  281.         {
  282.             var startInfo = new ProcessStartInfo
  283.             {
  284.                 FileName = "python",
  285.                 Arguments = command,
  286.                 WorkingDirectory = workingDirectory,
  287.                 RedirectStandardInput = true,
  288.                 RedirectStandardOutput = true,
  289.                 CreateNoWindow = true,
  290.                 UseShellExecute = false
  291.             };
  292.  
  293.             _process = new Process { StartInfo = startInfo };
  294.             _process.EnableRaisingEvents = true;
  295.             _process.Exited += Process_Exited;
  296.         }
  297.  
  298.         public void Connect()
  299.         {
  300.             lock (_outputLock)
  301.             {
  302.                 _outputBufferIndex = 0;
  303.             }
  304.  
  305.             _process.Start();
  306.  
  307.             // Wait for the process to exit
  308.             _processExitedTcs.Task.Wait();
  309.  
  310.             // Reset the buffer
  311.             lock (_outputLock)
  312.             {
  313.                 _outputBufferIndex = 0;
  314.             }
  315.         }
  316.  
  317.         public void Dispose()
  318.         {
  319.             _process.Dispose();
  320.             _processExitedTcs.TrySetResult(true);
  321.         }
  322.  
  323.         public void SendInput(string input)
  324.         {
  325.             _process.StandardInput.WriteLine(input);
  326.         }
  327.  
  328.         public string GetPrompt()
  329.         {
  330.             return _initialPrompt;
  331.         }
  332.  
  333.         public string GetOutput()
  334.         {
  335.             lock (_outputLock)
  336.             {
  337.                 return string.Join(Environment.NewLine, _outputBuffer);
  338.             }
  339.         }
  340.  
  341.         private void Process_Exited(object sender, EventArgs e)
  342.         {
  343.             _processExitedTcs.TrySetResult(true);
  344.         }
  345.  
  346.         private async Task ReadOutputAsync()
  347.         {
  348.             while (!_process.HasExited)
  349.             {
  350.                 string output = await _process.StandardOutput.ReadLineAsync();
  351.                 if (output == null) break;
  352.  
  353.                 lock (_outputLock)
  354.                 {
  355.                     _outputBuffer[_outputBufferIndex] = output;
  356.                     _outputBufferIndex = (_outputBufferIndex + 1) % _outputBuffer.Length;
  357.                 }
  358.             }
  359.         }
  360.     }
  361. }
  362.  
  363. using System;
  364. using System.Collections.Generic;
  365. using System.IO;
  366. using System.Linq;
  367. using System.Text;
  368. using System.Text.RegularExpressions;
  369. using System.Threading.Tasks;
  370. using System.Windows;
  371.  
  372. namespace InterActor
  373. {
  374.     public class ConversationHistory
  375.     {
  376.  
  377.         private string _conversationHistory;
  378.         private string conversationHistoryFilePath;
  379.         private string lastText;
  380.         private string previous;
  381.         private string previousSession;
  382.  
  383.         public string ConnectionStatus { get; set; }
  384.  
  385.         public ConversationHistory(string pConversationHistoryFilePath)
  386.         {
  387.             conversationHistoryFilePath = pConversationHistoryFilePath;
  388.             ConnectionStatus = Load(conversationHistoryFilePath);
  389.         }
  390.  
  391.         //Loads the content of conversationHistoryFilePath into _conversationHistory
  392.         //returns the status of the process
  393.         public string Load(string conversationHistoryFilePath)
  394.         {
  395.             if (File.Exists(conversationHistoryFilePath))
  396.             {
  397.                 string[] lines = File.ReadAllLines(conversationHistoryFilePath);
  398.                 foreach (string line in lines)
  399.                 {
  400.                     Add(line);
  401.                 }
  402.             }
  403.             else
  404.             {
  405.                 return "The Conversation History file does not exist";
  406.             }
  407.             return "Loaded Conversation History";
  408.         }
  409.  
  410.         //Add - adds new text to the _conversationHistory member however it excludes some newline values such as any of the "thinking" derivatives
  411.         //speaker is an optional when a set of lines begins for a new speaker.
  412.         //returns the _conversationHistory but adding in a value for "thinking" or other discardable values
  413.         //it will be the previous text plus possibly
  414.         public string Add(string newText, string speaker = "")
  415.         {
  416.             lastText = newText;
  417.             var displayText = "";
  418.             if (!string.IsNullOrEmpty(newText))
  419.             {
  420.                 if (newText.Contains("| Thinking...") ||
  421.                     newText.Contains("\\ Thinking...") ||
  422.                     newText.Contains("/ Thinking...") ||
  423.                     newText.Contains("- Thinking..."))
  424.                 {
  425.                     //nothing to add but return
  426.                     displayText = _conversationHistory + Environment.NewLine;
  427.                     displayText = _conversationHistory + displayText;
  428.                     return previous + displayText;
  429.                 }
  430.                 else
  431.                 {
  432.                     string cleanText = RemoveEscapeCodes(newText);
  433.                     string message;
  434.                     if (speaker != "")
  435.                     {
  436.                         string timestamp = DateTime.Now.ToString("hh:mm:ss tt");
  437.                         message = $"{timestamp} {speaker}: {cleanText}";
  438.                     }
  439.                     else
  440.                     {
  441.                         message = cleanText;
  442.                     }
  443.                     message = message.Trim();
  444.                     if (message != "")
  445.                     {
  446.                         _conversationHistory = _conversationHistory + Environment.NewLine;
  447.                         _conversationHistory = _conversationHistory + message;
  448.                     }
  449.                     displayText = _conversationHistory;
  450.                 }
  451.             }
  452.             previous = previousSession + Environment.NewLine + _conversationHistory;
  453.             return previous + displayText;
  454.         }
  455.  
  456.         //AddPrevious - adds new text to the previous member however it excludes some newline values such as any of the "thinking" derivatives
  457.         //Adds boundary lines to distinguish it.
  458.         public void AddPrevious(string newText)
  459.         {
  460.             lastText = newText;
  461.             if (!string.IsNullOrEmpty(newText))
  462.             {
  463.                 if (newText.Contains("| Thinking...") ||
  464.                     newText.Contains("\\ Thinking...") ||
  465.                     newText.Contains("/ Thinking...") ||
  466.                     newText.Contains("- Thinking..."))
  467.                 {
  468.                     // nothing to add, just return
  469.                     return;
  470.                 }
  471.                 else
  472.                 {
  473.                     string cleanText = RemoveEscapeCodes(newText);
  474.                     string message;
  475.                     message = cleanText;
  476.                     message.Trim();
  477.                     if (message != "")
  478.                     {
  479.                         // add newText to temporary previousSession variable
  480.                         previousSession = previousSession + Environment.NewLine + message;
  481.                     }
  482.                 }
  483.             }
  484.         }
  485.  
  486.         //returns lastText in order that the "thinking options can be cycled in display but not included in the Get value.
  487.         public string Get(ref string value)
  488.         {
  489.             value = _conversationHistory;
  490.             return lastText;
  491.         }
  492.  
  493.         public void Persist()
  494.         {
  495.  
  496.             // Write the message to the conversation history file
  497.             using (StreamWriter writer = File.AppendText(conversationHistoryFilePath))
  498.             {
  499.                 writer.WriteLine(_conversationHistory);
  500.             }
  501.         }
  502.  
  503.         private static string RemoveEscapeCodes(string input)
  504.         {
  505.             return Regex.Replace(input, @"\x1B\[[^@-~]*[@-~]", "");
  506.         }
  507.     }
  508. }
  509.  
  510. <Window x:Class="GPTAgent.MainWindow"
  511.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  512.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  513.         Title="Auto GPT Agent" Height="950">
  514.     <Grid>
  515.         <Grid.ColumnDefinitions>
  516.             <ColumnDefinition Width="112*"/>
  517.             <ColumnDefinition Width="29*"/>
  518.             <ColumnDefinition Width="83*"/>
  519.             <ColumnDefinition Width="0*"/>
  520.         </Grid.ColumnDefinitions>
  521.         <Grid.RowDefinitions>
  522.             <RowDefinition Height="50"/>
  523.             <RowDefinition Height="150"/>
  524.             <RowDefinition Height="300"/>
  525.             <RowDefinition Height="*"/>
  526.         </Grid.RowDefinitions>
  527.         <StackPanel Grid.Row="0" Height="50" Orientation="Horizontal" Grid.ColumnSpan="3">
  528.             <Label Content="Enter your message:" Width="500" VerticalAlignment="Bottom"/>
  529.             <Button x:Name="btnSubmit" Content="Submit" Height="20" Width="147" Click="btnSubmit_Click" />
  530.             <TextBlock x:Name="AutoGPTStatus" Width="400" Margin="10,10"></TextBlock>
  531.         </StackPanel>
  532.         <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"/>
  533.         <ScrollViewer Grid.Row="2" Grid.ColumnSpan="3" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
  534.             <TextBox Grid.Row="2" x:Name="tbConversationHistory" Grid.ColumnSpan="3"
  535.          TextWrapping="Wrap" IsReadOnly="True" VerticalScrollBarVisibility="Auto"
  536.          IsReadOnlyCaretVisible="False" />
  537.         </ScrollViewer>
  538.  
  539.  
  540.         <ListBox x:Name="StatusListBox" Grid.Row="3" Grid.ColumnSpan="3" ItemsSource="{Binding StatusList}" />
  541.  
  542.  
  543.     </Grid>
  544. </Window>
  545.  
  546.  
  547.  
Tags: C# wpf AutoGPT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement