# DeepSeek API 交互模块 v1.1 param( [string]$Prompt = "你好,请介绍一下你自己", # 默认提示 [string]$Model = "deepseek-reasoner", # 默认模型 [int]$MaxTokens = 1000, # 生成长度限制 [double]$Temperature = 0.7 # 生成随机性控制 ) # 配置区 ============================================== $API_KEY = $env:DEEPSEEK_API_KEY # 从环境变量读取密钥 $API_ENDPOINT = "https://api.deepseek.com/v1/chat/completions" # 防御性检查 =========================================== if (-not $API_KEY) { Write-Error "未检测到 API 密钥!请执行以下操作之一:`n" + "1. 设置环境变量: `$env:DEEPSEEK_API_KEY = 'your-api-key'`n" + "2. 在脚本参数中直接传入密钥" exit 1 } # TLS 安全协议配置 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 # 构造请求负载 $requestBody = @{ model = $Model messages = @( @{ role = "user" content = $Prompt } ) temperature = $Temperature max_tokens = $MaxTokens } | ConvertTo-Json -Depth 5 # 构造请求头 $headers = @{ "Authorization" = "Bearer $API_KEY" "Content-Type" = "application/json" } # 发送 API 请求 ======================================== try { $response = Invoke-RestMethod -Uri $API_ENDPOINT ` -Method Post ` -Headers $headers ` -Body $requestBody ` -ErrorAction Stop # 解析响应 $answer = $response.choices[0].message.content Write-Host "`n[DeepSeek 响应]`n" -ForegroundColor Cyan Write-Host $answer -ForegroundColor Green # 显示使用量统计 Write-Host "`n[用量统计]" -ForegroundColor Yellow Write-Host "本次消耗 tokens: $($response.usage.total_tokens)" } catch [System.Net.WebException] { # HTTP 错误处理 $errorResponse = $_.Exception.Response $statusCode = [int]$errorResponse.StatusCode $stream = $errorResponse.GetResponseStream() $reader = New-Object System.IO.StreamReader($stream) $errorBody = $reader.ReadToEnd() | ConvertFrom-Json Write-Error "[API 错误 $statusCode] $($errorBody.error.message)" } catch { # 常规错误处理 Write-Error "请求失败: $($_.Exception.Message)" }