一. 前置
1. 说明
支持多种语言,详见:https://platform.openai.com/docs/libraries/community-libraries
以.Net为例,主要有三个包
OpenAI https://github.com/OkGoDoIt/OpenAI-API-dotnet
Betalgo.OpenAI https://github.com/betalgo/openai
OpenAI-DotNet https://github.com/RageAgainstThePixel/OpenAI-DotNet
其中Betalgo.OpenAI的stars最多1.9k,OpenAI下载次数最多9w,本节先以【OpenAI】这个为主,研究样例
2. 准备
string openAiKey = "sk-xxxx";
var api = new OpenAI_API.OpenAIAPI(openAiKey);
二. Chat Api
1. 说明
给定一组描述对话的消息列表(可以训练格式),模型将返回一个响应。
2. 样例1-训练的模式
{
var chat = api.Chat.CreateConversation();
//1. 事先训练chatgpt的回答格式
chat.AppendSystemMessage("You are a teacher who helps children understand if things are animals or not. " +
" If the user tells you an animal, you say \"yes\". " +
" If the user tells you something that is not an animal, you say \"no\". " +
" You only ever respond with \"yes\" or \"no\". You do not say anything else.");
// give a few examples as user and assistant
chat.AppendUserInput("Is this an animal? Cat");
chat.AppendExampleChatbotOutput("Yes");
chat.AppendUserInput("Is this an animal? House");
chat.AppendExampleChatbotOutput("No");
//2. 开始提问
chat.AppendUserInput("Is this an animal? Dog");
string response = await chat.GetResponseFromChatbotAsync();
Console.WriteLine(response); // "Yes"
chat.AppendUserInput("Is this an animal? Chair");
response = await chat.GetResponseFromChatbotAsync();
Console.WriteLine(response); // "No"
//3. 总结所有问题
// the entire chat history is available in chat.Messages
foreach (ChatMessage msg in chat.Messages)
{
Console.WriteLine($"{msg.Role}: {msg.Content}");
}
}
3. 样例2-不等待,边获取,边输出
{
var chat = api.Chat.CreateConversation(new ChatRequest()
{
Model = Model.ChatGPTTurbo //这也是默认值,模型是:gpt-3.5-turbo
});
chat.AppendUserInput("用C#写个数组去重的算法");
//C# 8.0 写法
//await foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())
//{
// Console.Write(res);
//}
//C# 8.0 之前的写法
await chat.StreamResponseFromChatbotAsync(res => Console.Write(res));
}
4. 样例3-等待获取所有结果,一次性完整输出
{
var results = await api.Chat.CreateChatCompletionAsync(new ChatRequest()
{
Model = Model.ChatGPTTurbo, //表示模型是:gpt-3.5-turbo
Temperature = 0.1, //回答的精确度 可以尝试 0.9 或 0
MaxTokens = 4046, //回答字数,默认是16
Messages = new ChatMessage[] {
new ChatMessage(ChatMessageRole.User, "讲个笑话给我听吧"),
new ChatMessage(ChatMessageRole.Assistant, "哈哈哈,真好笑"),
new ChatMessage(ChatMessageRole.User, "说一句话让我高兴一下吧"),
}
});
// 默认写法,不含任何配置
//var results = api.Chat.CreateChatCompletionAsync("Hello!");
//获取回答结果
//写法1:
var reply = results.Choices[0].Message;
Console.WriteLine($"{reply.Role}: {reply.Content.Trim()}");
//写法2
//Console.WriteLine(results);
}
三. Completions Api
1. 说明
给定提示,模型将返回一个或多个预测的结果,并且还可以返回每个位置上可选标记的概率。
2. 样例1-获取全部结果,一次性输出
{
var result = await api.Completions.CreateCompletionAsync(
new CompletionRequest(
"哈士奇和阿拉斯加有什么区别?",
model: Model.DavinciText, //最强大的GPT-3型号。可以做任何其他模型可以做的任务,通常具有更高的质量,更长的输出和更好的指令遵循。还支持在文本中插入补全。
temperature: 0.1,
max_tokens: 2048
));
Console.WriteLine(result);
}
3. 样例2-不等待,边获取,边输出
{
//C# 8.0 写法
//await foreach (var token in api.Completions.StreamCompletionEnumerableAsync(
// new CompletionRequest(
// "哈士奇和阿拉斯加有什么区别?",
// model: Model.DavinciText,
// max_tokens: 2048,
// temperature: 0.5,
// presencePenalty: 0.1,
// frequencyPenalty: 0.1)))
//{
// Console.Write(token);
//}
//C# 8.0 之前的写法
await api.Completions.StreamCompletionAsync(
new CompletionRequest(
"vue3.2版本有哪些新特性?",
model: Model.DavinciText,
max_tokens: 2048,
temperature: 0.5,
presencePenalty: 0.1,
frequencyPenalty: 0.1),
res => Console.Write(res.ToString()));
}
四. Moderation
1. 说明
判断输入文本是否违规
2. 样例
{
// 写法1
var result1 = await api.Moderation.CallModerationAsync(new ModerationRequest("哈士奇和阿拉斯加有什么区别?", Model.TextModerationLatest));
// 写法2
var result2 = await api.Moderation.CallModerationAsync("我要杀了你");
Console.WriteLine("-----------------result1----------------------");
foreach (var item in result1.Results[0].Categories)
{
Console.WriteLine(item);
}
Console.WriteLine("-----------------result2----------------------");
foreach (var item in result2.Results[0].Categories)
{
Console.WriteLine(item);
}
}
运行结果:
五. File
1. 说明
文件的增删改查,但是该文件必须是json文件,内容也必须是json内容。
2. 样例
{
// 上传文件 (文件必须是json格式,且每行都是json)
var response = await api.Files.UploadFileAsync("test1.json");
Console.WriteLine(response.Id.Length > 0);
Console.WriteLine(response.Object == "file");
Console.WriteLine(response.Bytes > 0);
Console.WriteLine(response.CreatedAt > 0);
Console.WriteLine(response.Status == "uploaded");
//获取文件
var response2 = await api.Files.GetFilesAsync();
foreach (var file in response2)
{
Console.WriteLine(file.Name);
Console.WriteLine(file.Id);
}
}
六. Images
1. 说明
根据描述,生成图片。
2. 样例
{
// for example
var result = await api.ImageGenerations.CreateImageAsync(
new ImageGenerationRequest(
prompt: "帮我画一张大熊猫的图片",
numOfImages: 1,
size: ImageSize._512,
responseFormat: ImageResponseFormat.Url //返回图片的路径
));
// or
//var result = await api.ImageGenerations.CreateImageAsync("A drawing of a computer writing a test");
Console.WriteLine(result.Data[0].Url);
}
运行结果:
七. Embeddings (用不上)
1. 说明
创建表示输入文本的嵌入向量
{
// for example
var result1 = await api.Embeddings.CreateEmbeddingAsync(new EmbeddingRequest("A test text for embedding", Model.AdaTextEmbedding));
// or
var result2 = await api.Embeddings.CreateEmbeddingAsync("A test text for embedding");
}
!
- 作 者 : Yaopengfei(姚鹏飞)
- 博客地址 : http://www.cnblogs.com/yaopengfei/
- 声 明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
- 声 明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。