├── .vscode
└── settings.json
├── assets
└── README
│ ├── image.png
│ ├── image-1.png
│ ├── image-2.png
│ ├── image-3.png
│ ├── image-4.png
│ ├── image-5.png
│ └── image-6.png
├── PromptPlayground
├── Assets
│ ├── logo.ico
│ └── logo.png
├── ViewModels
│ ├── ViewModelBase.cs
│ ├── ConfigViewModels
│ │ ├── LLM
│ │ │ ├── ILLMConfigViewModel.cs
│ │ │ ├── OpenAIConfigViewModel.cs
│ │ │ ├── DashScopeConfigViewModel.cs
│ │ │ ├── AzureOpenAIConfigViewModel.cs
│ │ │ ├── LLamaSharpConfigViewModel.cs
│ │ │ └── BaiduConfigViewModel.cs
│ │ ├── IConfigViewModel.cs
│ │ └── ConfigAttribute.cs
│ ├── ResultsViewModel.cs
│ ├── StatusViewModel.cs
│ ├── AboutViewModel.cs
│ ├── MainViewModel.cs
│ ├── GenerateResult.cs
│ ├── VariablesViewModel.cs
│ ├── PluginViewModel.cs
│ ├── PluginsViewModel.cs
│ ├── ConfigViewModel.cs
│ └── SemanticFunctionViewModel.cs
├── Constants.cs
├── Views
│ ├── MainWindow.axaml.cs
│ ├── ResultsView.axaml.cs
│ ├── PluginsView.axaml.cs
│ ├── MainWindow.axaml
│ ├── AboutView.axaml.cs
│ ├── ConfigWindow.axaml.cs
│ ├── VariablesWindows.axaml.cs
│ ├── EditorView.axaml.cs
│ ├── VariablesWindows.axaml
│ ├── AboutView.axaml
│ ├── MainView.axaml
│ ├── PluginsView.axaml
│ ├── EditorView.axaml
│ ├── ConfigWindow.axaml
│ ├── ResultsView.axaml
│ └── MainView.axaml.cs
├── Messages
│ ├── CopyTextMessage.cs
│ ├── FunctionCreateMessage.cs
│ ├── FunctionSelectedMessage.cs
│ ├── PluginOpenMessage.cs
│ ├── FunctionOpenMessage.cs
│ ├── CloseFunctionMessage.cs
│ ├── ConfigurationRequestMessage.cs
│ ├── RequestVariablesMessage.cs
│ ├── ConfirmRequestMessage.cs
│ ├── FileOrFolderPathMessage.cs
│ └── NotificationMessage.cs
├── App.axaml
├── Services
│ ├── Models
│ │ └── GenerationResultStore.cs
│ ├── ProfileService.cs
│ ├── DbStore.cs
│ └── PromptService.cs
├── Converters
│ ├── NullToVisibilityConverter.cs
│ └── StringToBooleanConverter.cs
├── Program.cs
├── app.manifest
├── App.axaml.cs
├── Migrations
│ ├── 20240221112923_GenerationResultStore.cs
│ ├── DbStoreModelSnapshot.cs
│ └── 20240221112923_GenerationResultStore.Designer.cs
├── Behaviors
│ └── DocumentTextBindingBehavior.cs
└── PromptPlayground.csproj
├── Directory.Build.props
├── LICENSE
├── README_CN.md
├── PromptPlayground.sln
├── CONTRIBUTING.md
├── README.md
├── .gitattributes
├── installer.iss
├── CODE_OF_CONDUCT.md
└── .gitignore
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "dotnet.defaultSolution": "PromptPlayground.sln"
3 | }
--------------------------------------------------------------------------------
/assets/README/image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image.png
--------------------------------------------------------------------------------
/assets/README/image-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-1.png
--------------------------------------------------------------------------------
/assets/README/image-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-2.png
--------------------------------------------------------------------------------
/assets/README/image-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-3.png
--------------------------------------------------------------------------------
/assets/README/image-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-4.png
--------------------------------------------------------------------------------
/assets/README/image-5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-5.png
--------------------------------------------------------------------------------
/assets/README/image-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/assets/README/image-6.png
--------------------------------------------------------------------------------
/PromptPlayground/Assets/logo.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/PromptPlayground/Assets/logo.ico
--------------------------------------------------------------------------------
/PromptPlayground/Assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xbotter/PromptPlayground/HEAD/PromptPlayground/Assets/logo.png
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ViewModelBase.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 |
3 | namespace PromptPlayground.ViewModels;
4 |
5 | public class ViewModelBase : ObservableObject
6 | {
7 | }
8 |
--------------------------------------------------------------------------------
/PromptPlayground/Constants.cs:
--------------------------------------------------------------------------------
1 | namespace PromptPlayground
2 | {
3 | internal static class Constants
4 | {
5 | public const string SkPrompt = "skprompt.txt";
6 | public const string SkConfig = "config.json";
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/MainWindow.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 |
3 | namespace PromptPlayground.Views;
4 |
5 | public partial class MainWindow : Window
6 | {
7 | public MainWindow()
8 | {
9 | InitializeComponent();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/CopyTextMessage.cs:
--------------------------------------------------------------------------------
1 | namespace PromptPlayground.Services
2 | {
3 | public class CopyTextMessage
4 | {
5 | public CopyTextMessage(string text)
6 | {
7 | this.Text = text;
8 | }
9 |
10 | public string Text { get; set; }
11 | }
12 | }
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | enable
4 | 0.7.1
5 |
6 |
7 |
8 | none
9 | false
10 |
11 |
12 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/FunctionCreateMessage.cs:
--------------------------------------------------------------------------------
1 | namespace PromptPlayground.ViewModels
2 | {
3 | public class FunctionCreateMessage
4 | {
5 | public FunctionCreateMessage(SemanticFunctionViewModel? function = null)
6 | {
7 | Function = function;
8 | }
9 |
10 | public SemanticFunctionViewModel? Function { get; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/FunctionSelectedMessage.cs:
--------------------------------------------------------------------------------
1 | using PromptPlayground.ViewModels;
2 |
3 | namespace PromptPlayground.Messages
4 | {
5 | public class FunctionSelectedMessage
6 | {
7 | public SemanticFunctionViewModel Function { get; set; }
8 |
9 | public FunctionSelectedMessage(SemanticFunctionViewModel viewModel)
10 | {
11 | this.Function = viewModel;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/PluginOpenMessage.cs:
--------------------------------------------------------------------------------
1 | using PromptPlayground.Messages;
2 |
3 | namespace PromptPlayground.ViewModels
4 | {
5 | public class PluginOpenMessage : FileOrFolderPathMessage
6 | {
7 | public PluginOpenMessage(string path) : base(path) { }
8 | }
9 |
10 | public class PluginCloseMessage : FileOrFolderPathMessage
11 | {
12 | public PluginCloseMessage(string path) : base(path) { }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/ResultsView.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Controls.Notifications;
4 | using Avalonia.Interactivity;
5 | using CommunityToolkit.Mvvm.Messaging;
6 | using PromptPlayground.Services;
7 | using PromptPlayground.ViewModels;
8 | using System;
9 |
10 | namespace PromptPlayground.Views;
11 |
12 | public partial class ResultsView : UserControl
13 | {
14 | public ResultsView()
15 | {
16 | InitializeComponent();
17 | }
18 | }
--------------------------------------------------------------------------------
/PromptPlayground/Messages/FunctionOpenMessage.cs:
--------------------------------------------------------------------------------
1 | using PromptPlayground.Messages;
2 |
3 | namespace PromptPlayground.ViewModels
4 | {
5 | public class FunctionOpenMessage : FileOrFolderPathMessage
6 | {
7 | public FunctionOpenMessage(string folder) : base(folder)
8 | {
9 |
10 | }
11 | }
12 |
13 | public class FunctionSavedMessage : FileOrFolderPathMessage
14 | {
15 | public FunctionSavedMessage(string folder) : base(folder)
16 | {
17 |
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/ILLMConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using PromptPlayground.Services;
3 | using System.Collections.Generic;
4 | using System.Collections.ObjectModel;
5 | using System.Linq;
6 |
7 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
8 | {
9 | public interface ILLMConfigViewModel : IConfigViewModel
10 | {
11 | public IKernelBuilder CreateKernelBuilder();
12 | public ResultTokenUsage? GetUsage(FunctionResult resultModel);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/CloseFunctionMessage.cs:
--------------------------------------------------------------------------------
1 | using PromptPlayground.ViewModels;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace PromptPlayground.Messages
9 | {
10 | public class CloseFunctionMessage
11 | {
12 | public CloseFunctionMessage(SemanticFunctionViewModel function)
13 | {
14 | Function = function;
15 | }
16 |
17 | public SemanticFunctionViewModel Function { get; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/ConfigurationRequestMessage.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.Messaging.Messages;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace PromptPlayground.Messages
9 | {
10 | public class ConfigurationRequestMessage : RequestMessage
11 | {
12 | public ConfigurationRequestMessage(string config)
13 | {
14 | Config = config;
15 | }
16 |
17 | public string Config { get; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/PluginsView.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Interactivity;
3 | using Avalonia.Platform.Storage;
4 | using PromptPlayground.ViewModels;
5 | using System;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.Views;
11 |
12 | public partial class PluginsView : UserControl
13 | {
14 | public PluginsViewModel Model => (this.DataContext as PluginsViewModel)!;
15 |
16 | public PluginsView()
17 | {
18 | InitializeComponent();
19 | this.DataContext = new PluginsViewModel();
20 | }
21 | }
--------------------------------------------------------------------------------
/PromptPlayground/App.axaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/RequestVariablesMessage.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.Messaging.Messages;
2 | using PromptPlayground.ViewModels;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace PromptPlayground.Messages
10 | {
11 | public class RequestVariablesMessage : AsyncRequestMessage
12 | {
13 | public RequestVariablesMessage(List variables)
14 | {
15 | Variables = variables;
16 | }
17 | public List Variables { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/ConfirmRequestMessage.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.Messaging.Messages;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace PromptPlayground.Messages
9 | {
10 | public class ConfirmRequestMessage : AsyncRequestMessage
11 | {
12 | public string Title { get; set; }
13 | public string? Message { get; set; }
14 | public ConfirmRequestMessage(string title, string? message)
15 | {
16 | Title = title;
17 | Message = message;
18 | }
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/PromptPlayground/Services/Models/GenerationResultStore.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace PromptPlayground.Services.Models
8 | {
9 | internal class GenerationResultStore
10 | {
11 | public long Id { get; set; }
12 | public required string FunctionPath { get; set; }
13 | public required string Text { get; set; }
14 | public required string RenderedPrompt { get; set; }
15 | public ResultTokenUsage? Usage { get; set; }
16 | public DateTime CreatedAt { get; set; }
17 | public TimeSpan Elapsed { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/MainWindow.axaml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/FileOrFolderPathMessage.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.Messaging.Messages;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace PromptPlayground.Messages
9 | {
10 | public abstract class FileOrFolderPathMessage
11 | {
12 | public string? Path { get; set; }
13 | public FileOrFolderPathMessage(string? path)
14 | {
15 | Path = path;
16 | }
17 | }
18 |
19 | public class RequestFileOpen : AsyncRequestMessage
20 | {
21 |
22 | }
23 | public class RequestFolderOpen : AsyncRequestMessage
24 | {
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/PromptPlayground/Converters/NullToVisibilityConverter.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Data.Converters;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Globalization;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace PromptPlayground.Converters
10 | {
11 | public class NullToVisibilityConverter : IValueConverter
12 | {
13 | public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
14 | {
15 | return value != null;
16 | }
17 |
18 | public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
19 | {
20 | throw new NotImplementedException();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/PromptPlayground/Messages/NotificationMessage.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace PromptPlayground.Messages
8 | {
9 | public class NotificationMessage
10 | {
11 | public enum NotificationType
12 | {
13 | Information,
14 | Success,
15 | Warning,
16 | Error
17 | }
18 | public NotificationType Level { get; set; }
19 | public string Title { get; set; }
20 | public string? Message { get; set; }
21 | public NotificationMessage(string title, string? message, NotificationType level = NotificationType.Information)
22 | {
23 | Level = level;
24 | Title = title;
25 | Message = message;
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/AboutView.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Interactivity;
4 | using Avalonia.Styling;
5 |
6 | namespace PromptPlayground.Views
7 | {
8 | public partial class AboutView : Window
9 | {
10 | public AboutView()
11 | {
12 | InitializeComponent();
13 | }
14 |
15 | public void CloseClick(object sender, RoutedEventArgs e)
16 | {
17 | this.Close();
18 | }
19 |
20 | private void ToggleTheme(object sender, RoutedEventArgs e)
21 | {
22 | var app = Application.Current;
23 | if (app is not null)
24 | {
25 | var theme = app.ActualThemeVariant;
26 | app.RequestedThemeVariant = theme == ThemeVariant.Dark ? ThemeVariant.Light : ThemeVariant.Dark;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/PromptPlayground/Program.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Projektanker.Icons.Avalonia.MaterialDesign;
3 | using Projektanker.Icons.Avalonia;
4 | using System;
5 |
6 | namespace PromptPlayground;
7 | class Program
8 | {
9 | // Initialization code. Don't use any Avalonia, third-party APIs or any
10 | // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
11 | // yet and stuff might break.
12 | [STAThread]
13 | public static void Main(string[] args) => BuildAvaloniaApp()
14 | .StartWithClassicDesktopLifetime(args);
15 |
16 | // Avalonia configuration, don't remove; also used by visual designer.
17 | public static AppBuilder BuildAvaloniaApp()
18 | {
19 | IconProvider.Current
20 | .Register();
21 | return AppBuilder.Configure()
22 | .UsePlatformDetect()
23 | .WithInterFont()
24 | .LogToTrace();
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/ConfigWindow.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Interactivity;
3 | using PromptPlayground.ViewModels;
4 | using System;
5 |
6 | namespace PromptPlayground.Views;
7 |
8 | public partial class ConfigWindow : Window
9 | {
10 | public ConfigWindow()
11 | {
12 | InitializeComponent();
13 | this.Closed += ConfigWindow_Closed;
14 | }
15 |
16 | private void ConfigWindow_Closed(object? sender, EventArgs e)
17 | {
18 | if (this.DataContext is ConfigViewModel config)
19 | {
20 | config.ReloadConfig();
21 | }
22 | }
23 |
24 | public void SaveConfig(object? sender, RoutedEventArgs e)
25 | {
26 | if (this.DataContext is ConfigViewModel config)
27 | {
28 | config.SaveConfig();
29 | }
30 | this.Close();
31 | }
32 | public void ResetConfig(object? sender, RoutedEventArgs e)
33 | {
34 | this.Close();
35 | }
36 | }
--------------------------------------------------------------------------------
/PromptPlayground/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ResultsViewModel.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Messaging;
3 | using PromptPlayground.Messages;
4 | using PromptPlayground.Services;
5 | using System.Collections.ObjectModel;
6 |
7 | namespace PromptPlayground.ViewModels
8 | {
9 | public class ResultsViewModel : ObservableRecipient, IRecipient
10 | {
11 | private SemanticFunctionViewModel function;
12 | public ObservableCollection Results => function.Results;
13 | public AverageResult AverageResult => function.Average;
14 |
15 | public ResultsViewModel(SemanticFunctionViewModel function)
16 | {
17 | this.function = function;
18 | IsActive = true;
19 | }
20 |
21 | public void Receive(FunctionSelectedMessage message)
22 | {
23 | this.function = message.Function;
24 | OnPropertyChanged(nameof(Results));
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/PromptPlayground/Converters/StringToBooleanConverter.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Data.Converters;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Globalization;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 |
9 | namespace PromptPlayground.Converters
10 | {
11 | public class StringToBooleanConverter : IValueConverter
12 | {
13 | public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
14 | {
15 | if (value == null || parameter == null || !(value is string) || !(parameter is string))
16 | {
17 | return false;
18 | }
19 |
20 | var strValue = (string)value;
21 | var strParameter = (string)parameter;
22 |
23 | return strValue.Equals(strParameter, StringComparison.OrdinalIgnoreCase);
24 | }
25 |
26 | public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
27 | {
28 | throw new NotSupportedException();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/VariablesWindows.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using Avalonia.Interactivity;
3 | using PromptPlayground.ViewModels;
4 |
5 | namespace PromptPlayground.Views;
6 |
7 | public partial class VariablesWindows : Window
8 | {
9 | private VariablesViewModel Model => (this.DataContext as VariablesViewModel)!;
10 | public VariablesWindows()
11 | {
12 | InitializeComponent();
13 | }
14 |
15 | protected override void OnClosing(WindowClosingEventArgs e)
16 | {
17 | if (!this.Model.IsCanceled)
18 | {
19 | if (!e.IsProgrammatic)
20 | {
21 | this.Model.IsCanceled = true;
22 | }
23 | }
24 | }
25 |
26 | public void OnCanceledClick(object sender, RoutedEventArgs e)
27 | {
28 | this.Model.IsCanceled = true;
29 | this.Close();
30 | }
31 | public void OnContinuedClick(object sender, RoutedEventArgs e)
32 | {
33 | if ((this.DataContext as VariablesViewModel)!.Configured())
34 | {
35 | this.Close();
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 xbotter
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/PromptPlayground/App.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls.ApplicationLifetimes;
3 | using Avalonia.Data.Core.Plugins;
4 | using Avalonia.Markup.Xaml;
5 |
6 | using PromptPlayground.ViewModels;
7 | using PromptPlayground.Views;
8 |
9 | namespace PromptPlayground;
10 |
11 | public partial class App : Application
12 | {
13 | public override void Initialize()
14 | {
15 | AvaloniaXamlLoader.Load(this);
16 | }
17 |
18 | public override void OnFrameworkInitializationCompleted()
19 | {
20 | // Line below is needed to remove Avalonia data validation.
21 | // Without this line you will get duplicate validations from both Avalonia and CT
22 | BindingPlugins.DataValidators.RemoveAt(0);
23 |
24 | if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
25 | {
26 | desktop.MainWindow = new MainWindow
27 | {
28 | DataContext = new MainViewModel()
29 | };
30 | }
31 | else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
32 | {
33 | singleViewPlatform.MainView = new MainView
34 | {
35 | DataContext = new MainViewModel()
36 | };
37 | }
38 |
39 | base.OnFrameworkInitializationCompleted();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/StatusViewModel.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Messaging;
3 | using CommunityToolkit.Mvvm.Messaging.Messages;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.ViewModels
11 | {
12 | public partial class StatusViewModel : ObservableRecipient, IRecipient>, IRecipient
13 | {
14 | [ObservableProperty]
15 | public string text = string.Empty;
16 |
17 | [ObservableProperty]
18 | private bool loading = false;
19 |
20 | public StatusViewModel()
21 | {
22 | this.IsActive = true;
23 |
24 | WeakReferenceMessenger.Default.Register, string>(this, "Status");
25 | }
26 |
27 | public void Receive(ValueChangedMessage message)
28 | {
29 |
30 | }
31 |
32 | public void Receive(LoadingStatus message)
33 | {
34 | this.Loading = message.IsRunning;
35 | }
36 | }
37 | }
38 | public class LoadingStatus
39 | {
40 | public LoadingStatus(bool isRunning)
41 | {
42 | IsRunning = isRunning;
43 | }
44 |
45 | public bool IsRunning { get; set; }
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/AboutViewModel.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Input;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Diagnostics;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Net.Http;
9 | using System.Reflection;
10 | using System.Text;
11 | using System.Threading.Tasks;
12 |
13 | namespace PromptPlayground.ViewModels
14 | {
15 | public partial class AboutViewModel : ViewModelBase
16 | {
17 |
18 | const string GitHubLink = "https://github.com/xbotter/PromptPlayground";
19 | const string ReleaseLink = GitHubLink + "/releases/latest";
20 |
21 | public Version? CurrentVersion { get; set; }
22 |
23 | public AboutViewModel()
24 | {
25 | CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version;
26 | }
27 |
28 |
29 | [RelayCommand]
30 | public void OpenGitHub() => OpenLink(GitHubLink);
31 |
32 | [RelayCommand]
33 | public void CheckVersion() => OpenLink(ReleaseLink);
34 |
35 | public static void OpenLink(string link)
36 | {
37 | var psi = new ProcessStartInfo()
38 | {
39 | FileName = link,
40 | UseShellExecute = true
41 | };
42 | Process.Start(psi);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/OpenAIConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using Microsoft.SemanticKernel;
3 | using PromptPlayground.Services;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
11 | {
12 | internal class OpenAIConfigViewModel : ConfigViewModelBase, ILLMConfigViewModel
13 | {
14 | public OpenAIConfigViewModel(IConfigAttributesProvider provider) : base(provider)
15 | {
16 | RequireAttribute(ConfigAttribute.OpenAIModel);
17 | RequireAttribute(ConfigAttribute.OpenAIApiKey);
18 | }
19 |
20 | public override string Name => "OpenAI";
21 |
22 | public IKernelBuilder CreateKernelBuilder()
23 | {
24 | var model = GetAttribute(ConfigAttribute.OpenAIModel);
25 | var apiKey = GetAttribute(ConfigAttribute.OpenAIApiKey);
26 |
27 | return Kernel.CreateBuilder()
28 | .AddOpenAIChatCompletion(model, apiKey);
29 | }
30 |
31 | public ResultTokenUsage? GetUsage(FunctionResult result)
32 | {
33 | var usage = result.Metadata?["Usage"] as CompletionsUsage;
34 | if (usage == null)
35 | {
36 | return null;
37 | }
38 | return new ResultTokenUsage(usage.TotalTokens, usage.PromptTokens, usage.CompletionTokens);
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/PromptPlayground/Services/ProfileService.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace PromptPlayground.Services
9 | {
10 | internal class ProfileService
11 | {
12 | private readonly string _profile;
13 |
14 | public ProfileService(string profile)
15 | {
16 | this._profile = profile;
17 | }
18 |
19 | public string ProfilePath()
20 | {
21 | var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
22 | var profileFolder = Path.Combine(userProfile, ".prompt_playground");
23 | if (!Directory.Exists(profileFolder))
24 | {
25 | Directory.CreateDirectory(profileFolder);
26 | }
27 | return Path.Combine(profileFolder, $"{_profile}");
28 | }
29 |
30 |
31 |
32 | public T? Get()
33 | {
34 | var path = ProfilePath();
35 | if (!File.Exists(path))
36 | {
37 | return default;
38 | }
39 | var json = File.ReadAllText(path);
40 | return System.Text.Json.JsonSerializer.Deserialize(json);
41 | }
42 |
43 | public void Save(T profile)
44 | {
45 | var path = ProfilePath();
46 | var json = System.Text.Json.JsonSerializer.Serialize(profile);
47 | File.WriteAllText(path, json, Encoding.UTF8);
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/DashScopeConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using DashScope;
3 | using DashScope.Models;
4 | using Microsoft.SemanticKernel;
5 | using PromptPlayground.Services;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Text;
10 | using System.Threading.Tasks;
11 |
12 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
13 | {
14 | internal class DashScopeConfigViewModel : ConfigViewModelBase, ILLMConfigViewModel
15 | {
16 | public override string Name => "DashScope";
17 |
18 | public DashScopeConfigViewModel(IConfigAttributesProvider provider) : base(provider)
19 | {
20 | RequireAttribute(ConfigAttribute.DashScopeApiKey);
21 | RequireAttribute(ConfigAttribute.DashScopeModel);
22 | }
23 |
24 | public IKernelBuilder CreateKernelBuilder()
25 | {
26 | var apiKey = GetAttribute(ConfigAttribute.DashScopeApiKey);
27 | var model = GetAttribute(ConfigAttribute.DashScopeModel);
28 |
29 | return Kernel.CreateBuilder().WithDashScopeCompletionService(apiKey, model);
30 | }
31 |
32 | public ResultTokenUsage? GetUsage(FunctionResult resultModel)
33 | {
34 | var usage = resultModel.Metadata?["Usage"] as CompletionUsage;
35 | if (usage == null)
36 | {
37 | return null;
38 | }
39 | return new ResultTokenUsage(usage.InputTokens + usage.OutputTokens, usage.InputTokens, usage.OutputTokens);
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/EditorView.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Controls.Notifications;
4 | using Avalonia.Interactivity;
5 | using Avalonia.Platform.Storage;
6 | using AvaloniaEdit;
7 | using AvaloniaEdit.TextMate;
8 | using CommunityToolkit.Mvvm.Messaging;
9 | using Microsoft.SemanticKernel;
10 | using MsBox.Avalonia;
11 | using PromptPlayground.Messages;
12 | using PromptPlayground.Services;
13 | using PromptPlayground.ViewModels;
14 | using PromptPlayground.ViewModels.ConfigViewModels;
15 | using PromptPlayground.ViewModels.ConfigViewModels.LLM;
16 | using System;
17 | using System.IO;
18 | using System.Linq;
19 | using System.Threading;
20 | using System.Threading.Tasks;
21 | using TextMateSharp.Grammars;
22 |
23 | namespace PromptPlayground.Views;
24 |
25 | public partial class EditorView : UserControl, IRecipient
26 | {
27 | public EditorView()
28 | {
29 | InitializeComponent();
30 | WeakReferenceMessenger.Default.RegisterAll(this);
31 | }
32 |
33 | protected override void OnInitialized()
34 | {
35 | base.OnInitialized();
36 |
37 | var _editor = this.FindControl("prompt");
38 |
39 | var _registryOptions = new RegistryOptions(ThemeName.LightPlus);
40 |
41 | var _textMateInstallation = _editor.InstallTextMate(_registryOptions);
42 |
43 | _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".handlebars").Id));
44 | }
45 |
46 | public void Receive(FunctionSelectedMessage message)
47 | {
48 | this.DataContext = message.Function;
49 | }
50 | }
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/MainViewModel.cs:
--------------------------------------------------------------------------------
1 | using Avalonia.Controls;
2 | using CommunityToolkit.Mvvm.ComponentModel;
3 | using CommunityToolkit.Mvvm.Input;
4 | using CommunityToolkit.Mvvm.Messaging;
5 | using CommunityToolkit.Mvvm.Messaging.Messages;
6 | using PromptPlayground.Messages;
7 | using System;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.ViewModels;
11 |
12 | public partial class MainViewModel : ViewModelBase
13 | {
14 | static IMessenger Messenger => WeakReferenceMessenger.Default;
15 |
16 | public ConfigViewModel Config { get; set; } = new(true);
17 |
18 | public StatusViewModel Status { get; set; } = new();
19 |
20 | public AboutViewModel About { get; set; } = new();
21 |
22 |
23 | public MainViewModel()
24 | {
25 | WeakReferenceMessenger.Default.RegisterAll(this);
26 | }
27 |
28 | [RelayCommand]
29 | public static void NewFile()
30 | {
31 | WeakReferenceMessenger.Default.Send(new FunctionCreateMessage());
32 | }
33 |
34 | [RelayCommand]
35 | public async Task OpenFileAsync()
36 | {
37 | var response = await Messenger.Send();
38 |
39 | if (!string.IsNullOrWhiteSpace(response))
40 | {
41 | WeakReferenceMessenger.Default.Send(new FunctionOpenMessage(response));
42 | }
43 | }
44 |
45 | [RelayCommand]
46 | public async Task OpenFolderAsync()
47 | {
48 | var response = await Messenger.Send();
49 |
50 | if (!string.IsNullOrWhiteSpace(response))
51 | {
52 | WeakReferenceMessenger.Default.Send(new PluginOpenMessage(response!));
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/PromptPlayground/Migrations/20240221112923_GenerationResultStore.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.EntityFrameworkCore.Migrations;
3 |
4 | #nullable disable
5 |
6 | namespace PromptPlayground.Migrations
7 | {
8 | ///
9 | public partial class GenerationResultStore : Migration
10 | {
11 | ///
12 | protected override void Up(MigrationBuilder migrationBuilder)
13 | {
14 | migrationBuilder.CreateTable(
15 | name: "GenerationResultStores",
16 | columns: table => new
17 | {
18 | Id = table.Column(type: "INTEGER", nullable: false)
19 | .Annotation("Sqlite:Autoincrement", true),
20 | FunctionPath = table.Column(type: "TEXT", nullable: false),
21 | Text = table.Column(type: "TEXT", nullable: false),
22 | RenderedPrompt = table.Column(type: "TEXT", nullable: false),
23 | CreatedAt = table.Column(type: "TEXT", nullable: false),
24 | Elapsed = table.Column(type: "TEXT", nullable: false),
25 | Usage = table.Column(type: "TEXT", nullable: true)
26 | },
27 | constraints: table =>
28 | {
29 | table.PrimaryKey("PK_GenerationResultStores", x => x.Id);
30 | });
31 | }
32 |
33 | ///
34 | protected override void Down(MigrationBuilder migrationBuilder)
35 | {
36 | migrationBuilder.DropTable(
37 | name: "GenerationResultStores");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/README_CN.md:
--------------------------------------------------------------------------------
1 | # Prompt Playground
2 |
3 | 一个简易的Semantic Kernel提示词调试工具。
4 |
5 | ## 使用方法 🐣
6 |
7 | ### 下载安装
8 |
9 | 1. 从Release下载最新的安装包。
10 | 2. 安装运行即可。
11 |
12 | ### 首次使用
13 |
14 | 首次使用需要先进入配置设置。
15 |
16 | 点击菜单的配置,即可进入配置界面。
17 | 
18 |
19 | 目前模型的选择支持:
20 |
21 | 1. Azure OpenAI ChatCompletion (gpt-35/gpt-4)
22 | 1. OpenAI ChatCompletion
23 | 1. Baidu ERNIE-Bot
24 | 1. Aliyun DashScope
25 |
26 | `生成数量`指最大生成结果数量,默认为3。
27 |
28 | 填写入对应的参数,关闭即可。
29 |
30 | ### 直接使用
31 |
32 | 在主界面的提示词框中直接输入提示词,点击`生成`(Ctrl+G/Ctrl+Enter)即可。
33 |
34 | ### 导入skprompt
35 |
36 | 点击菜单栏的`打开文件`按钮,选择skprompt.txt文件,即可自动导入提示词,同时会导入对于config.json文件。
37 |
38 | 对于没有config.json文件的skprompt,会自动创建一个默认的config.json文件。
39 |
40 | 点击输入框上方的Tab,可以切换到config.json编辑界面。
41 |
42 | ### 保存skprompt
43 |
44 | 对于skprompt.txt或者config.json文件修改后,点击保存(Ctrl+S)按钮,即可保存到对应的文件。
45 |
46 | ## 导入Semantic Plugin
47 |
48 | 1. 点击菜单栏,选择[打开文件夹],选择包含Semantic Functions的文件夹
49 | 1. 展开侧边栏,即可看到当前文件夹下的所有Semantic Functions
50 | 1. 选择对应的 Function ,即可进行编辑运行
51 |
52 | ## 截图
53 |
54 | 
55 |
56 | ## 构建 🛠
57 |
58 | 1. 安装 .NET 8 SDK
59 | 2. 下载源码
60 | 3. 运行 `dotnet build` 即可
61 |
62 | ## Roadmap 🚧
63 |
64 | See [Roadmap](https://github.com/xbotter/PromptPlayground/issues/1)
65 |
66 | ## Dependencies 📦
67 |
68 | - [AvaloniaUI](https://github.com/AvaloniaUI/Avalonia)
69 | - [Semi.Avalonia](https://github.com/irihitech/Semi.Avalonia)
70 | - [AvaloniaEdit](https://github.com/AvaloniaUI/AvaloniaEdit)
71 | - [Icons.Avalonia](https://github.com/Projektanker/Icons.Avalonia)
72 | - [Semantic-Kernel](https://github.com/microsoft/semantic-kernel)
73 | - [semantic-kernel-ERNIE-Bot](https://github.com/custouch/semantic-kernel-ERNIE-Bot)
74 |
75 | ## License 📃
76 |
77 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
78 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/AzureOpenAIConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using Microsoft;
3 | using Microsoft.SemanticKernel;
4 | using PromptPlayground.Services;
5 |
6 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
7 | {
8 | public class AzureOpenAIConfigViewModel : ConfigViewModelBase, ILLMConfigViewModel
9 | {
10 | public AzureOpenAIConfigViewModel(IConfigAttributesProvider provider) : base(provider)
11 | {
12 | RequireAttribute(ConfigAttribute.AzureDeployment);
13 | RequireAttribute(ConfigAttribute.AzureEndpoint);
14 | RequireAttribute(ConfigAttribute.AzureSecret);
15 | }
16 | public override string Name => "Azure OpenAI";
17 |
18 | public IKernelBuilder CreateKernelBuilder()
19 | {
20 | Requires.NotNullOrWhiteSpace(GetAttribute(ConfigAttribute.AzureDeployment), ConfigAttribute.AzureDeployment);
21 | Requires.NotNullOrWhiteSpace(GetAttribute(ConfigAttribute.AzureEndpoint), ConfigAttribute.AzureEndpoint);
22 | Requires.NotNullOrWhiteSpace(GetAttribute(ConfigAttribute.AzureSecret), ConfigAttribute.AzureSecret);
23 |
24 | return Kernel.CreateBuilder()
25 | .AddAzureOpenAIChatCompletion(GetAttribute(ConfigAttribute.AzureDeployment),
26 | GetAttribute(ConfigAttribute.AzureEndpoint),
27 | GetAttribute(ConfigAttribute.AzureSecret));
28 | }
29 |
30 | public ResultTokenUsage? GetUsage(FunctionResult result)
31 | {
32 | var usage = result.Metadata?["Usage"] as CompletionsUsage;
33 | if (usage != null)
34 | {
35 | return new ResultTokenUsage(usage.TotalTokens, usage.PromptTokens, usage.CompletionTokens);
36 | }
37 | return null;
38 | }
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/GenerateResult.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Input;
3 | using CommunityToolkit.Mvvm.Messaging;
4 | using PromptPlayground.ViewModels;
5 | using System;
6 | using System.Collections.Generic;
7 |
8 | namespace PromptPlayground.Services
9 | {
10 | public partial class AverageResult : ViewModelBase
11 | {
12 | [ObservableProperty]
13 | private bool hasResults = false;
14 |
15 | [ObservableProperty]
16 | private TimeSpan elapsed;
17 |
18 | [ObservableProperty]
19 | private ResultTokenUsage? tokenUsage;
20 |
21 | }
22 |
23 | public partial class GenerateResult : ViewModelBase
24 | {
25 | [ObservableProperty]
26 | private string text = string.Empty;
27 |
28 | [ObservableProperty]
29 | private TimeSpan? elapsed;
30 |
31 | [ObservableProperty]
32 | private string? error;
33 |
34 | [ObservableProperty]
35 | private string? promptRendered;
36 |
37 | [ObservableProperty]
38 | private ResultTokenUsage? tokenUsage;
39 |
40 | public bool HasError => !string.IsNullOrWhiteSpace(Error);
41 |
42 | [RelayCommand]
43 | public void CopyPrompt()
44 | {
45 | if (!string.IsNullOrWhiteSpace(PromptRendered))
46 | {
47 | WeakReferenceMessenger.Default.Send(new CopyTextMessage(PromptRendered));
48 | }
49 | }
50 |
51 | [RelayCommand]
52 | public void CopyText()
53 | {
54 | if (!string.IsNullOrWhiteSpace(Text) && !HasError)
55 | {
56 | WeakReferenceMessenger.Default.Send(new CopyTextMessage(Text));
57 | }
58 | }
59 |
60 | }
61 |
62 | public record ResultTokenUsage(int Total, int Prompt, int Completion);
63 | }
64 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/LLamaSharpConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using LLama.Common;
2 | using LLama;
3 | using LLamaSharp.SemanticKernel.TextCompletion;
4 | using Microsoft.Extensions.DependencyInjection;
5 | using Microsoft.SemanticKernel;
6 | using Microsoft.SemanticKernel.TextGeneration;
7 | using PromptPlayground.Services;
8 | using System;
9 | using System.Collections.Generic;
10 | using System.Linq;
11 | using System.Text;
12 | using System.Threading.Tasks;
13 |
14 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
15 | {
16 | internal class LlamaSharpConfigViewModel : ConfigViewModelBase, ILLMConfigViewModel
17 | {
18 | private string? _modelPath;
19 | private LLamaWeights? _model;
20 | public LlamaSharpConfigViewModel(IConfigAttributesProvider provider) : base(provider)
21 | {
22 | RequireAttribute(ConfigAttribute.LlamaModelPath);
23 | }
24 | public override string Name => "LlamaSharp";
25 |
26 | public IKernelBuilder CreateKernelBuilder()
27 | {
28 | var modelPath = this.GetAttribute(ConfigAttribute.LlamaModelPath);
29 | var parameters = new ModelParams(modelPath);
30 |
31 | if (_model is null || _modelPath != modelPath)
32 | {
33 | _model?.Dispose();
34 | _modelPath = modelPath;
35 | _model = LLamaWeights.LoadFromFile(parameters);
36 | }
37 |
38 | var ex = new StatelessExecutor(_model, parameters);
39 |
40 | var builder = Kernel.CreateBuilder();
41 | builder.Services.AddKeyedSingleton("local-llama", new LLamaSharpTextCompletion(ex));
42 |
43 | return builder;
44 | }
45 |
46 | public ResultTokenUsage? GetUsage(FunctionResult resultModel)
47 | {
48 | return null;
49 | }
50 |
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/PromptPlayground.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.6.33815.320
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PromptPlayground", "PromptPlayground\PromptPlayground.csproj", "{0452BA27-AF15-4889-B534-E85EE87E422B}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DBEE43A7-A207-4531-AB49-FE0D366424D6}"
9 | ProjectSection(SolutionItems) = preProject
10 | Directory.Build.props = Directory.Build.props
11 | README.md = README.md
12 | README_CN.md = README_CN.md
13 | EndProjectSection
14 | EndProject
15 | Global
16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
17 | Debug|Any CPU = Debug|Any CPU
18 | Debug|x64 = Debug|x64
19 | Release|Any CPU = Release|Any CPU
20 | Release|x64 = Release|x64
21 | EndGlobalSection
22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
23 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Debug|Any CPU.Build.0 = Debug|Any CPU
25 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Debug|x64.ActiveCfg = Debug|x64
26 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Debug|x64.Build.0 = Debug|x64
27 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Release|x64.ActiveCfg = Release|x64
30 | {0452BA27-AF15-4889-B534-E85EE87E422B}.Release|x64.Build.0 = Release|x64
31 | EndGlobalSection
32 | GlobalSection(SolutionProperties) = preSolution
33 | HideSolutionNode = FALSE
34 | EndGlobalSection
35 | GlobalSection(ExtensibilityGlobals) = postSolution
36 | SolutionGuid = {DC3B9235-110A-41D4-80FF-1BB0DE75AEDF}
37 | EndGlobalSection
38 | EndGlobal
39 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/IConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using PromptPlayground.Services;
3 | using PromptPlayground.ViewModels.ConfigViewModels.LLM;
4 |
5 | using System.Collections.Generic;
6 | using System.Collections.ObjectModel;
7 | using System.ComponentModel.DataAnnotations;
8 | using System.Linq;
9 | using System.Reactive;
10 | using System.Reactive.Linq;
11 |
12 | namespace PromptPlayground.ViewModels.ConfigViewModels
13 | {
14 | public interface IConfigViewModel
15 | {
16 | string Name { get; }
17 | public IList SelectAttributes(IList allAttributes);
18 | }
19 |
20 | public abstract class ConfigViewModelBase : ViewModelBase, IConfigViewModel
21 | {
22 | protected readonly IConfigAttributesProvider provider;
23 | private List _requiredAttributes = [];
24 |
25 | public ConfigViewModelBase(IConfigAttributesProvider provider)
26 | {
27 | this.provider = provider;
28 | }
29 | public abstract string Name { get; }
30 |
31 | public IList SelectAttributes(IList allAttributes)
32 | {
33 | return allAttributes.Where(_ => _requiredAttributes.Contains(_.Name)).ToList();
34 | }
35 |
36 | protected void RequireAttribute(string attribute)
37 | {
38 | if (!_requiredAttributes.Contains(attribute))
39 | {
40 | _requiredAttributes.Add(attribute);
41 | }
42 | }
43 | protected string GetAttribute(string name)
44 | {
45 | return provider.AllAttributes.FirstOrDefault(_ => _.Name == name)?.Value ?? string.Empty;
46 | }
47 | }
48 |
49 |
50 | public interface IConfigAttributesProvider
51 | {
52 | IList AllAttributes { get; }
53 | ILLMConfigViewModel GetLLM();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/LLM/BaiduConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using ERNIE_Bot.SDK;
2 | using ERNIE_Bot.SDK.Models;
3 | using Microsoft;
4 | using Microsoft.SemanticKernel;
5 | using PromptPlayground.Services;
6 |
7 | namespace PromptPlayground.ViewModels.ConfigViewModels.LLM
8 | {
9 | public class BaiduConfigViewModel : ConfigViewModelBase, ILLMConfigViewModel
10 | {
11 | const string ClientId = ConfigAttribute.BaiduClientId;
12 | const string Secret = ConfigAttribute.BaiduSecret;
13 |
14 | public override string Name => "Baidu";
15 |
16 | public BaiduConfigViewModel(IConfigAttributesProvider provider) : base(provider)
17 | {
18 | RequireAttribute(ConfigAttribute.BaiduModel);
19 | RequireAttribute(ClientId);
20 | RequireAttribute(Secret);
21 | }
22 | public IKernelBuilder CreateKernelBuilder()
23 | {
24 | return Kernel.CreateBuilder()
25 | .WithERNIEBotChatCompletionService(GetAttribute(ClientId), GetAttribute(Secret), modelEndpoint: ModelEndpoint);
26 | }
27 | public ResultTokenUsage? GetUsage(FunctionResult result)
28 | {
29 | var usage = result.Metadata?["Usage"] as UsageData;
30 | if (usage == null)
31 | {
32 | return null;
33 | }
34 | return new ResultTokenUsage(usage.TotalTokens, usage.PromptTokens, usage.CompletionTokens);
35 | }
36 |
37 | private ModelEndpoint ModelEndpoint =>
38 | GetAttribute(ConfigAttribute.BaiduModel) switch
39 | {
40 | "BLOOMZ_7B" => ModelEndpoints.BLOOMZ_7B,
41 | "Ernie-Bot-turbo" => ModelEndpoints.ERNIE_Bot_Turbo,
42 | "Ernie-Bot-4" => ModelEndpoints.ERNIE_Bot_4,
43 | "Ernie-Bot 8k" => ModelEndpoints.ERNIE_Bot_8K,
44 | "Ernie-Bot-speed" => ModelEndpoints.ERNIE_Bot_Speed,
45 | _ => ModelEndpoints.ERNIE_Bot
46 | };
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/PromptPlayground/Behaviors/DocumentTextBindingBehavior.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Xaml.Interactivity;
3 | using AvaloniaEdit;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.Behaviors;
11 |
12 | public class DocumentTextBindingBehavior : Behavior
13 | {
14 | private TextEditor? _textEditor;
15 |
16 | public static readonly StyledProperty TextProperty =
17 | AvaloniaProperty.Register(nameof(Text));
18 |
19 | public string Text
20 | {
21 | get => GetValue(TextProperty);
22 | set => SetValue(TextProperty, value);
23 | }
24 |
25 | protected override void OnAttached()
26 | {
27 | base.OnAttached();
28 |
29 | if (AssociatedObject is TextEditor textEditor)
30 | {
31 | _textEditor = textEditor;
32 | _textEditor.TextChanged += TextChanged;
33 | this.GetObservable(TextProperty).Subscribe(TextPropertyChanged);
34 | }
35 | }
36 |
37 | protected override void OnDetaching()
38 | {
39 | base.OnDetaching();
40 |
41 | if (_textEditor != null)
42 | {
43 | _textEditor.TextChanged -= TextChanged;
44 | }
45 | }
46 |
47 | private void TextChanged(object? sender, EventArgs eventArgs)
48 | {
49 | if (_textEditor != null && _textEditor.Document != null)
50 | {
51 | Text = _textEditor.Document.Text;
52 | }
53 | }
54 |
55 | private void TextPropertyChanged(string text)
56 | {
57 | if (_textEditor != null && _textEditor.Document != null && text != null)
58 | {
59 | var caretOffset = _textEditor.CaretOffset;
60 | _textEditor.Document.Text = text;
61 | if (caretOffset <= text.Length)
62 | {
63 | _textEditor.CaretOffset = caretOffset;
64 | }
65 | else
66 | {
67 | _textEditor.CaretOffset = 0;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/PromptPlayground/Services/DbStore.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using Microsoft.EntityFrameworkCore.Design;
3 | using PromptPlayground.Services.Models;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 |
10 | namespace PromptPlayground.Services
11 | {
12 | internal class DbStore : DbContext
13 | {
14 | static string defaultConnectionString;
15 | public static DbStore NewScoped
16 | {
17 | get
18 | {
19 | var options = new DbContextOptionsBuilder()
20 | .UseSqlite(defaultConnectionString)
21 | .Options;
22 | return new DbStore(options);
23 | }
24 | }
25 |
26 | static DbStore()
27 | {
28 | var path = new ProfileService("store.db").ProfilePath();
29 | defaultConnectionString = $"Data Source={path};Mode=ReadWriteCreate;Cache=Shared";
30 |
31 | var db = NewScoped;
32 | db.Database.Migrate();
33 | }
34 |
35 | public DbStore(DbContextOptions options) : base(options)
36 | {
37 |
38 | }
39 |
40 | public DbSet GenerationResultStores { get; set; }
41 |
42 | protected override void OnModelCreating(ModelBuilder modelBuilder)
43 | {
44 | base.OnModelCreating(modelBuilder);
45 |
46 | modelBuilder.Entity(
47 | entity =>
48 | {
49 | entity.OwnsOne(_ => _.Usage, builder =>
50 | {
51 | builder.ToJson();
52 | });
53 | });
54 | }
55 | }
56 |
57 | internal class DbStoreContextFactory : IDesignTimeDbContextFactory
58 | {
59 | public DbStore CreateDbContext(string[] args)
60 | {
61 | var options = new DbContextOptionsBuilder()
62 | .UseSqlite("Data Source=design.db")
63 | .Options;
64 | return new DbStore(options);
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/VariablesViewModel.cs:
--------------------------------------------------------------------------------
1 | using Bogus;
2 | using CommunityToolkit.Mvvm.ComponentModel;
3 | using System.Collections.Generic;
4 | using System.Collections.ObjectModel;
5 | using System.Linq;
6 |
7 | namespace PromptPlayground.ViewModels
8 | {
9 | public class VariablesViewModel : ViewModelBase
10 | {
11 | static readonly Dictionary _variablesCache = [];
12 |
13 | ///
14 | /// only for design time
15 | ///
16 | public VariablesViewModel()
17 | {
18 | Variables = new ObservableCollection([.. new Faker()
19 | .RuleFor(x => x.Name, f => f.Lorem.Word())
20 | .Generate(5)]);
21 | }
22 |
23 | public VariablesViewModel(List variables)
24 | {
25 | Variables = new ObservableCollection(variables);
26 |
27 | foreach (var var in Variables)
28 | {
29 | if (_variablesCache.TryGetValue(var.Name, out string? value))
30 | {
31 | var.Value = value;
32 | }
33 | else if (string.IsNullOrWhiteSpace(var.Value) && !string.IsNullOrWhiteSpace(var.DefaultValue))
34 | {
35 | var.Value = var.DefaultValue;
36 | }
37 | }
38 | }
39 | public bool IsCanceled { get; set; }
40 | public ObservableCollection Variables { get; set; }
41 |
42 | public bool Configured()
43 | {
44 | foreach (var var in Variables)
45 | {
46 | if (var.IsRequired && string.IsNullOrWhiteSpace(var.Value))
47 | {
48 | return false;
49 | }
50 | if (var.Value != var.DefaultValue)
51 | {
52 | _variablesCache[var.Name] = var.Value;
53 | }
54 | }
55 | return true;
56 | }
57 | }
58 | public class Variable : ObservableObject
59 | {
60 | public string Name { get; set; } = string.Empty;
61 | public string Value { get; set; } = string.Empty;
62 | public string? DefaultValue { get; set; }
63 | public bool IsRequired { get; set; } = false;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/VariablesWindows.axaml:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
27 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Thank you for your interest in contributing to PromptPlayground!
4 |
5 | We appreciate contributions from everyone, whether it's a bug fix, new feature, or improvement in documentation. This guide aims to give you an overview of how you can contribute.
6 |
7 | ## How Can I Contribute?
8 |
9 | ### Reporting Bugs
10 |
11 | Before creating bug reports, please check the issue list as you might find out that you don't need to create one. When you are creating a bug report, please include as many details as possible and follow the bug report template.
12 |
13 | ### Suggesting Enhancements
14 |
15 | Enhancement suggestions are welcome. But please first check if there's a similar suggestion. If not, provide a clear description of the enhancement in as much detail as possible.
16 |
17 | ### Pull Requests
18 |
19 | Pull requests are a great way to contribute. Here are a few guidelines you should follow:
20 |
21 | 1. Fork the repository and create your branch from `main`.
22 | 2. If you've added code, add tests to ensure your contribution works as expected.
23 | 3. Ensure your code follows the `.NET coding style` guidelines.
24 | 4. Ensure all tests pass.
25 | 5. Submit your pull request.
26 |
27 | ## Code Style and Conventions
28 |
29 | For this project, we adhere to the `.NET coding style` guidelines. Here are some key points:
30 |
31 | - **Naming Conventions**: Use CamelCase for method names, variable names, and properties. Use PascalCase for class names and namespaces.
32 | - **Indentation**: Use spaces instead of tabs with a standard indent size of 4.
33 | - **Brace Style**: Use the K&R style for braces, where the opening brace goes on the same line as the statement but the closing brace goes on its own line.
34 |
35 | For a comprehensive guide, please refer to the [.NET coding conventions](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions) provided by Microsoft.
36 |
37 | ## Code of Conduct
38 |
39 | PromptPlayground adheres to a Code of Conduct adapted from the Contributor Covenant, version 2.0, available at [Code of Conduct](./CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.
40 |
41 | ## Getting Help
42 |
43 | If you have questions or need assistance, feel free to open an issue in our GitHub repository. This is the preferred method of communication for project-related inquiries. You can go to [Issues](https://github.com/xbotter/PromptPlayground/issues) to create a new issue.
44 |
45 | Thank you for contributing to PromptPlayground, and we look forward to your contributions!
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Prompt Playground
2 |
3 | A simple Semantic Kernel prompt debugging tool.
4 |
5 | ## How to use 🐣
6 |
7 | ### Download and Install
8 |
9 | 1. Download the latest installation package from Release.
10 | 2. Install and run `prompt-playground.exe`.
11 |
12 | ### First-time use
13 |
14 | You need to enter the configuration settings for the first time.
15 |
16 | Click on the configuration in the menu to enter the configuration interface.
17 | 
18 |
19 | The current model selection supports:
20 |
21 | 1. Azure OpenAI ChatCompletion (gpt-35/gpt-4)
22 | 1. OpenAI ChatCompletion
23 | 1. Baidu ERNIE-Bot
24 | 1. Aliyun DashScope
25 |
26 | `Generation quantity` refers to the maximum number of results generated, the default is 3.
27 |
28 | Fill in the corresponding parameters and close.
29 |
30 | ### Direct use
31 |
32 | Enter the prompt directly in the prompt box on the main interface, and click `Generate` (Ctrl+G/Ctrl+Enter).
33 |
34 | ### Import skprompt
35 |
36 | Click the `Open File` button on the menu bar, select the skprompt.txt file, and the prompt will be automatically imported, and the corresponding config.json file will be imported at the same time.
37 |
38 | For skprompts without a config.json file, a default config.json file will be automatically created.
39 |
40 | Click the Tab above the input box to switch to the config.json editing interface.
41 |
42 | ### Save skprompt
43 |
44 | After modifying the skprompt.txt or config.json file, click the Save (Ctrl+S) button to save to the corresponding file.
45 |
46 | ## Import Semantic Plugin
47 |
48 | 1. Click on the menu bar, select [Open Folder], and choose the folder containing Semantic Functions
49 | 1. Expand the sidebar to see all Semantic Functions in the current folder
50 | 1. Select the corresponding Function to edit and run
51 |
52 | ## Screenshots
53 |
54 | 
55 |
56 | ## Build 🛠
57 |
58 | 1. Install .NET 8 SDK
59 | 2. Download the source code
60 | 3. Run `dotnet build`
61 |
62 | ## Roadmap 🚧
63 |
64 | See [Roadmap](https://github.com/xbotter/PromptPlayground/issues/1)
65 |
66 | ## Dependencies 📦
67 |
68 | - [AvaloniaUI](https://github.com/AvaloniaUI/Avalonia)
69 | - [Semi.Avalonia](https://github.com/irihitech/Semi.Avalonia)
70 | - [AvaloniaEdit](https://github.com/AvaloniaUI/AvaloniaEdit)
71 | - [Icons.Avalonia](https://github.com/Projektanker/Icons.Avalonia)
72 | - [Semantic-Kernel](https://github.com/microsoft/semantic-kernel)
73 | - [semantic-kernel-ERNIE-Bot](https://github.com/custouch/semantic-kernel-ERNIE-Bot)
74 |
75 | ## License 📃
76 |
77 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
78 |
79 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/installer.iss:
--------------------------------------------------------------------------------
1 | ; Script generated by the Inno Setup Script Wizard.
2 | ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
3 |
4 | #define MyAppName "Prompt Playground"
5 | #define PublishDir AddBackSlash(SourcePath) + 'publish\windows\'
6 | #define MyAppPublisher "xbotter"
7 | #define MyAppURL "https://github.com/xbotter/PromptPlayground"
8 | #define MyAppExeName "prompt-playground.exe"
9 | #define MyAppVersion GetVersionNumbersString(PublishDir + MyAppExeName)
10 | #define IconFile AddBackSlash(SourcePath) + "PromptPlayground\Assets\logo.ico"
11 |
12 | [Setup]
13 | ; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications.
14 | ; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
15 | AppId={{10ED70BD-402C-473F-BFCF-A98809FA58FF}
16 | AppName={#MyAppName}
17 | AppVersion={#MyAppVersion}
18 | ;AppVerName={#MyAppName} {#MyAppVersion}
19 | AppPublisher={#MyAppPublisher}
20 | AppPublisherURL={#MyAppURL}
21 | AppSupportURL={#MyAppURL}
22 | AppUpdatesURL={#MyAppURL}
23 | DefaultDirName={autopf}\{#MyAppName}
24 | DisableProgramGroupPage=yes
25 | LicenseFile={#file AddBackSlash(SourcePath)+ 'LICENSE'}
26 | ; Remove the following line to run in administrative install mode (install for all users.)
27 | PrivilegesRequired=lowest
28 | PrivilegesRequiredOverridesAllowed=dialog
29 | SetupIconFile={#IconFile}
30 | Compression=lzma
31 | SolidCompression=yes
32 | WizardStyle=modern
33 | OutputBaseFilename=win-x64-setup
34 |
35 | ; "ArchitecturesAllowed=x64" specifies that Setup cannot run on
36 | ; anything but x64.
37 | ArchitecturesAllowed=x64
38 | ; "ArchitecturesInstallIn64BitMode=x64" requests that the install be
39 | ; done in "64-bit mode" on x64, meaning it should use the native
40 | ; 64-bit Program Files directory and the 64-bit view of the registry.
41 | ArchitecturesInstallIn64BitMode=x64
42 |
43 | [Languages]
44 | Name: "english"; MessagesFile: "compiler:Default.isl"
45 | Name: "chinesesimplified"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
46 |
47 | [Tasks]
48 | Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
49 |
50 | [Files]
51 | Source: "D:\Github\PromptPlayground\publish\windows\prompt-playground.exe"; DestDir: "{app}"; Flags: ignoreversion
52 | Source: "D:\Github\PromptPlayground\publish\windows\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
53 | ; NOTE: Don't use "Flags: ignoreversion" on any shared system files
54 |
55 | [Icons]
56 | Name: "{autoprograms}\Promp Playground"; Filename: "{app}\prompt-playground.exe"
57 | Name: "{autodesktop}\Promp Playground"; Filename: "{app}\prompt-playground.exe"; Tasks: desktopicon
58 |
59 | [Run]
60 | Filename: "{app}\prompt-playground.exe"; Description: "{cm:LaunchProgram,Promp Playground}"; Flags: nowait postinstall skipifsilent
61 |
62 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/AboutView.axaml:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
16 |
17 |
20 |
21 |
26 |
27 |
30 |
31 | Prompt Playground
36 |
37 |
42 |
43 |
44 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/PromptPlayground/Migrations/DbStoreModelSnapshot.cs:
--------------------------------------------------------------------------------
1 | //
2 | using System;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
6 | using PromptPlayground.Services;
7 |
8 | #nullable disable
9 |
10 | namespace PromptPlayground.Migrations
11 | {
12 | [DbContext(typeof(DbStore))]
13 | partial class DbStoreModelSnapshot : ModelSnapshot
14 | {
15 | protected override void BuildModel(ModelBuilder modelBuilder)
16 | {
17 | #pragma warning disable 612, 618
18 | modelBuilder.HasAnnotation("ProductVersion", "8.0.2");
19 |
20 | modelBuilder.Entity("PromptPlayground.Services.Models.GenerationResultStore", b =>
21 | {
22 | b.Property("Id")
23 | .ValueGeneratedOnAdd()
24 | .HasColumnType("INTEGER");
25 |
26 | b.Property("CreatedAt")
27 | .HasColumnType("TEXT");
28 |
29 | b.Property("Elapsed")
30 | .HasColumnType("TEXT");
31 |
32 | b.Property("FunctionPath")
33 | .IsRequired()
34 | .HasColumnType("TEXT");
35 |
36 | b.Property("RenderedPrompt")
37 | .IsRequired()
38 | .HasColumnType("TEXT");
39 |
40 | b.Property("Text")
41 | .IsRequired()
42 | .HasColumnType("TEXT");
43 |
44 | b.HasKey("Id");
45 |
46 | b.ToTable("GenerationResultStores");
47 | });
48 |
49 | modelBuilder.Entity("PromptPlayground.Services.Models.GenerationResultStore", b =>
50 | {
51 | b.OwnsOne("PromptPlayground.Services.ResultTokenUsage", "Usage", b1 =>
52 | {
53 | b1.Property("GenerationResultStoreId")
54 | .HasColumnType("INTEGER");
55 |
56 | b1.Property("Completion")
57 | .HasColumnType("INTEGER");
58 |
59 | b1.Property("Prompt")
60 | .HasColumnType("INTEGER");
61 |
62 | b1.Property("Total")
63 | .HasColumnType("INTEGER");
64 |
65 | b1.HasKey("GenerationResultStoreId");
66 |
67 | b1.ToTable("GenerationResultStores");
68 |
69 | b1.ToJson("Usage");
70 |
71 | b1.WithOwner()
72 | .HasForeignKey("GenerationResultStoreId");
73 | });
74 |
75 | b.Navigation("Usage");
76 | });
77 | #pragma warning restore 612, 618
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/MainView.axaml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
23 |
24 |
25 |
26 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/PluginsView.axaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 | 0
13 | 0
14 | 0
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
34 |
41 |
42 |
43 |
44 |
45 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/PromptPlayground/Migrations/20240221112923_GenerationResultStore.Designer.cs:
--------------------------------------------------------------------------------
1 | //
2 | using System;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Migrations;
6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7 | using PromptPlayground.Services;
8 |
9 | #nullable disable
10 |
11 | namespace PromptPlayground.Migrations
12 | {
13 | [DbContext(typeof(DbStore))]
14 | [Migration("20240221112923_GenerationResultStore")]
15 | partial class GenerationResultStore
16 | {
17 | ///
18 | protected override void BuildTargetModel(ModelBuilder modelBuilder)
19 | {
20 | #pragma warning disable 612, 618
21 | modelBuilder.HasAnnotation("ProductVersion", "8.0.2");
22 |
23 | modelBuilder.Entity("PromptPlayground.Services.Models.GenerationResultStore", b =>
24 | {
25 | b.Property("Id")
26 | .ValueGeneratedOnAdd()
27 | .HasColumnType("INTEGER");
28 |
29 | b.Property("CreatedAt")
30 | .HasColumnType("TEXT");
31 |
32 | b.Property("Elapsed")
33 | .HasColumnType("TEXT");
34 |
35 | b.Property("FunctionPath")
36 | .IsRequired()
37 | .HasColumnType("TEXT");
38 |
39 | b.Property("RenderedPrompt")
40 | .IsRequired()
41 | .HasColumnType("TEXT");
42 |
43 | b.Property("Text")
44 | .IsRequired()
45 | .HasColumnType("TEXT");
46 |
47 | b.HasKey("Id");
48 |
49 | b.ToTable("GenerationResultStores");
50 | });
51 |
52 | modelBuilder.Entity("PromptPlayground.Services.Models.GenerationResultStore", b =>
53 | {
54 | b.OwnsOne("PromptPlayground.Services.ResultTokenUsage", "Usage", b1 =>
55 | {
56 | b1.Property("GenerationResultStoreId")
57 | .HasColumnType("INTEGER");
58 |
59 | b1.Property("Completion")
60 | .HasColumnType("INTEGER");
61 |
62 | b1.Property("Prompt")
63 | .HasColumnType("INTEGER");
64 |
65 | b1.Property("Total")
66 | .HasColumnType("INTEGER");
67 |
68 | b1.HasKey("GenerationResultStoreId");
69 |
70 | b1.ToTable("GenerationResultStores");
71 |
72 | b1.ToJson("Usage");
73 |
74 | b1.WithOwner()
75 | .HasForeignKey("GenerationResultStoreId");
76 | });
77 |
78 | b.Navigation("Usage");
79 | });
80 | #pragma warning restore 612, 618
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/PromptPlayground/PromptPlayground.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | WinExe
4 | net8.0
5 | enable
6 | latest
7 | true
8 | Assets\logo.ico
9 | false
10 | AnyCPU;x64
11 | SKEXP0001;SKEXP0002;SKEXP0004;SKEXP0050
12 | true
13 | app.manifest
14 | true
15 | prompt-playground
16 |
17 |
18 | $(DefineConstants);WINDOWS
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 | all
47 | runtime; build; native; contentfiles; analyzers; buildtransitive
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | PluginsView.axaml
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/EditorView.axaml:
--------------------------------------------------------------------------------
1 |
14 |
15 |
26 |
27 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/ConfigWindow.axaml:
--------------------------------------------------------------------------------
1 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
28 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
65 |
66 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/ResultsView.axaml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
31 |
32 |
33 |
38 |
39 |
40 |
41 |
42 |
54 |
63 |
64 |
69 |
70 |
71 |
72 |
73 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModels/ConfigAttribute.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using DashScope;
3 | using ERNIE_Bot.SDK;
4 | using Humanizer;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Diagnostics;
8 | using System.Linq;
9 | using System.Reflection;
10 | using System.Text.Json.Serialization;
11 |
12 | namespace PromptPlayground.ViewModels.ConfigViewModels
13 | {
14 | public class ConfigAttribute : ObservableObject
15 | {
16 | static ConfigAttribute()
17 | {
18 | var consts = typeof(ConfigAttribute).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).Where(fi => fi.IsLiteral && !fi.IsInitOnly).ToList();
19 | var ct = typeof(ConfigTypeAttribute);
20 | _fields = consts.Select(c =>
21 | {
22 | var value = c.GetValue(null) as string;
23 |
24 | if (c.IsDefined(ct))
25 | {
26 | return (value, c.GetCustomAttribute(ct) as ConfigTypeAttribute);
27 | }
28 | else
29 | {
30 | return (value, new ConfigTypeAttribute());
31 | }
32 | }).ToDictionary(_ => _.Item1!, _ => _.Item2!);
33 | }
34 | static readonly Dictionary _fields;
35 | public ConfigAttribute(string name)
36 | {
37 | Name = name;
38 | this.Type = _fields[name].Type;
39 | this.SelectValues = _fields[name].SelectValues?.ToList() ?? [];
40 | }
41 | private string _value = string.Empty;
42 | [JsonIgnore]
43 | public string HumanizeName => Name.Humanize();
44 | public string Type { get; set; } = "string";
45 | [JsonIgnore]
46 | public List SelectValues { get; set; }
47 | public string Name { get; set; } = string.Empty;
48 | public string Value
49 | {
50 | get => _value;
51 | set
52 | {
53 | if (!string.IsNullOrWhiteSpace(value))
54 | {
55 | _value = value;
56 | }
57 | }
58 | }
59 |
60 | #region Constants
61 | public const string AzureDeployment = nameof(AzureDeployment);
62 | public const string AzureEndpoint = nameof(AzureEndpoint);
63 | public const string AzureSecret = nameof(AzureSecret);
64 | public const string AzureEmbeddingDeployment = nameof(AzureEmbeddingDeployment);
65 |
66 | public const string BaiduClientId = nameof(BaiduClientId);
67 | public const string BaiduSecret = nameof(BaiduSecret);
68 | [ConfigType("select", "Ernie-Bot", "Ernie-Bot-turbo", "Ernie-Bot-4", "Ernie-Bot 8k", "Ernie-Bot-speed", "BLOOMZ_7B")]
69 | public const string BaiduModel = nameof(BaiduModel);
70 |
71 | public const string OpenAIApiKey = nameof(OpenAIApiKey);
72 | public const string OpenAIModel = nameof(OpenAIModel);
73 |
74 | public const string DashScopeApiKey = nameof(DashScopeApiKey);
75 | [ConfigType("select", DashScopeModels.QWenTurbo, DashScopeModels.QWenPlus, DashScopeModels.QWenMax, DashScopeModels.QWenLongContext)]
76 | public const string DashScopeModel = nameof(DashScopeModel);
77 |
78 | public const string LlamaModelPath = nameof(LlamaModelPath);
79 | #endregion
80 | }
81 |
82 | [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
83 | public class ConfigTypeAttribute : Attribute
84 | {
85 | ///
86 | /// `string` or `select`, use select must set SelectValues
87 | ///
88 | ///
89 | public ConfigTypeAttribute(string type = "string", params string[] selectValues)
90 | {
91 | Type = type;
92 | if (type == "select")
93 | {
94 | if (selectValues == null || selectValues.Length == 0)
95 | {
96 | throw new ArgumentException("selectValues must not be null or empty when type is select");
97 | }
98 |
99 | SelectValues = selectValues;
100 | }
101 | }
102 |
103 | public string Type { get; }
104 | public string[]? SelectValues { get; }
105 | }
106 |
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/PluginViewModel.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Input;
3 | using CommunityToolkit.Mvvm.Messaging;
4 | using PromptPlayground.Messages;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Collections.ObjectModel;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Text.RegularExpressions;
11 |
12 | namespace PromptPlayground.ViewModels
13 | {
14 | public partial class PluginViewModel : ObservableRecipient, IEquatable, IRecipient, IRecipient
15 | {
16 | private static bool IsFunctionDir(string folder) => File.Exists(Path.Combine(folder, Constants.SkPrompt));
17 |
18 | public bool Equals(PluginViewModel? other)
19 | {
20 | return other?.Folder == this.Folder;
21 | }
22 |
23 | public PluginViewModel(string folder)
24 | {
25 | if (Directory.Exists(folder))
26 | {
27 | this.Folder = folder;
28 | this.Title = Path.GetFileName(folder);
29 | var functions = Directory.GetDirectories(Folder)
30 | .Where(IsFunctionDir)
31 | .Select(SemanticFunctionViewModel.Create)
32 | .ToList();
33 |
34 | Functions = new ObservableCollection(functions);
35 | }
36 | else
37 | {
38 | this.Title = folder;
39 | Functions = [];
40 | }
41 | IsActive = true;
42 | }
43 | public string? Folder { get; set; }
44 | public string Title { get; set; }
45 |
46 | [ObservableProperty]
47 | private ObservableCollection functions;
48 |
49 | [ObservableProperty]
50 | private SemanticFunctionViewModel? selected;
51 |
52 |
53 | partial void OnSelectedChanged(SemanticFunctionViewModel? oldValue, SemanticFunctionViewModel? newValue)
54 | {
55 | if (newValue != null && oldValue != newValue)
56 | {
57 | WeakReferenceMessenger.Default.Send(new FunctionSelectedMessage(newValue));
58 | }
59 | }
60 |
61 | [RelayCommand(CanExecute = nameof(CanAddNewFunction))]
62 | public void AddNewFunction()
63 | {
64 | AddNewFunction(new SemanticFunctionViewModel(""));
65 | }
66 |
67 | private bool CanAddNewFunction()
68 | {
69 | return !Directory.Exists(this.Folder);
70 | }
71 |
72 | [RelayCommand(CanExecute = nameof(CanRemovePlugin))]
73 | public void RemovePlugin()
74 | {
75 | if (this.Folder != null && Directory.Exists(this.Folder))
76 | {
77 | WeakReferenceMessenger.Default.Send(new PluginCloseMessage(this.Folder));
78 | }
79 | }
80 |
81 | private bool CanRemovePlugin()
82 | {
83 | return Directory.Exists(this.Folder);
84 | }
85 |
86 | public void AddNewFunction(SemanticFunctionViewModel function)
87 | {
88 | if (string.IsNullOrWhiteSpace(function.Name))
89 | {
90 | function.Name = $"[{DefaultName} {FindLastFunctionIndex() + 1}]";
91 | }
92 | this.Functions.Add(function);
93 | }
94 | const string DefaultName = "Unsaved";
95 | readonly Regex DefaultNamePattern = new(@"\[Unsaved (?\d+)\]", RegexOptions.Compiled);
96 | private int FindLastFunctionIndex()
97 | {
98 | return this.Functions.Where(_ => DefaultNamePattern.IsMatch(_.Name))
99 | .Select(_ => DefaultNamePattern.Match(_.Name).Groups["index"])
100 | .Select(_ => int.Parse(_.Value))
101 | .Order()
102 | .LastOrDefault();
103 | }
104 |
105 | public void Receive(FunctionSelectedMessage message)
106 | {
107 | if (message.Function != null)
108 | {
109 | if (message.Function != this.Selected)
110 | {
111 | if (Functions.Contains(message.Function))
112 | {
113 | this.Selected = message.Function;
114 | }
115 | else
116 | {
117 | this.Selected = null;
118 | }
119 | }
120 | }
121 | }
122 |
123 | public void Receive(CloseFunctionMessage message)
124 | {
125 | if (this.Functions.Contains(message.Function) && message.Function != this.Selected)
126 | {
127 | this.Functions.Remove(message.Function);
128 | }
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/PluginsViewModel.cs:
--------------------------------------------------------------------------------
1 | using CommunityToolkit.Mvvm.ComponentModel;
2 | using CommunityToolkit.Mvvm.Input;
3 | using CommunityToolkit.Mvvm.Messaging;
4 | using Microsoft;
5 | using PromptPlayground.Messages;
6 | using PromptPlayground.Services;
7 | using PromptPlayground.Views;
8 | using System.Collections.Generic;
9 | using System.Collections.ObjectModel;
10 | using System.ComponentModel;
11 | using System.IO;
12 | using System.Linq;
13 | using System.Threading.Tasks;
14 |
15 | namespace PromptPlayground.ViewModels
16 | {
17 | public partial class PluginsViewModel : ObservableRecipient,
18 | IRecipient,
19 | IRecipient,
20 | IRecipient,
21 | IRecipient,
22 | IRecipient
23 | {
24 | private readonly ProfileService> profile;
25 | const string DefaultPlugin = "·______·";
26 |
27 | public PluginsViewModel()
28 | {
29 | this.profile = new ProfileService>("openedPlugins.json");
30 | Plugins = [];
31 | OpenedPlugin = new PluginViewModel(DefaultPlugin);
32 | Plugins.Add(OpenedPlugin);
33 |
34 | var plugins = profile.Get();
35 | if (plugins != null)
36 | {
37 | foreach (var plugin in plugins)
38 | {
39 | if (Directory.Exists(plugin))
40 | {
41 | Plugins.Add(new PluginViewModel(plugin));
42 | }
43 | }
44 | }
45 | IsActive = true;
46 | }
47 |
48 | [RelayCommand]
49 | public static void FunctionSelected(SemanticFunctionViewModel viewModel)
50 | {
51 | WeakReferenceMessenger.Default.Send(new FunctionSelectedMessage(viewModel));
52 | }
53 |
54 |
55 | public void Receive(PluginOpenMessage message)
56 | {
57 | if (Directory.Exists(message.Path))
58 | {
59 | var plugin = new PluginViewModel(message.Path);
60 | if (!Plugins.Contains(plugin))
61 | {
62 | Plugins.Add(plugin);
63 | this.profile.Save(Plugins
64 | .Where(_ => _.Folder != DefaultPlugin)
65 | .Select(_ => _.Folder!)
66 | .ToList());
67 | }
68 | }
69 | }
70 |
71 | public void Receive(PluginCloseMessage message)
72 | {
73 | if (Directory.Exists(message.Path))
74 | {
75 | var plugin = Plugins.FirstOrDefault(_ => _.Folder == message.Path);
76 | if (plugin != null)
77 | {
78 | Plugins.Remove(plugin);
79 | this.profile.Save(Plugins
80 | .Where(_ => _.Folder != DefaultPlugin)
81 | .Select(_ => _.Folder!)
82 | .ToList());
83 | }
84 | }
85 | }
86 |
87 | public void Receive(FunctionOpenMessage message)
88 | {
89 | if (string.IsNullOrWhiteSpace(message.Path) || (!Directory.Exists(message.Path) && !File.Exists(message.Path)))
90 | {
91 | return;
92 | }
93 |
94 | var function = new SemanticFunctionViewModel(message.Path);
95 | if (!OpenedPlugin.Functions.Contains(function))
96 | {
97 | OpenedPlugin.Functions.Add(function);
98 | FunctionSelected(function);
99 | }
100 | }
101 |
102 | public void Receive(FunctionCreateMessage message)
103 | {
104 | var function = message.Function ?? new SemanticFunctionViewModel("");
105 | this.OpenedPlugin.AddNewFunction(function);
106 |
107 | FunctionSelected(function);
108 | }
109 |
110 | public void Receive(FunctionSavedMessage message)
111 | {
112 | var defaultPlugin = Plugins.FirstOrDefault(_ => _.Folder is null);
113 | if (defaultPlugin != null)
114 | {
115 | var function = defaultPlugin.Functions.FirstOrDefault(_ => _.Folder == message.Path);
116 |
117 | var parent = Path.GetDirectoryName(message.Path);
118 |
119 | var plugin = Plugins.FirstOrDefault(_ => _.Folder == parent);
120 |
121 | if (plugin != null && function != null)
122 | {
123 | defaultPlugin.Functions.Remove(function);
124 | plugin.Functions.Add(function);
125 | WeakReferenceMessenger.Default.Send(new FunctionSelectedMessage(function));
126 | }
127 | }
128 | }
129 |
130 | public PluginViewModel OpenedPlugin { get; set; }
131 |
132 | public ObservableCollection Plugins { get; set; }
133 |
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/PromptPlayground/Services/PromptService.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.SemanticKernel;
2 | using Microsoft.SemanticKernel.Plugins.Core;
3 | using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
4 | using PromptPlayground.ViewModels.ConfigViewModels;
5 | using PromptPlayground.ViewModels.ConfigViewModels.LLM;
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Diagnostics;
9 | using System.Linq;
10 | using System.Runtime.CompilerServices;
11 | using System.Text;
12 | using System.Threading;
13 | using System.Threading.Tasks;
14 |
15 | namespace PromptPlayground.Services
16 | {
17 | public class PromptService
18 | {
19 | private readonly TimeProvider _timeProvider = TimeProvider.System;
20 | private readonly ILLMConfigViewModel _model;
21 |
22 | public PromptService(IConfigAttributesProvider provider)
23 | {
24 | this._model = provider.GetLLM() ?? throw new Exception("无法创建Kernel,请检查LLM配置");
25 | }
26 |
27 | private Kernel Build()
28 | {
29 |
30 | var builder = _model.CreateKernelBuilder();
31 |
32 | var _kernel = builder.Build();
33 |
34 | _kernel.ImportPluginFromType();
35 |
36 |
37 | return _kernel;
38 | }
39 |
40 | private static IPromptTemplateFactory? CreatePromptTemplateFactory(string templateFormat)
41 | {
42 | return templateFormat switch
43 | {
44 | "handlebars" => new HandlebarsPromptTemplateFactory(),
45 | _ => null
46 | };
47 | }
48 |
49 | public async IAsyncEnumerable RunStreamAsync(string prompt,
50 | string templateFormat,
51 | PromptExecutionSettings? config,
52 | KernelArguments arguments,
53 | [EnumeratorCancellation]
54 | CancellationToken cancellationToken = default)
55 | {
56 | var _kernel = Build();
57 | var promptFilter = new KernelFilter();
58 | _kernel.PromptFilters.Add(promptFilter);
59 | _kernel.FunctionFilters.Add(promptFilter);
60 |
61 | var templateFactory = CreatePromptTemplateFactory(templateFormat);
62 |
63 | var startTimestamp = _timeProvider.GetTimestamp();
64 | var func = _kernel.CreateFunctionFromPrompt(prompt, config, templateFormat: templateFormat, promptTemplateFactory: templateFactory);
65 |
66 | var results = func.InvokeStreamingAsync(_kernel, arguments, cancellationToken);
67 | var sb = new StringBuilder();
68 | await foreach (var result in results.ConfigureAwait(false))
69 | {
70 | sb.Append(result.ToString());
71 | yield return new GenerateResult()
72 | {
73 | Text = sb.ToString(),
74 | Elapsed = _timeProvider.GetElapsedTime(startTimestamp),
75 | PromptRendered = promptFilter.PromptRendered
76 | };
77 | }
78 | }
79 |
80 | public async Task RunAsync(string prompt,
81 | string templateFormat,
82 | PromptExecutionSettings? config,
83 | KernelArguments arguments,
84 | CancellationToken cancellationToken = default)
85 | {
86 | var _kernel = Build();
87 | var promptFilter = new KernelFilter();
88 | _kernel.PromptFilters.Add(promptFilter);
89 | _kernel.FunctionFilters.Add(promptFilter);
90 |
91 | var templateFactory = CreatePromptTemplateFactory(templateFormat);
92 |
93 | var startTimestamp = _timeProvider.GetTimestamp();
94 | var func = _kernel.CreateFunctionFromPrompt(prompt, config, templateFormat: templateFormat, promptTemplateFactory: templateFactory);
95 |
96 | var result = await func.InvokeAsync(_kernel, arguments, cancellationToken);
97 | var elapsed = _timeProvider.GetElapsedTime(startTimestamp);
98 | try
99 | {
100 | var usage = _model.GetUsage(result);
101 | return new GenerateResult()
102 | {
103 | Text = result.GetValue() ?? "",
104 | TokenUsage = usage,
105 | Elapsed = elapsed,
106 | PromptRendered = promptFilter.PromptRendered
107 | };
108 | }
109 | catch (KernelException ex)
110 | {
111 | return new GenerateResult()
112 | {
113 | Text = ex.Message,
114 | Elapsed = elapsed,
115 | Error = ex.Message,
116 | };
117 | }
118 | }
119 |
120 | public static KernelArguments CreateArguments() => [];
121 | }
122 |
123 | public class KernelFilter : IPromptFilter, IFunctionFilter
124 | {
125 | public string? PromptRendered { get; set; }
126 | public void OnFunctionInvoked(FunctionInvokedContext context)
127 | {
128 | }
129 |
130 | public void OnFunctionInvoking(FunctionInvokingContext context)
131 | {
132 | }
133 |
134 | public void OnPromptRendered(PromptRenderedContext context)
135 | {
136 | PromptRendered = context.RenderedPrompt;
137 | }
138 |
139 | public void OnPromptRendering(PromptRenderingContext context)
140 | {
141 | }
142 | }
143 |
144 |
145 | }
146 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/ConfigViewModel.cs:
--------------------------------------------------------------------------------
1 | using Azure.AI.OpenAI;
2 | using CommunityToolkit.Mvvm.ComponentModel;
3 | using CommunityToolkit.Mvvm.Messaging;
4 | using CommunityToolkit.Mvvm.Messaging.Messages;
5 | using PromptPlayground.Messages;
6 | using PromptPlayground.Services;
7 | using PromptPlayground.ViewModels.ConfigViewModels;
8 | using PromptPlayground.ViewModels.ConfigViewModels.LLM;
9 | using System;
10 | using System.Collections.Generic;
11 | using System.Collections.ObjectModel;
12 | using System.IO;
13 | using System.Linq;
14 | using System.Text.Json;
15 | using System.Text.Json.Serialization;
16 |
17 | namespace PromptPlayground.ViewModels;
18 |
19 | public partial class ConfigViewModel : ViewModelBase, IConfigAttributesProvider,
20 | IRecipient,
21 | IRecipient>
22 | {
23 | private string[] RequiredAttributes =
24 | [
25 | #region LLM Config
26 | ConfigAttribute.AzureDeployment,
27 | ConfigAttribute.AzureEndpoint,
28 | ConfigAttribute.AzureSecret,
29 | ConfigAttribute.BaiduClientId,
30 | ConfigAttribute.BaiduSecret,
31 | ConfigAttribute.BaiduModel,
32 | ConfigAttribute.OpenAIApiKey,
33 | ConfigAttribute.OpenAIModel,
34 | ConfigAttribute.DashScopeApiKey,
35 | ConfigAttribute.DashScopeModel,
36 | ConfigAttribute.LlamaModelPath
37 | #endregion
38 | ];
39 |
40 | public List AllAttributes { get; set; } = [];
41 |
42 | [ObservableProperty]
43 | private int maxCount = 3;
44 |
45 | [ObservableProperty]
46 | private bool runStream = false;
47 |
48 | #region Model
49 | private int modelSelectedIndex = 0;
50 | private ProfileService _profile;
51 |
52 | public int ModelSelectedIndex
53 | {
54 | get => modelSelectedIndex; set
55 | {
56 | if (modelSelectedIndex != value)
57 | {
58 | modelSelectedIndex = value;
59 | OnPropertyChanged(nameof(ModelSelectedIndex));
60 | OnPropertyChanged(nameof(SelectedModel));
61 | OnPropertyChanged(nameof(ModelAttributes));
62 | OnPropertyChanged(nameof(SelectedModel.Name));
63 | }
64 | }
65 | }
66 |
67 | [JsonIgnore]
68 | public List ModelLists => LLMs.Select(_ => _.Name).ToList();
69 | [JsonIgnore]
70 | public IList ModelAttributes => SelectedModel.SelectAttributes(this.AllAttributes);
71 | [JsonIgnore]
72 | public ILLMConfigViewModel SelectedModel => LLMs[ModelSelectedIndex];
73 | [JsonIgnore]
74 | private readonly List LLMs = [];
75 | #endregion
76 |
77 | #region IConfigAttributesProvider
78 | IList IConfigAttributesProvider.AllAttributes => this.AllAttributes;
79 | public ILLMConfigViewModel GetLLM()
80 | {
81 | return this.SelectedModel;
82 | }
83 | #endregion
84 |
85 | public ConfigViewModel(bool requireLoadConfig = false) : this()
86 | {
87 | if (requireLoadConfig)
88 | {
89 | WeakReferenceMessenger.Default.RegisterAll(this);
90 | LoadConfigFromUserProfile();
91 | }
92 | }
93 |
94 | public ConfigViewModel()
95 | {
96 | this.AllAttributes = CheckAttributes(this.AllAttributes);
97 |
98 | LLMs.Add(new AzureOpenAIConfigViewModel(this));
99 | LLMs.Add(new BaiduConfigViewModel(this));
100 | LLMs.Add(new OpenAIConfigViewModel(this));
101 | LLMs.Add(new DashScopeConfigViewModel(this));
102 | // LLMs.Add(new LlamaSharpConfigViewModel(this));
103 |
104 | this._profile = new ProfileService("user.config");
105 | }
106 |
107 | private void LoadConfigFromUserProfile()
108 | {
109 | var vm = this._profile.Get();
110 | if (vm != null)
111 | {
112 | this.AllAttributes = CheckAttributes(vm.AllAttributes);
113 |
114 | this.MaxCount = vm.MaxCount;
115 | this.RunStream = vm.RunStream;
116 | this.ModelSelectedIndex = vm.ModelSelectedIndex;
117 | }
118 | }
119 | private List CheckAttributes(List list)
120 | {
121 | foreach (var item in RequiredAttributes)
122 | {
123 | if (!list.Any(_ => _.Name == item))
124 | {
125 | list.Add(new ConfigAttribute(item));
126 | }
127 | }
128 | return list;
129 | }
130 |
131 | private void SaveConfigToUserProfile()
132 | {
133 | this._profile.Save(this);
134 | }
135 |
136 | public void SaveConfig()
137 | {
138 | SaveConfigToUserProfile();
139 | }
140 |
141 | public void ReloadConfig()
142 | {
143 | this.LoadConfigFromUserProfile();
144 | }
145 |
146 | public void Receive(RequestMessage message)
147 | {
148 | message.Reply(this);
149 | }
150 |
151 | public void Receive(ConfigurationRequestMessage request)
152 | {
153 | switch (request.Config)
154 | {
155 | case nameof(MaxCount):
156 | request.Reply(this.MaxCount.ToString());
157 | break;
158 | case nameof(RunStream):
159 | request.Reply(this.RunStream.ToString());
160 | break;
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | xbotter@outlook.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/PromptPlayground/Views/MainView.axaml.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using Avalonia.Controls;
3 | using Avalonia.Controls.Notifications;
4 | using Avalonia.Interactivity;
5 | using Avalonia.Platform.Storage;
6 | using CommunityToolkit.Mvvm.Messaging;
7 | using CommunityToolkit.Mvvm.Messaging.Messages;
8 | using ERNIE_Bot.SDK.Models;
9 | using Microsoft.Extensions.Logging;
10 | using MsBox.Avalonia;
11 | using PromptPlayground.Messages;
12 | using PromptPlayground.Services;
13 | using PromptPlayground.ViewModels;
14 | using System;
15 | using System.Collections.Generic;
16 | using System.IO;
17 | using System.Linq;
18 | using System.Threading.Tasks;
19 |
20 | namespace PromptPlayground.Views;
21 |
22 | public partial class MainView : UserControl, IRecipient,
23 | IRecipient,
24 | IRecipient,
25 | IRecipient,
26 | IRecipient,
27 | IRecipient
28 | {
29 | private WindowNotificationManager? _manager;
30 |
31 | private MainViewModel Model => (this.DataContext as MainViewModel)!;
32 | private Window MainWindow => (this.Parent as Window)!;
33 |
34 | public MainView()
35 | {
36 | InitializeComponent();
37 |
38 | WeakReferenceMessenger.Default.RegisterAll(this);
39 | }
40 | protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
41 | {
42 | base.OnAttachedToVisualTree(e);
43 | var topLevel = TopLevel.GetTopLevel(this);
44 | _manager = new WindowNotificationManager(topLevel) { MaxItems = 3 };
45 |
46 | var defaultFunction = new SemanticFunctionViewModel("[Unsaved]");
47 | this.EditorView.DataContext = defaultFunction;
48 | this.ResultsView.DataContext = new ResultsViewModel(defaultFunction);
49 |
50 | WeakReferenceMessenger.Default.Send(new FunctionCreateMessage(defaultFunction));
51 | }
52 |
53 | private void AboutClick(object sender, RoutedEventArgs e)
54 | {
55 | var aboutWindow = new AboutView()
56 | {
57 | DataContext = Model.About,
58 | ShowInTaskbar = false,
59 | WindowStartupLocation = WindowStartupLocation.CenterOwner,
60 | };
61 | aboutWindow.Show(MainWindow);
62 | }
63 |
64 | private void OnConfigClick(object sender, RoutedEventArgs e)
65 | {
66 | var configWindow = new ConfigWindow()
67 | {
68 | DataContext = Model.Config,
69 | ShowInTaskbar = false,
70 | WindowStartupLocation = WindowStartupLocation.CenterOwner
71 | };
72 |
73 | configWindow.ShowDialog(MainWindow);
74 | }
75 |
76 | private async Task FolderOpenAsync()
77 | {
78 | var folders = await TopLevel.GetTopLevel(this)!.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions()
79 | {
80 | AllowMultiple = false
81 | });
82 | var folder = folders[0]?.TryGetLocalPath();
83 | return folder;
84 | }
85 | private async Task FileOpenAsync()
86 | {
87 | var file = await TopLevel.GetTopLevel(this)!.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions()
88 | {
89 | AllowMultiple = false,
90 | FileTypeFilter =
91 | [
92 | new FilePickerFileType("sk prompt")
93 | {
94 | Patterns = [Constants.SkPrompt]
95 | }
96 | ]
97 | });
98 | var filePath = file[0]?.TryGetLocalPath();
99 | return filePath;
100 | }
101 |
102 | private async Task ConfirmRequestMessageAsync(ConfirmRequestMessage message)
103 | {
104 | var result = await MessageBoxManager.GetMessageBoxStandard(message.Title, message.Message, MsBox.Avalonia.Enums.ButtonEnum.OkCancel)
105 | .ShowAsPopupAsync(this);
106 |
107 | return result == MsBox.Avalonia.Enums.ButtonResult.Ok;
108 | }
109 |
110 | public void Receive(RequestFolderOpen message)
111 | {
112 | message.Reply(FolderOpenAsync());
113 | }
114 |
115 | public void Receive(RequestFileOpen message)
116 | {
117 | message.Reply(FileOpenAsync());
118 | }
119 |
120 | public void Receive(ConfirmRequestMessage message)
121 | {
122 | message.Reply(ConfirmRequestMessageAsync(message));
123 | }
124 |
125 | public void Receive(NotificationMessage message)
126 | {
127 | _manager?.Show(new Notification(message.Title, message.Message, (NotificationType)message.Level, TimeSpan.FromSeconds(1.5)));
128 | }
129 |
130 | public async void Receive(CopyTextMessage message)
131 | {
132 | var topLevel = TopLevel.GetTopLevel(this);
133 | if (topLevel is null || topLevel.Clipboard is null)
134 | return;
135 |
136 | await topLevel.Clipboard.SetTextAsync(message.Text);
137 |
138 | _manager?.Show(new Notification("Copied", "", NotificationType.Success, TimeSpan.FromSeconds(1)));
139 | }
140 |
141 | public void Receive(RequestVariablesMessage message)
142 | {
143 | message.Reply(ShowVariablesWindows(message.Variables));
144 | }
145 | private async Task ShowVariablesWindows(List variables)
146 | {
147 | var variablesVm = new VariablesViewModel(variables);
148 | var variableWindows = new VariablesWindows()
149 | {
150 | DataContext = variablesVm,
151 | ShowInTaskbar = false,
152 | WindowStartupLocation = WindowStartupLocation.CenterOwner
153 | };
154 | await variableWindows.ShowDialog(MainWindow);
155 | return variablesVm;
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # Tye
66 | .tye/
67 |
68 | # ASP.NET Scaffolding
69 | ScaffoldingReadMe.txt
70 |
71 | # StyleCop
72 | StyleCopReport.xml
73 |
74 | # Files built by Visual Studio
75 | *_i.c
76 | *_p.c
77 | *_h.h
78 | *.ilk
79 | *.meta
80 | *.obj
81 | *.iobj
82 | *.pch
83 | *.pdb
84 | *.ipdb
85 | *.pgc
86 | *.pgd
87 | *.rsp
88 | *.sbr
89 | *.tlb
90 | *.tli
91 | *.tlh
92 | *.tmp
93 | *.tmp_proj
94 | *_wpftmp.csproj
95 | *.log
96 | *.vspscc
97 | *.vssscc
98 | .builds
99 | *.pidb
100 | *.svclog
101 | *.scc
102 |
103 | # Chutzpah Test files
104 | _Chutzpah*
105 |
106 | # Visual C++ cache files
107 | ipch/
108 | *.aps
109 | *.ncb
110 | *.opendb
111 | *.opensdf
112 | *.sdf
113 | *.cachefile
114 | *.VC.db
115 | *.VC.VC.opendb
116 |
117 | # Visual Studio profiler
118 | *.psess
119 | *.vsp
120 | *.vspx
121 | *.sap
122 |
123 | # Visual Studio Trace Files
124 | *.e2e
125 |
126 | # TFS 2012 Local Workspace
127 | $tf/
128 |
129 | # Guidance Automation Toolkit
130 | *.gpState
131 |
132 | # ReSharper is a .NET coding add-in
133 | _ReSharper*/
134 | *.[Rr]e[Ss]harper
135 | *.DotSettings.user
136 |
137 | # TeamCity is a build add-in
138 | _TeamCity*
139 |
140 | # DotCover is a Code Coverage Tool
141 | *.dotCover
142 |
143 | # AxoCover is a Code Coverage Tool
144 | .axoCover/*
145 | !.axoCover/settings.json
146 |
147 | # Coverlet is a free, cross platform Code Coverage Tool
148 | coverage*.json
149 | coverage*.xml
150 | coverage*.info
151 |
152 | # Visual Studio code coverage results
153 | *.coverage
154 | *.coveragexml
155 |
156 | # NCrunch
157 | _NCrunch_*
158 | .*crunch*.local.xml
159 | nCrunchTemp_*
160 |
161 | # MightyMoose
162 | *.mm.*
163 | AutoTest.Net/
164 |
165 | # Web workbench (sass)
166 | .sass-cache/
167 |
168 | # Installshield output folder
169 | [Ee]xpress/
170 |
171 | # DocProject is a documentation generator add-in
172 | DocProject/buildhelp/
173 | DocProject/Help/*.HxT
174 | DocProject/Help/*.HxC
175 | DocProject/Help/*.hhc
176 | DocProject/Help/*.hhk
177 | DocProject/Help/*.hhp
178 | DocProject/Help/Html2
179 | DocProject/Help/html
180 |
181 | # Click-Once directory
182 | publish/
183 |
184 | # Publish Web Output
185 | *.[Pp]ublish.xml
186 | *.azurePubxml
187 | # Note: Comment the next line if you want to checkin your web deploy settings,
188 | # but database connection strings (with potential passwords) will be unencrypted
189 | *.pubxml
190 | *.publishproj
191 |
192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
193 | # checkin your Azure Web App publish settings, but sensitive information contained
194 | # in these scripts will be unencrypted
195 | PublishScripts/
196 |
197 | # NuGet Packages
198 | *.nupkg
199 | # NuGet Symbol Packages
200 | *.snupkg
201 | # The packages folder can be ignored because of Package Restore
202 | **/[Pp]ackages/*
203 | # except build/, which is used as an MSBuild target.
204 | !**/[Pp]ackages/build/
205 | # Uncomment if necessary however generally it will be regenerated when needed
206 | #!**/[Pp]ackages/repositories.config
207 | # NuGet v3's project.json files produces more ignorable files
208 | *.nuget.props
209 | *.nuget.targets
210 |
211 | # Microsoft Azure Build Output
212 | csx/
213 | *.build.csdef
214 |
215 | # Microsoft Azure Emulator
216 | ecf/
217 | rcf/
218 |
219 | # Windows Store app package directories and files
220 | AppPackages/
221 | BundleArtifacts/
222 | Package.StoreAssociation.xml
223 | _pkginfo.txt
224 | *.appx
225 | *.appxbundle
226 | *.appxupload
227 |
228 | # Visual Studio cache files
229 | # files ending in .cache can be ignored
230 | *.[Cc]ache
231 | # but keep track of directories ending in .cache
232 | !?*.[Cc]ache/
233 |
234 | # Others
235 | ClientBin/
236 | ~$*
237 | *~
238 | *.dbmdl
239 | *.dbproj.schemaview
240 | *.jfm
241 | *.pfx
242 | *.publishsettings
243 | orleans.codegen.cs
244 |
245 | # Including strong name files can present a security risk
246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
247 | #*.snk
248 |
249 | # Since there are multiple workflows, uncomment next line to ignore bower_components
250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
251 | #bower_components/
252 |
253 | # RIA/Silverlight projects
254 | Generated_Code/
255 |
256 | # Backup & report files from converting an old project file
257 | # to a newer Visual Studio version. Backup files are not needed,
258 | # because we have git ;-)
259 | _UpgradeReport_Files/
260 | Backup*/
261 | UpgradeLog*.XML
262 | UpgradeLog*.htm
263 | ServiceFabricBackup/
264 | *.rptproj.bak
265 |
266 | # SQL Server files
267 | *.mdf
268 | *.ldf
269 | *.ndf
270 |
271 | # Business Intelligence projects
272 | *.rdl.data
273 | *.bim.layout
274 | *.bim_*.settings
275 | *.rptproj.rsuser
276 | *- [Bb]ackup.rdl
277 | *- [Bb]ackup ([0-9]).rdl
278 | *- [Bb]ackup ([0-9][0-9]).rdl
279 |
280 | # Microsoft Fakes
281 | FakesAssemblies/
282 |
283 | # GhostDoc plugin setting file
284 | *.GhostDoc.xml
285 |
286 | # Node.js Tools for Visual Studio
287 | .ntvs_analysis.dat
288 | node_modules/
289 |
290 | # Visual Studio 6 build log
291 | *.plg
292 |
293 | # Visual Studio 6 workspace options file
294 | *.opt
295 |
296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
297 | *.vbw
298 |
299 | # Visual Studio LightSwitch build output
300 | **/*.HTMLClient/GeneratedArtifacts
301 | **/*.DesktopClient/GeneratedArtifacts
302 | **/*.DesktopClient/ModelManifest.xml
303 | **/*.Server/GeneratedArtifacts
304 | **/*.Server/ModelManifest.xml
305 | _Pvt_Extensions
306 |
307 | # Paket dependency manager
308 | .paket/paket.exe
309 | paket-files/
310 |
311 | # FAKE - F# Make
312 | .fake/
313 |
314 | # CodeRush personal settings
315 | .cr/personal
316 |
317 | # Python Tools for Visual Studio (PTVS)
318 | __pycache__/
319 | *.pyc
320 |
321 | # Cake - Uncomment if you are using it
322 | # tools/**
323 | # !tools/packages.config
324 |
325 | # Tabs Studio
326 | *.tss
327 |
328 | # Telerik's JustMock configuration file
329 | *.jmconfig
330 |
331 | # BizTalk build output
332 | *.btp.cs
333 | *.btm.cs
334 | *.odx.cs
335 | *.xsd.cs
336 |
337 | # OpenCover UI analysis results
338 | OpenCover/
339 |
340 | # Azure Stream Analytics local run output
341 | ASALocalRun/
342 |
343 | # MSBuild Binary and Structured Log
344 | *.binlog
345 |
346 | # NVidia Nsight GPU debugger configuration file
347 | *.nvuser
348 |
349 | # MFractors (Xamarin productivity tool) working folder
350 | .mfractor/
351 |
352 | # Local History for Visual Studio
353 | .localhistory/
354 |
355 | # BeatPulse healthcheck temp database
356 | healthchecksdb
357 |
358 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
359 | MigrationBackup/
360 |
361 | # Ionide (cross platform F# VS Code tools) working folder
362 | .ionide/
363 |
364 | # Fody - auto-generated XML schema
365 | FodyWeavers.xsd
366 |
367 | ##
368 | ## Visual studio for Mac
369 | ##
370 |
371 |
372 | # globs
373 | Makefile.in
374 | *.userprefs
375 | *.usertasks
376 | config.make
377 | config.status
378 | aclocal.m4
379 | install-sh
380 | autom4te.cache/
381 | *.tar.gz
382 | tarballs/
383 | test-results/
384 |
385 | # Mac bundle stuff
386 | *.dmg
387 | *.app
388 |
389 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
390 | # General
391 | .DS_Store
392 | .AppleDouble
393 | .LSOverride
394 |
395 | # Icon must end with two \r
396 | Icon
397 |
398 |
399 | # Thumbnails
400 | ._*
401 |
402 | # Files that might appear in the root of a volume
403 | .DocumentRevisions-V100
404 | .fseventsd
405 | .Spotlight-V100
406 | .TemporaryItems
407 | .Trashes
408 | .VolumeIcon.icns
409 | .com.apple.timemachine.donotpresent
410 |
411 | # Directories potentially created on remote AFP share
412 | .AppleDB
413 | .AppleDesktop
414 | Network Trash Folder
415 | Temporary Items
416 | .apdisk
417 |
418 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
419 | # Windows thumbnail cache files
420 | Thumbs.db
421 | ehthumbs.db
422 | ehthumbs_vista.db
423 |
424 | # Dump file
425 | *.stackdump
426 |
427 | # Folder config file
428 | [Dd]esktop.ini
429 |
430 | # Recycle Bin used on file shares
431 | $RECYCLE.BIN/
432 |
433 | # Windows Installer files
434 | *.cab
435 | *.msi
436 | *.msix
437 | *.msm
438 | *.msp
439 |
440 | # Windows shortcuts
441 | *.lnk
442 |
443 | # JetBrains Rider
444 | .idea/
445 | *.sln.iml
446 |
447 | ##
448 | ## Visual Studio Code
449 | ##
450 | .vscode/*
451 | !.vscode/settings.json
452 | !.vscode/tasks.json
453 | !.vscode/launch.json
454 | !.vscode/extensions.json
455 | /Output
456 |
--------------------------------------------------------------------------------
/PromptPlayground/ViewModels/SemanticFunctionViewModel.cs:
--------------------------------------------------------------------------------
1 | using Avalonia;
2 | using AvaloniaEdit.Document;
3 | using CommunityToolkit.Mvvm.ComponentModel;
4 | using CommunityToolkit.Mvvm.Input;
5 | using CommunityToolkit.Mvvm.Messaging;
6 | using CommunityToolkit.Mvvm.Messaging.Messages;
7 | using Microsoft.SemanticKernel;
8 | using PromptPlayground.Messages;
9 | using PromptPlayground.Services;
10 |
11 | using PromptPlayground.ViewModels.ConfigViewModels;
12 | using System;
13 | using System.Collections.Generic;
14 | using System.Collections.ObjectModel;
15 | using System.IO;
16 | using System.Linq;
17 | using System.Reflection;
18 | using System.Text.Json;
19 | using System.Threading;
20 | using System.Threading.Tasks;
21 |
22 | namespace PromptPlayground.ViewModels
23 | {
24 | public partial class SemanticFunctionViewModel : ViewModelBase, IEquatable
25 | {
26 | #region static
27 | static readonly JsonSerializerOptions _options = new()
28 | {
29 | WriteIndented = true,
30 | DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
31 | };
32 | static string DefaultConfig()
33 | {
34 | return JsonSerializer.Serialize(new
35 | {
36 | schema = 1,
37 | description = "",
38 | template_format = "semantic-kernel",
39 | input_variables = new List()
40 | {
41 | new()
42 | {
43 | Name = "input",
44 | Default = "",
45 | Description = "",
46 | IsRequired = false
47 | }
48 | },
49 | execution_settings = new
50 | {
51 | @default = new { }
52 | }
53 | }, _options);
54 | }
55 |
56 | public static SemanticFunctionViewModel Create(string folder) => new(folder);
57 |
58 | #endregion
59 |
60 |
61 | [ObservableProperty]
62 | [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
63 | private bool isChanged;
64 |
65 | [ObservableProperty]
66 | private bool isGenerating;
67 |
68 | public SemanticFunctionViewModel(string folderOrName)
69 | {
70 | if (Path.GetFileName(folderOrName) == Constants.SkPrompt)
71 | {
72 | folderOrName = Path.GetDirectoryName(folderOrName)!;
73 | }
74 |
75 | if (Directory.Exists(folderOrName))
76 | {
77 | this.Folder = folderOrName;
78 | Name = Path.GetFileName(folderOrName);
79 | var promptPath = Path.Combine(folderOrName, Constants.SkPrompt);
80 | var configPath = Path.Combine(folderOrName, Constants.SkConfig);
81 | this.Prompt = File.ReadAllText(promptPath);
82 | this.Config = File.ReadAllText(configPath);
83 | }
84 | else
85 | {
86 | this.Folder = "";
87 | this.Name = folderOrName;
88 | this.Prompt = "";
89 | this.Config = DefaultConfig();
90 | }
91 | this.IsChanged = false;
92 | }
93 |
94 | [ObservableProperty]
95 | public string prompt;
96 | [ObservableProperty]
97 | public string config;
98 | [ObservableProperty]
99 | private string folder = string.Empty;
100 | [ObservableProperty]
101 | private string name = string.Empty;
102 |
103 | partial void OnPromptChanged(string value)
104 | {
105 | IsChanged = true;
106 | }
107 |
108 | partial void OnConfigChanged(string value)
109 | {
110 | IsChanged = true;
111 | }
112 | partial void OnIsGeneratingChanged(bool value)
113 | {
114 | WeakReferenceMessenger.Default.Send(new LoadingStatus(value));
115 | }
116 |
117 | public bool Equals(SemanticFunctionViewModel? other)
118 | {
119 | if (ReferenceEquals(this, other)) return true;
120 | return other?.Folder == this.Folder && Directory.Exists(this.Folder);
121 | }
122 |
123 | public PromptTemplateConfig PromptConfig => PromptTemplateConfig.FromJson(Config);
124 |
125 | public List InputVariables
126 | {
127 | get => PromptConfig.InputVariables;
128 | set => PromptConfig.InputVariables = value;
129 | }
130 |
131 | public IList Blocks => PromptConfig.InputVariables.Select(_ => _.Name).ToList();
132 |
133 | [RelayCommand]
134 | public async Task CloseAsync()
135 | {
136 | if (this.IsChanged)
137 | {
138 | var confirm = await WeakReferenceMessenger.Default.Send(new ConfirmRequestMessage("File unsaved", $"the {Name} is unsaved, do you want to close it?"));
139 | if (!confirm)
140 | {
141 | return;
142 | }
143 | }
144 | else
145 | {
146 | WeakReferenceMessenger.Default.Send(new CloseFunctionMessage(this));
147 | }
148 | }
149 |
150 | [RelayCommand(AllowConcurrentExecutions = false, CanExecute = nameof(IsChanged))]
151 | public async Task SaveAsync()
152 | {
153 | if (string.IsNullOrWhiteSpace(this.Folder) || !Directory.Exists(this.Folder))
154 | {
155 | var response = await WeakReferenceMessenger.Default.Send(new RequestFolderOpen());
156 | if (string.IsNullOrWhiteSpace(response))
157 | {
158 | return;
159 | }
160 |
161 | var _promptPath = Path.Combine(response, Constants.SkPrompt);
162 |
163 | if (File.Exists(_promptPath))
164 | {
165 | var confirm = await WeakReferenceMessenger.Default.Send(new ConfirmRequestMessage("file overwrite", "The prompt file already exists, do you want to overwrite it?"));
166 | if (!confirm)
167 | {
168 | return;
169 | }
170 | }
171 |
172 | this.Folder = response;
173 | this.Name = Path.GetFileName(response);
174 | }
175 |
176 | var promptPath = Path.Combine(this.Folder, Constants.SkPrompt);
177 | var configPath = Path.Combine(this.Folder, Constants.SkConfig);
178 | await File.WriteAllTextAsync(promptPath, this.Prompt);
179 | await File.WriteAllTextAsync(configPath, this.Config);
180 |
181 | this.IsChanged = false;
182 |
183 | WeakReferenceMessenger.Default.Send(new NotificationMessage("Saved!", this.Folder, NotificationMessage.NotificationType.Success));
184 | WeakReferenceMessenger.Default.Send(new FunctionSavedMessage(this.Folder));
185 | }
186 |
187 |
188 | [RelayCommand(AllowConcurrentExecutions = false, IncludeCancelCommand = true)]
189 | public async Task GenerateResultAsync(CancellationToken cancellationToken)
190 | {
191 | try
192 | {
193 | this.IsGenerating = true;
194 | Results.Clear();
195 | var configProvider = WeakReferenceMessenger.Default.Send(new RequestMessage());
196 | var service = new PromptService(configProvider.Response);
197 |
198 | var arguments = PromptService.CreateArguments();
199 | var varBlocks = this.InputVariables;
200 | if (varBlocks.Count > 0)
201 | {
202 | var variables = varBlocks.Select(_ => new Variable()
203 | {
204 | Name = _.Name.TrimStart('$'),
205 | DefaultValue = _.Default?.ToString(),
206 | IsRequired = _.IsRequired
207 | }).Distinct().ToList();
208 |
209 | var result = await WeakReferenceMessenger.Default.Send(new RequestVariablesMessage(variables));
210 |
211 | if (result.IsCanceled)
212 | {
213 | throw new Exception("生成已取消");
214 | }
215 | if (!result.Configured())
216 | {
217 | throw new Exception("变量未配置");
218 | }
219 |
220 | foreach (var variable in result.Variables)
221 | {
222 | arguments[variable.Name] = variable.Value;
223 | }
224 | }
225 |
226 | var maxCount = GetMaxCount();
227 | var results = Enumerable.Range(0, maxCount)
228 | .Select(_ => new GenerateResult()
229 | {
230 | Text = "🤖"
231 | }).ToList();
232 |
233 | var tasks = results
234 | .Select(async r =>
235 | {
236 | Results.Add(r);
237 | if (GetRunStream())
238 | {
239 | var results = service.RunStreamAsync(Prompt, PromptConfig.TemplateFormat, PromptConfig.DefaultExecutionSettings, new KernelArguments(arguments), cancellationToken)
240 | .ConfigureAwait(false);
241 | await foreach (var result in results)
242 | {
243 | r.PromptRendered = result.PromptRendered;
244 | r.Text = result.Text;
245 | r.Elapsed = result.Elapsed;
246 | r.Error = result.Error;
247 | r.TokenUsage = result.TokenUsage;
248 | }
249 | }
250 | else
251 | {
252 | var result = await service.RunAsync(Prompt, PromptConfig.TemplateFormat, PromptConfig.DefaultExecutionSettings, new KernelArguments(arguments), cancellationToken);
253 | r.PromptRendered = result.PromptRendered;
254 | r.Text = result.Text;
255 | r.Elapsed = result.Elapsed;
256 | r.Error = result.Error;
257 | r.TokenUsage = result.TokenUsage;
258 | }
259 | })
260 | .ToList();
261 |
262 | await Task.WhenAll(tasks);
263 | }
264 | catch (OperationCanceledException ex)
265 | {
266 | WeakReferenceMessenger.Default.Send(new NotificationMessage("Canceled", ex.Message, NotificationMessage.NotificationType.Warning));
267 | }
268 | catch (Exception ex)
269 | {
270 |
271 | WeakReferenceMessenger.Default.Send(new NotificationMessage("Error", ex.Message, NotificationMessage.NotificationType.Warning));
272 | }
273 | finally
274 | {
275 | this.IsGenerating = false;
276 | }
277 | }
278 |
279 |
280 |
281 | private static int GetMaxCount()
282 | {
283 | var result = WeakReferenceMessenger.Default.Send(new ConfigurationRequestMessage("MaxCount"));
284 |
285 | return int.Parse(result.Response);
286 | }
287 |
288 | private static bool GetRunStream()
289 | {
290 | var result = WeakReferenceMessenger.Default.Send(new ConfigurationRequestMessage("RunStream"));
291 |
292 | return bool.Parse(result.Response);
293 | }
294 |
295 | public ObservableCollection Results { get; set; } = [];
296 |
297 | [ObservableProperty]
298 | private AverageResult average = new();
299 |
300 | public override bool Equals(object? obj)
301 | {
302 | return Equals(obj as SemanticFunctionViewModel);
303 | }
304 |
305 | public override int GetHashCode()
306 | {
307 | return this.Folder.GetHashCode();
308 | }
309 | }
310 | }
311 |
--------------------------------------------------------------------------------