wps添加AI

By | 2025-02-11

JS宏

/*
 功能:WPS宏调用DeepSeek-API
 作者:E精精  
*/

function callDeepSeekAPI() {
    // API配置
    const apiUrl = "https://api.deepseek.com/chat/completions"; 
    // 替换为你的API密钥
    const apiKey = "sk-4d925b7790c94d1ca815ce24892e9bec"; 

  str_question = Selection.Text;

    // 请求参数
    const requestBody = JSON.stringify({
        "model": "deepseek-chat",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": str_question}
        ],
        "stream": false
      });

    // 创建HTTP请求
    const xhr = new XMLHttpRequest();

    xhr.open("POST", apiUrl, false); // 同步请求
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", "Bearer " + apiKey);
    xhr.send(requestBody);

    // 处理响应
    if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        wt_info(response.choices[0].message.content);
    } else {
        alert("API调用失败!状态码:" + xhr.status + "
          响应内容:" + xhr.responseText);
    }
}

VBS宏

'On Error Resume Next
Function CallDeepSeekAPI(api_key As String, inputText As String) As String
    Dim API As String
    Dim SendTxt As String
    Dim Http As Object
    Dim status_code As Integer
    Dim response As String

    API = "https://api.moonshot.cn/v1/chat/completions"
    postData = "{""model"": ""moonshot-v1-8k"", ""messages"": [{""role"":""system"", ""content"":""你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。""}, {""role"":""user"", ""content"":""" & inputText & """}], ""stream"": false}"


 ' 设置要发送的JSON数据
    'postData = "{""model"": ""moonshot-v1-8k"", ""messages"": ""value2""}" ' JSON格式的数据

    ' 创建XMLHTTP对象
    Set Http = CreateObject("MSXML2.XMLHTTP")

    ' 打开连接并设置请求方法为POST
    With Http
        .Open "POST", API, False
        .setRequestHeader "Content-Type", "application/json" ' 设置请求头为JSON
        .setRequestHeader "Authorization", "Bearer " & api_key
        .send postData ' 发送POST数据
        status_code = .Status
        response = .responseText ' 获取服务器响应
    End With

    ' 输出响应到Immediate窗口(按Ctrl+G查看)
    Debug.Print response

    ' 清理对象
    Set Http = Nothing



    ' 弹出窗口显示 API 响应(调试用)

    'MsgBox "API Response: " & response, vbInformation, "Debug Info"

    If status_code = 200 Then
        CallDeepSeekAPI = response
    Else
        CallDeepSeekAPI = "Error: " & status_code & " - " & response
    End If

    Set Http = Nothing
End Function

Sub DeepSeekV3()
    Dim api_key As String
    Dim inputText As String
    Dim response As String
    Dim regex As Object
    Dim matches As Object
    Dim originalSelection As Object

    api_key = "sk-NAlWuiOeOpI9RqTLW8pqVABdtXY7VsD1IjWJaZEfhRy2M6mJ"
    If api_key = "" Then
        MsgBox "Please enter the API key."
        Exit Sub
    ElseIf Selection.Type <> wdSelectionNormal Then
        MsgBox "Please select text."
        Exit Sub
    End If

    ' 保存原始选中的文本
    Set originalSelection = Selection.Range.Duplicate

    inputText = Replace(Replace(Replace(Replace(Replace(Selection.Text, "\", "\\"), vbCrLf, ""), vbCr, ""), vbLf, ""), Chr(34), "\""")
    'inputText = "你是谁"
    response = CallDeepSeekAPI(api_key, inputText)


    If Left(response, 5) <> "Error" Then
        Set regex = CreateObject("VBScript.RegExp")
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = """content"":""(.*?)"""
        End With
        Set matches = regex.Execute(response)
        If matches.Count > 0 Then
            response = matches(0).SubMatches(0)
            response = Replace(Replace(response, """", Chr(34)), """", Chr(34))
            response = Replace(response, "\n", vbLf)

            ' 取消选中原始文本
            Selection.Collapse Direction:=wdCollapseEnd

            ' 将内容插入到选中文字的下一行
            Selection.TypeParagraph ' 插入新行
            Selection.TypeText Text:=response

            ' 将光标移回原来选中文本的末尾
            originalSelection.Select
        Else
            MsgBox "Failed to parse API response.", vbExclamation
        End If
    Else
        MsgBox response, vbCritical
    End If


End Sub