[Python] 纯文本查看 复制代码
Function CallDeepSeekAPI(api_key As String, inputText As String) As String
Dim API As String
Dim SendExt As String
Dim Http As Object
Dim status_code As Integer
Dim response As String
API = "http://api.siliconflow.cn/v1/chat/completions"
SendExt = "{""model"": ""deepseek-ai/DeepSeek-V3"", ""messages"": [{""role"":""system"",""content"":""You are a helpful assistant.""},{""role"":""user"",""content"":""" & inputText & """}]}"
On Error Resume Next
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
If Err.Number <> 0 Then
CallDeepSeekAPI = "Error: Failed to create HTTP object - " & Err.Description
Exit Function
End If
With Http
.Open "POST", API, False
.setRequestHeader "Content-Type", "application/json; charset=utf-8"
.setRequestHeader "Authorization", "Bearer " & api_key
.Send SendExt
If Err.Number <> 0 Then
CallDeepSeekAPI = "Error: API request failed - " & Err.Description
Exit Function
End If
status_code = .Status
response = .responseText
End With
On Error GoTo 0
If status_code = 200 Then
CallDeepSeekAPI = response
Else
CallDeepSeekAPI = "HTTP " & status_code & " : " & response
End If
Set Http = Nothing
End Function
Sub DeepSeekV3_Simplest()
Dim api_key As String
Dim inputText As String
Dim response As String
Dim content As String
Dim originalSelection As Range
Dim startPos As Long
Dim endPos As Long
' 设置 API 密钥
api_key = "<你硅基流动的API_KEY>"
' 检查 API 密钥是否为空
If api_key = "" Then
MsgBox "请填写API密钥", vbCritical
Exit Sub
End If
' 检查是否选择了文本
If Selection.Type <> wdSelectionNormal Then
MsgBox "请先选择需要处理的文本", vbExclamation
Exit Sub
End If
' 保存当前选中的文本范围
Set originalSelection = Selection.Range
inputText = Trim(Replace(Selection.Text, vbCr, ""))
' 调用 DeepSeek API
response = CallDeepSeekAPI(api_key, inputText)
' 检查 API 调用是否出错
If Left(response, 5) = "Error" Or Left(response, 4) = "HTTP" Then
MsgBox response, vbCritical
Exit Sub
End If
' 简单提取content内容(不使用JSON解析)
startPos = InStr(response, """content"":""") + 11
endPos = InStr(startPos, response, """},""")
If startPos > 11 And endPos > startPos Then
content = Mid(response, startPos, endPos - startPos)
' 清理格式
content = Replace(content, "\n", vbCrLf)
content = Replace(content, "\""", """")
content = Replace(content, "**", "")
content = Replace(content, "###", "")
' 插入到文档
originalSelection.Collapse Direction:=wdCollapseEnd
originalSelection.InsertAfter vbCrLf & vbCrLf & "AI回答:" & vbCrLf & content
Else
MsgBox "无法解析API响应", vbExclamation
End If
End Sub