赞
踩
c# 调用文心一言API
- using Newtonsoft.Json;
- using RestSharp;
- using System;
- using System.Collections.Generic;
-
- namespace 文心一言
- {
- class Program
- {
- const string API_KEY = "";
- const string SECRET_KEY = "";
- static void Main(string[] args)
- {
- var token = GetAccessToken();
- //文心一言会根据前面的问答回复信息
- List<ChatVO> messages = new List<ChatVO>();
- //用户问1
- messages.Add(new ChatVO { role = "user", content = "父亲的英文是什么?" });
- //温馨一言答1
- messages.Add(new ChatVO { role = "assistant", content = "父亲是father" });
- //用户问2
- messages.Add(new ChatVO { role = "user", content = "那母亲呢?" });
- var chatMsg = GetChat(token, "13900000011", messages);
- Console.WriteLine(chatMsg);
- Console.ReadLine();
- }
- static string GetChat(string accessToken, string userId, List<ChatVO> messages)
- {
- WxyyChatReq wxyyChatReq = new WxyyChatReq
- {
- user_id = userId,
- messages = messages,
- temperature = 0.95,
- top_p = 0.8,
- penalty_score = 1,
- disable_search = false,
- enable_citation = false,
- stream = false
- };
- var url = $"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={accessToken}";
- var client = new RestClient(url);
- client.Timeout = -1;
- var request = new RestRequest(Method.POST);
- request.AddHeader("Content-Type", "application/json");
- var body = JsonConvert.SerializeObject(wxyyChatReq);
- request.AddParameter("application/json", body, ParameterType.RequestBody);
- IRestResponse response = client.Execute(request);
- return response.Content;
- }
- /**
- * 使用 AK,SK 生成鉴权签名(Access Token)
- * @return 鉴权签名信息(Access Token)
- */
- static string GetAccessToken()
- {
- var url = "https://aip.baidubce.com/oauth/2.0/token";
- var client = new RestClient(url);
- client.Timeout = -1;
- var request = new RestRequest(Method.POST);
- request.AddParameter("grant_type", "client_credentials");
- request.AddParameter("client_id", API_KEY);
- request.AddParameter("client_secret", SECRET_KEY);
- IRestResponse response = client.Execute(request);
- Console.WriteLine(response.Content);
- var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
- return result.access_token.ToString();
- }
- }
- public class WxyyChatReq
- {
- public string user_id { get; set; }
- public double temperature { get; set; }
- public double top_p { get; set; }
- public double penalty_score { get; set; }
- public bool disable_search { get; set; }
- public bool enable_citation { get; set; }
-
- //是否流式处理
- public bool stream { get; set; }
-
- //最大输出token数(token:字数一般为1:2)
- //public int max_output_tokens { get; set; }
-
- public List<ChatVO> messages { get; set; }
- }
- public class ChatVO
- {
- public string role { get; set; }
- public string content { get; set; }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。