我正在 C# .net 框架中开发一个关于使用 Google Gemini API 制作人工智能的窗口应用程序。我在 CURL 中阅读了 google gemini api 的文档超过 10 遍。在 ChatGPT 的帮助下,我用 C# 编写了一些代码。这里看起来像:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KJAI
{
public partial class Form1 : Form
{
private string apiKey = "YOUR_API_KEY";
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
string userInput = textBox1.Text;
string output = await SendRequestAndGetResponse(userInput);
output = output.Replace("\\n", Environment.NewLine)
.Replace("\n", "")
.Replace("**", "");
richTextBox1.Text = output;
}
private async Task<string> SendRequestAndGetResponse(string userInput)
{
string jsonBody = $@"{{
""contents"": [
{{
""role"": """",
""parts"": [
{{
""text"": ""{userInput}""
}}
]
}}
],
""generationConfig"": {{
""temperature"": 0.9,
""topK"": 50,
""topP"": 0.95,
""maxOutputTokens"": 4096,
""stopSequences"": []
}},
""safetySettings"": [
]
}}";
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key={apiKey}");
request.Content = new StringContent(jsonBody, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody.Substring(responseBody.IndexOf("\"text\": \"") + 9, responseBody.IndexOf("\"", responseBody.IndexOf("\"text\": \"") + 10) - responseBody.IndexOf("\"text\": \"") - 9);
}
else
{
return $"Error: {response.StatusCode} - {response.ReasonPhrase}";
}
}
}
}
但是,我想让 Gemini 能够记住用户和人工智能之前的对话,但我不知道该怎么做。大家有想法吗?
我尽力建立用户和ai之间的聊天记录并将其制成字典形式,但我失败了。让人工智能能够访问并记住他们的对话非常重要。
字符串 googleaikey = "**6oY"; RestClient 客户端 = new RestClient("https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key="+googleaikey+ ""); RestRequest 请求 = new RestRequest() { Method = Method.Post }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0 request.AddParameter("Content-Type", "application/json", ParameterType.GetOrPost); // 使用消息和其他参数创建请求正文
string requestBody = @"{{
""contents"": [
{{
""role"": ""user"",
""parts"": [
{{
""text"":"+ userInput+ @"
}}
]
}}
],
""generationConfig"": {{
""temperature"": 0.9,
""topK"": 50,
""topP"": 0.95,
""maxOutputTokens"": 4096,
""stopSequences"": []
}},
""safetySettings"": [
]
}}";
// Add the JSON body to the request
request.AddJsonBody(JsonConvert.SerializeObject(requestBody));
RestResponse response = client.Execute(request);
var contents = response.Content;
不工作“错误”无效参数 400