0%

20230115-Manjaro 與 VSCode 綜合練習2 (類別庫)

20230115-Manjaro 與 VSCode 綜合練習2 (類別庫)

新增類別庫專案

專案配置成果

  • 建置類別庫
  • 建置主程式專案
  • 執行主程式
    1
    sudo dotnet run

HankService.ChatGPT

  • /home/hcc/DotNetCore/HankService/ChatGPT/ChatGPT.csproj
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
    </ItemGroup>

    </Project>
  • /home/hcc/DotNetCore/HankService/ChatGPT/ChatGPTService.cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;

    using Microsoft.Extensions.Configuration;

    namespace HankService.ChatGPT
    {
    public class ChatGPTService
    {
    IConfigurationRoot _config;
    public ChatGPTService(IConfigurationRoot config)
    {
    this._config = config;
    }

    public CompletionsResponse GetResponseByWebClient(string prompt)
    {
    WebClient cli;
    using (cli = new WebClient())
    {
    cli.Encoding = Encoding.GetEncoding(this._config["ChatGPT:Encoding"].ToString());
    cli.Headers[HttpRequestHeader.ContentType] = this._config["ChatGPT:HttpRequestHeader:ContentType"];
    cli.Headers[HttpRequestHeader.Authorization] = this._config["ChatGPT:HttpRequestHeader:Authorization"];
    string payload = GetRequestBodyJson(prompt, 0, 999);
    string responseBody = cli.UploadString(this._config["ChatGPT:Host"], payload);
    return JsonSerializer.Deserialize<CompletionsResponse>(responseBody);
    }
    }

    public string GetResponseTextByWebClient(string prompt)
    {
    return this.GetResponseByWebClient(prompt).Choices[0].Text;
    }

    private static string GetRequestBodyJson(string prompt, decimal temperature, int maxTokens)
    {
    // Set up the request body
    var requestBody = new CompletionsRequestBody
    {
    Model = "text-davinci-003",
    Prompt = prompt,
    Temperature = temperature,
    MaxTokens = maxTokens,
    TopP = 1.0m,
    FrequencyPenalty = 0.0m,
    PresencePenalty = 0.0m,
    N = 1,
    Stop = "[END]",
    };

    // Create a new JsonSerializerOptions object with the IgnoreNullValues and IgnoreReadOnlyProperties properties set to true
    var serializerOptions = new JsonSerializerOptions
    {
    IgnoreNullValues = true,
    IgnoreReadOnlyProperties = true,
    };

    // Serialize the request body to JSON using the JsonSerializer.Serialize method overload that takes a JsonSerializerOptions parameter
    return JsonSerializer.Serialize(requestBody, serializerOptions);
    }
    }
    }
  • /home/hcc/DotNetCore/HankService/ChatGPT/CompletionsRequestBody.cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.Json.Serialization;
    using System.Threading.Tasks;

    //https://github.com/yuzd/maui_chatgpt/blob/master/chatgpt/Services/ChatGpt/CompletionsRequestBody.cs
    namespace HankService.ChatGPT
    {
    public class CompletionsRequestBody
    {
    [JsonPropertyName("model")]
    public string Model { get; set; }

    [JsonPropertyName("prompt")]
    public string Prompt { get; set; } = "";

    [JsonPropertyName("suffix")]
    public string Suffix { get; set; } = null;

    [JsonPropertyName("max_tokens")]
    public int MaxTokens { get; set; } = 16;

    [JsonPropertyName("temperature")]
    public decimal Temperature { get; set; } = 1;

    [JsonPropertyName("top_p")]
    public decimal TopP { get; set; } = 1;

    [JsonPropertyName("n")]
    public int N { get; set; } = 1;

    [JsonPropertyName("stream")]
    public bool Stream { get; set; } = false;

    [JsonPropertyName("logprobs")]
    public int? Logprobs { get; set; } = null;

    [JsonPropertyName("echo")]
    public bool Echo { get; set; } = false;

    [JsonPropertyName("stop")]
    public string Stop { get; set; } = null;

    [JsonPropertyName("presence_penalty")]
    public decimal PresencePenalty { get; set; } = 0;

    [JsonPropertyName("frequency_penalty")]
    public decimal FrequencyPenalty { get; set; } = 0;

    [JsonPropertyName("best_of")]
    public int BestOf { get; set; } = 1;

    [JsonPropertyName("logit_bias")]
    public Dictionary<string, decimal> LogitBias { get; set; } = null;

    [JsonPropertyName("user")]
    public string User { get; set; }
    }

    public class CompletionsResponse
    {
    [JsonPropertyName("id")]
    public string Id { get; set; }

    [JsonPropertyName("object")]
    public string Object { get; set; } // Escaped with @ symbol

    [JsonPropertyName("created")]
    public int Created { get; set; }

    [JsonPropertyName("model")]
    public string Model { get; set; }

    [JsonPropertyName("choices")]
    public CompletionsChoice[] Choices { get; set; }

    [JsonPropertyName("usage")]
    public CompletionsUsage Usage { get; set; }
    }

    public class CompletionsChoice
    {
    [JsonPropertyName("text")]
    public string Text { get; set; }

    [JsonPropertyName("index")]
    public int Index { get; set; }

    [JsonPropertyName("logprobs")]
    public object Logprobs { get; set; }

    [JsonPropertyName("finish_reason")]
    public string FinishReason { get; set; }
    }

    public class CompletionsUsage
    {
    [JsonPropertyName("prompt_tokens")]
    public int PromptTokens { get; set; }

    [JsonPropertyName("completion_tokens")]
    public int CompletionTokens { get; set; }

    [JsonPropertyName("total_tokens")]
    public int TotalTokens { get; set; }
    }
    }

主程式 Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Text;

using Microsoft.Extensions.Configuration;
using HankService.ChatGPT;

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var config = builder.Build();

ChatGPTService chat = new ChatGPTService(config);
var t = chat.GetResponseTextByWebClient("請用 deliberate 造句並翻譯");
Console.WriteLine(t);

執行結果

run_prog

20230118 新增 HttpClient

類別庫新增的程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public async Task<CompletionsResponse> GetResponseByHttpClient(string prompt)
{
HttpClient client;
using (client = new HttpClient())
{
var json = GetRequestBodyJson(prompt, 0, 999);
var data = new StringContent(json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("ContentType", this._config["ChatGPT:HttpRequestHeader:ContentType"]);
client.DefaultRequestHeaders.Add("Authorization", this._config["ChatGPT:HttpRequestHeader:Authorization"]);

var response = await client.PostAsync(this._config["ChatGPT:Host"], data);

var result = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<CompletionsResponse>(result);
}
}

public async Task<string> GetResponseTextByHttpClient(string prompt)
{
var r = await this.GetResponseByHttpClient(prompt);
return r.Choices[0].Text;
}

主程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Text;

using Microsoft.Extensions.Configuration;
using HankTool2023.ChatGPT;
using System.Text.Json;

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var config = builder.Build();

ChatGPTService chat = new ChatGPTService(config);
var wc = chat.GetResponseTextByWebClient("請用 deliberate 造句並翻譯");
Console.WriteLine(wc);

var hc = await chat.GetResponseTextByHttpClient("請用 depict 造句並翻譯");
Console.WriteLine(hc);