目录前言Python脚本.NET调用结尾前言Python强大的AI生态基础任何一出现就会有大量的脚本。然.NET虽然有SK框架封装的AI似乎单薄了点。如果没有SK封装的AI脚本呢?那么就需要自己调用Python了本篇通过它们交互演示下这个过程。.NET SK AI.NET SK与DeepSeekv3.2交互using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; var kernel Kernel.CreateBuilder() .AddOpenAIChatCompletion( modelId: deepseek-ai/DeepSeek-V3.2, apiKey: hf_xxxxxx, endpoint: new Uri(https://router.huggingface.co/v1) // 很关键 ) .Build(); var ai kernel.GetRequiredServiceIChatCompletionService(); var result await ai.GetChatMessageContentAsync(你是谁); Console.WriteLine(result); Console.ReadLine();结果Python脚本Python有高达十几种调用dsv.32的方法这里展示其中典型的两种脚本方式。这里对于dsv3.2_speciale和dsv3.2分别展示其中一种其一dsv3.2_speciale通过兼容openai的baseurl进行调用from openai import OpenAI client OpenAI( api_keysk-xxxxxxxx, # 替换为你的DeepSeek API密钥 base_urlhttps://api.deepseek.com/v3.2_speciale_expires_on_20251215, # 修改基础地址为DeepSeek-v3.2_speciale,其原本基础地址https://api.deepseek.com ) response client.chat.completions.create( modeldeepseek-reasoner, # 指定使用DeepSeek的模型 messages[ {role: user, content: 你好请介绍一下你自己。} ], streamFalse ) print(response.choices[0].message.content其二dsv3.2通过兼容openai的stream形式import os from openai import OpenAI #这两行对应.net那边编码问题所以需要 import sys, io sys.stdout io.TextIOWrapper(sys.stdout.buffer, encodingutf-8, errorsignore) client OpenAI( base_urlhttps://router.huggingface.co/v1, api_keyhf_xxxxx #替换成自己的hugging face key ) stream client.chat.completions.create( modeldeepseek-ai/DeepSeek-V3.2, messages[ { role: user, content: 你是谁 } ], streamTrue, ) for chunk in stream: if not chunk.choices: continue delta chunk.choices[0].delta if delta is None or not hasattr(delta, content): continue content delta.content if content: print(content, end).NET调用.NET这边最稳妥的Python调用依然是Process.Start.把以上Python脚本保存下就可以在.net里面调与deepseek交互了。下面以.net调用python的deepseekv3.2脚本为例。using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; using Microsoft.Diagnostics.Runtime.AbstractDac; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; using System.Diagnostics; public class Program { public static void Main() { string pythonExe D:\Python\python.exe; string script D:\PyCharm\PythonProject4\deepseek-v32--auto-python-openai-stream.py; //string args 123 456; var psi new ProcessStartInfo { FileName pythonExe, Arguments ${script}, RedirectStandardOutput true, RedirectStandardError true, UseShellExecute false, CreateNoWindow true, //这两行是编码的问题所以需要加上 StandardOutputEncoding Encoding.UTF8, StandardErrorEncoding Encoding.UTF8 }; using var process Process.Start(psi); string output process!.StandardOutput.ReadToEnd(); string error process.StandardError.ReadToEnd(); process.WaitForExit(); Console.WriteLine(Output:); Console.WriteLine(output); if (!string.IsNullOrEmpty(error)) { Console.WriteLine(Error:); Console.WriteLine(error); } Console.ReadLine(); } }结果结尾本篇展示了一个简单的Python/.NET与最新的DeepSeekv3.2交互的过程引入地址