Skip to content

Instantly share code, notes, and snippets.

@kyubuns
Created March 5, 2023 02:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyubuns/119fe5028d8140d60c6172a786c5d44a to your computer and use it in GitHub Desktop.
Save kyubuns/119fe5028d8140d60c6172a786c5d44a to your computer and use it in GitHub Desktop.
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
// https://platform.openai.com/docs/guides/chat
const string apiKey = "(APIKEY)";
async Task<string> Send(HttpClient httpClient, IEnumerable<(string Role, string Content)> history)
{
var json = new
{
model = "gpt-3.5-turbo",
messages = history.Select(x => new
{
role = x.Role,
content = x.Content
}),
};
var content = JsonSerializer.Serialize(json);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.openai.com/v1/chat/completions"),
Headers = { Authorization = new AuthenticationHeaderValue("Bearer", apiKey) },
};
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var resultString = await response.Content.ReadAsStringAsync();
var message = JsonNode.Parse(resultString)?["choices"]?[0]?["message"]?["content"]?.ToString().Trim() ?? "";
return message;
}
else
{
throw new Exception($"Error: {response.StatusCode}");
}
}
var httpClient = new HttpClient();
var history = new[]
{
(Role: "user", Content: $@"以下のことを実行するbashスクリプトを書いてください。
- {args[0]}
出力には説明は含まず、スクリプトの中にコメントとして記述してください。"),
};
var result = await Send(httpClient, history);
var file = $"{DateTime.Now:yyyyMMdd_HHmmss}.bash";
Console.WriteLine(result);
File.WriteAllText(file, result);
Console.WriteLine("---");
Console.WriteLine("実行しますか?");
var r = Console.ReadLine()?.ToLowerInvariant();
if (r == "yes" || r == "y")
{
var startInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = file,
};
var proc = new Process
{
StartInfo = startInfo,
};
proc.Start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment