var handler = new HttpClientHandler(); var client = new HttpClient(handler);
设置代理 使用 Proxy 属性可以设置 HTTP 请求的代理服务器。
1 2 3 4 5 6
var proxy = new WebProxy("http://proxy.example.com:8080"); var handler = new HttpClientHandler { Proxy = proxy }; var client = new HttpClient(handler);
var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; var client = new HttpClient(handler);
或者编写更严格的自定义验证逻辑:
1 2 3 4 5 6 7 8 9
var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, errors) => { // 自定义验证逻辑,返回 true 表示接受证书,false 表示拒绝 returntrue; } }; var client = new HttpClient(handler);
var cookieContainer = new CookieContainer(); var handler = new HttpClientHandler { CookieContainer = cookieContainer }; var client = new HttpClient(handler);
using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.Extensions.DependencyInjection; using OpenAI; using System.ClientModel;
// 引入交互式的内核命名空间,以便用户输入
using PolyglotKernel= Microsoft.DotNet.Interactive.Kernel;
var zhipuApiKey = await PolyglotKernel.GetInputAsync("请输入您的智谱API Key:");
// Create kernel builder var builder = Kernel.CreateBuilder();
var zhipuEndpoint = new Uri("https://open.bigmodel.cn/api/paas/v4/"); OpenAIClientOptions clientOptions = new OpenAIClientOptions(); clientOptions.Endpoint = zhipuEndpoint;
// 创建自定义的OpenAI客户端
var httpClient = new HttpClient(new OpenAiHttpClientHandler(logger));
var response = await kernel.InvokePromptAsync("智谱AI有哪些模型,请直接返回模型列表。"); response.Display();
测试Function Calling
准备工作
自定义IFunctionInvocationFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
private sealed classFunctionCallLogFilter(ILogger<FunctionCallLogFilter> logger) : IFunctionInvocationFilter { public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next) { try { logger.LogInformation($"Invoking function {context.Function.PluginName}-{context.Function.Name} with parameters: {context.Arguments}"); // Try to invoke function awaitnext(context); logger.LogInformation($"Function {context.Function.PluginName}-{context.Function.Name} invoked successfully with result: {context.Result}"); } catch (Exception ex) { ex.Display(); context.Result = new FunctionResult(context.Result, "Function invocation failed. Please check..."); } } }
自定义Plugin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
kernel.Plugins.Clear(); kernel.ImportPluginFromFunctions("HelperFunctions", [ kernel.CreateFunctionFromMethod((string cityName) => cityName switch { "Boston" => "61 and rainy", "London" => "55 and cloudy", "Miami" => "80 and sunny", "Paris" => "60 and rainy", "Tokyo" => "50 and sunny", "Sydney" => "75 and sunny", "Tel Aviv" => "80 and sunny", "Beijing" => throw new Exception("Weather data not available for Beijing."), _ => "31 and snowing", }, "GetWeatherForCity", "Gets the current weather for the specified city."), ]);
{ "tools":[ { "function":{ "description":"Gets the current weather for the specified city.", "name":"HelperFunctions-GetWeatherForCity", "strict":false, "parameters":{ "type":"object", "required":[ "cityName" ], "properties":{ "cityName":{ "type":"string" } } } }, "type":"function" } ], "messages":[ { "role":"user", "content":"What is the likely color of the sky in London today?" } ], "model":"gpt-4o", "tool_choice":"auto" }
{ "tools":[ { "function":{ "description":"Gets the current weather for the specified city.", "name":"HelperFunctions-GetWeatherForCity", "strict":false, "parameters":{ "type":"object", "required":[ "cityName" ], "properties":{ "cityName":{ "type":"string" } } } }, "type":"function" } ], "messages":[ { "role":"user", "content":"What is the likely color of the sky in London today?" }, { "role":"assistant", "content":"", "tool_calls":[ { "id":"call_PkTX1ikZmc7qniXWA2pRN1iH", "function":{ "name":"HelperFunctions-GetWeatherForCity", "arguments":"{"cityName":"London"}" }, "type":"function" } ] }, { "role":"tool", "tool_call_id":"call_PkTX1ikZmc7qniXWA2pRN1iH", "content":"55 and cloudy" } ], "model":"gpt-4o", "tool_choice":"auto" }
Response:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
{ "choices":[ { "finish_reason":"stop", "index":0, "logprobs":null, "message":{ "content":"The likely color of the sky in London today is gray due to the cloudy weather.", "refusal":null, "role":"assistant" } } ], "created":1740104820, "id":"chatcmpl-B3D2iSLmW1kqjYhTLu6qBgBxsLdE5", "model":"gpt-4o-2024-08-06", "object":"chat.completion", "system_fingerprint":"fp_f3927aa00d" }