8月312025
Au3调用DeepSeekAPI接口进行AI对话
应群友的需求,结合AI写出,需求个对话用的AI接口,在AU3中使用。
采用 非流式,也就是直接取完整的返回数量。
也就是非那种像打字效果,一点一点出来的那种。
流式也是试过,就是处理相对复杂那么一点点,也会存在卡GUI状态,au3使用不太友好。
; 示例:使用 AutoIt 调用 DeepSeek-V3 聊天API
#include <Json.au3> ; -- 如果没有json函数 ,就去掉,把JY_ChatAPI_BinarySimple中的json解析换成 正则解析
; !!! 配置区 - 开始 !!!
Global $s_API_Key = "sk-需要自己去搞个key" ; 替换成你的真实API密钥 << https://platform.deepseek.com 申请地址
Global $s_API_URL = "https://api.deepseek.com/v1/chat/completions" ;
Global $s_Model = "deepseek-chat" ; 指定要使用的模型
; !!! 配置区 - 结束 !!!
; 构建请求的 JSON 数据
; 这是我们想要发送给AI的消息
Local $s_UserMessage = '你好!能给我写个autoit的示例吗?'
Local $s_JSON_Body = '{"model": "' & $s_Model & '", "messages": [{"role": "user", "content": "' & $s_UserMessage & '"}]}'
; 调用函数发送请求并获取结果
Local $s_AI_Response = JY_ChatAPI_BinarySimple($s_API_URL, $s_API_Key, $s_JSON_Body)
; 显示AI的回复
If @error Then
MsgBox(16, "API 请求错误", "错误: " & @error & @CRLF & "响应: " & $s_AI_Response)
Else
ConsoleWrite("AI 回复:"&@crlf& $s_AI_Response) ; 成功则显示回复
EndIf
; API 访问的DeepSeek大模型接口, 非流式.
Func JY_ChatAPI_BinarySimple($s_URL, $s_Key, $s_Body)
Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1")
If @error Then Return SetError(1, 0, "无法创建WinHTTP对象。")
$oHTTP.Open("POST", $s_URL, False)
$oHTTP.SetRequestHeader("Content-Type", "application/json")
$oHTTP.SetRequestHeader("Authorization", "Bearer " & $s_Key)
$oHTTP.Send($s_Body)
If $oHTTP.Status <> 200 Then
Return SetError($oHTTP.Status, 0, "HTTP错误: " & $oHTTP.StatusText)
EndIf
Local $vResponseData = $oHTTP.ResponseBody
Local $sResponseText = BinaryToString($vResponseData, 4) ; UTF-8转换
;=================================================使用正则解析============<<<<<<<<<<<<<<<< 注意 注意
;=================================================使用正则解析============
; 使用正则表达式匹配content解析时,如果是代码类对话,可能会取值不完整。对用对话没压力
;~ Local $aContent = StringRegExp($sResponseText, '"content":\s*"([^"]+)"', 1)
;~ If @error Then
;~ $aContent = StringRegExp($sResponseText, '"content":\s*"([\s\S]*?)"', 1) ; 再尝试一种可能的情况
;~ EndIf
;~ If @error Or Not IsArray($aContent) Then
;~ Return SetError(5, 0, "无法解析响应内容。原始响应: " & $sResponseText)
;~ EndIf
;~ Local $s_Content = $aContent[0]
; 处理JSON转义字符
;~ $s_Content = StringReplace($s_Content, "\n", @CRLF)
;~ $s_Content = StringReplace($s_Content, '"', '"')
;~ $s_Content = StringReplace($s_Content, "\", "")
;~ $s_Content = StringReplace($s_Content, "\/", "/")
;~ $s_Content = StringReplace($s_Content, "\t", @TAB)
;=================================================使用JSON解析=可正常解析到问到的代码===========
; 使用Json UDF解析响应
Local $oResponse = Json_Decode($sResponseText)
If @error Then
Return SetError(3, 0, "JSON解析失败。原始响应: " & $sResponseText)
EndIf
; 从解析后的对象中提取内容
Local $s_Content = Json_Get($oResponse, ".choices[0].message.content")
If @error Then
; 如果提取内容失败,尝试获取错误信息
Local $s_Error = Json_Get($oResponse, ".error.message")
If @error Then
$s_Error = "无法从响应中提取内容或错误信息。"
EndIf
Return SetError(4, 0, "API返回错误: " & $s_Error)
EndIf
;=================================================END====
Return $s_Content
EndFunc
扫描二维码,在手机上阅读