开辟前准备
散成一个正在线年夜模子(如通义千问),去开辟一个chat对于话范例的ai使用,尔需要先理解OpenAI的API文档,恳求战前去的参数皆因此相干交心文档的尺度截至的
相干文档
OpenAI API文档
https://platform.openai.com/docs/api-reference/chat/create
华文版
阿里云百炼文档中有OpenAI兼容的华文版交心文档
检察ApiKey
随便面启一个模子,检察概略
面打左上角“检察尔的API-KEY",能够显现API-KEY的界里,能够检察尔的API-KEY,假设不能够新修一个,那个KEY必须要庇护佳,没有要随意保守。
准备尝试代码
咱们进修从尝试代码开端,挑选一个模子
挑选的年夜模子:通义千问2-VL-启源版-7B
而后再API示例中,找到C#的示例代码
尝试代码:
using System.Net.Http.Headers;using System.Text;class Program{ private static readonly HttpClient httpClient = new HttpClient(); static async Task Main(string[] args) { // 若不设置情况变质,请用百炼API Key将上行交流为:string? apiKey = "sk-xxx"; string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("API Key 已树立。请保证情况变质 'DASHSCOPE_API_KEY' 已经树立。"); return; } // 树立恳求 URL 战实质 string url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 模子列表:https://help.aliyun.com/zh/model-studio/getting-started/models string jsonContent = @"{ ""model"": ""qwen-plus"", ""messages"": [ { ""role"": ""system"", ""content"": ""You are a helpful assistant."" }, { ""role"": ""user"", ""content"": ""您是谁?"" } ] }"; // 收收恳求并获得照应 string result = await SendPostRequestAsync(url, jsonContent, apiKey); //输出 成果 Console.WriteLine(result); } private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey) { using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json")) { // 树立恳求头 httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // 收收恳求并获得照应 HttpResponseMessage response = await httpClient.PostAsync(url, content); //处置 照应 if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { return "恳求失利: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}" ); }
结果:
树立流式输出的参数
树立stream_options参数,检察token使用数目
增加设置include_usage为true
"stream_options":{ "include_usage": true }
残破的恳求体
string jsonContent = @"{ ""model"": ""qwen2-vl-7b-instruct"", ""stream"": true, ""stream_options"":{ ""include_usage"": true }, ""messages"": [ { ""role"": ""system"", ""content"": ""您是一个AI帮忙."" }, { ""role"": ""user"", ""content"": ""您会写C#法式吗?写一个简朴的真例"" } ]}";
终极结果:
最初多一条显现token数目
|