using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Net.Http; using System.Text; namespace OpenAIClient { internal class OpenAI { // 替换为你的 OpenAI API 密钥 private const string OPENAI_API_KEY = "your-openai-api-key-here"; // 指定模型(例如 gpt-3.5-turbo 或 gpt-4) private const string MODEL_NAME = "qwen3-30b-a3b"; public static async Task GetOpenAIAnswer(string question) { using (var client = new HttpClient()) { // 设置 API 地址和请求头 client.BaseAddress = new Uri("http://localhost:1234/v1/chat/completions"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {OPENAI_API_KEY}"); // 构建请求体(JSON 格式) var request = new { model = MODEL_NAME, messages = new[] { new { role = "user", content = question } }, temperature = 0.7, // 控制随机性(0-1) max_tokens = 200 // 最大生成长度 }; var jsonRequest = System.Text.Json.JsonSerializer.Serialize(request); var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json"); // 发送 POST 请求 var response = await client.PostAsync("", content); // 确保响应成功 response.EnsureSuccessStatusCode(); // 解析 JSON 响应 var jsonResponse = await response.Content.ReadAsStringAsync(); var result = System.Text.Json.JsonSerializer.Deserialize(jsonResponse); // 提取模型回答 return result?.Choices[0].Message.Content.Trim(); } } // 定义响应类结构(根据实际 API 响应调整) private class OpenAIResponse { public Choice[] Choices { get; set; } } private class Choice { public Message Message { get; set; } } private class Message { public string Content { get; set; } } } }