' 需在VBA编辑器中添加引用:Microsoft XML, v6.0 (或更高版本)
' 工具 -> 引用 -> 勾选 "Microsoft XML, v6.0"
Sub CallKimiAPI()
Dim selectedText As String
Dim apiResponse As String
Dim resultContent As String
' 获取选中文本
On Error Resume Next
selectedText = Selection.Text
If selectedText = "" Then
MsgBox "请先选中要处理的文本"
Exit Sub
End If
' 调用API
apiResponse = SendToKimiAPI(selectedText)
' 解析结果(根据实际API返回格式调整)
resultContent = ParseResponse(apiResponse)
' 插入结果到文档
If resultContent <> "" Then
Selection.InsertAfter vbNewLine & "Kimi回复:" & vbNewLine & resultContent
Else
MsgBox "API返回结果解析失败111"
End If
End Sub
Function SendToKimiAPI(inputText As String) As String
Dim http As New MSXML2.XMLHTTP60
Dim url As String, apiKey As String, requestBody As String
url = "https://api.moonshot.cn/v1/chat/completions"
apiKey = "your_api_key_here"
' 转义特殊字符
inputText = Replace(inputText, """", "\""") ' 转义双引号
inputText = Replace(inputText, "\", "\\") ' 转义反斜杠
' 构建请求体(根据实际API文档调整)
requestBody = "{""model"":""moonshot-v1-8k"",""messages"":[{""role"":""user"",""content"":""" & inputText & """}]}"
' 清除字符串中的回车和换行符
requestBody = Replace(requestBody, vbCrLf, "")
requestBody = Replace(requestBody, vbCr, "")
requestBody = Replace(requestBody, vbLf, "")
On Error GoTo ErrorHandler
With http
.Open "POST", url, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Bearer " & apiKey
.setRequestHeader "Accept", "application/json"
.send requestBody
If .Status = 200 Then
SendToKimiAPI = .responseText
Else
' 显示详细错误信息
MsgBox "API返回错误:" & .Status & " - " & .StatusText & vbNewLine & .responseText
SendToKimiAPI = ""
End If
End With
Exit Function
ErrorHandler:
MsgBox "请求发送失败:" & Err.Description
SendToKimiAPI = ""
End Function
Function ParseResponse(responseText As String) As String
' 自定义解析逻辑(根据实际API返回格式调整)
Dim contentTag As String
Dim startPos As Long
Dim endPos As Long
' 示例解析方式:查找 "content": "..." 模式
contentTag = """content"":"""
startPos = InStr(responseText, contentTag)
If startPos > 0 Then
startPos = startPos + Len(contentTag) + 1 ' 跳过引号
endPos = InStr(startPos, responseText, """")
If endPos > startPos Then
ParseResponse = Mid(responseText, startPos, endPos - startPos)
' 处理转义字符
ParseResponse = Replace(ParseResponse, "\n", vbNewLine)
ParseResponse = Replace(ParseResponse, "\""", """")
End If
End If
End Function
如图所示已成功接入