You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CMD结合Groq API为Llama 4添加对话记忆功能

解决批处理AI部署中对话记忆丢失的问题

你的批处理脚本因为记忆存储格式、读取逻辑和变量引用的错误,导致每次新输入都会破坏有效记忆,无法保留历史对话上下文。以下是问题分析和修正方案:

核心问题分析

  1. 记忆写入格式错误:当前写入memory.txt的内容是("role":"user","content":"xxx"),这类无效格式,带多余括号和逗号,读取拼接后会变成混乱字符串,模型无法解析。
  2. 记忆读取逻辑错误:直接把每行内容无间隔拼接,没有按JSON数组格式处理,导致上下文传递给模型时格式非法。
  3. 变量引用漏洞:用%ai_response%引用延迟扩展赋值的变量,批处理解析顺序会导致无法正确获取最新响应内容。

修正后的完整脚本

@echo off
setlocal EnableDelayedExpansion

set "memory_file=memory.txt"
if not exist "%memory_file%" (
  echo.>"%memory_file%"
)

:loop
color 7
set /p user_input=Prompt: 
if /I "%user_input%"=="exit" goto end

:: 拼接历史对话为JSON数组元素格式
set "history_messages="
set "first_line=1"
for /f "usebackq delims=" %%A in ("%memory_file%") do (
    if "!first_line!"=="1" (
        set "history_messages=%%A"
        set "first_line=0"
    ) else (
        set "history_messages=!history_messages!,%%A"
    )
)

color a
:: 构建符合API规范的请求体
echo { > body.json
echo   "model": "meta-llama/llama-4-scout-17b-16e-instruct", >> body.json
echo   "messages": [ >> body.json
echo     {"role": "system", "content": "You are Julia, a helpful assistant."} >> body.json
if not "!history_messages!"=="" (
    echo     ,!history_messages! >> body.json
)
echo     ,{"role": "user", "content": "%user_input%"} >> body.json
echo   ] >> body.json
echo } >> body.json

curl https://api.groq.com/openai/v1/chat/completions -s ^
-H "Content-Type: application/json" ^
-H "Authorization: Bearer gsk_***************************" ^
-d @body.json > response.json

:: 正确获取AI响应内容
for /f "delims=" %%A in ('powershell -Command "Get-Content response.json | ConvertFrom-Json | Select-Object -ExpandProperty choices | Select-Object -ExpandProperty message | Select-Object -ExpandProperty content"') do (
    set "ai_response=%%A"
)

echo Julia: !ai_response!

:: 写入标准格式的对话到记忆文件
echo {"role":"user","content":"%user_input%"}>>"%memory_file%"
echo {"role":"assistant","content":"!ai_response!"}>>"%memory_file%"

goto loop

:end
REM del body.json
REM del response.json
endlocal

关键修改说明

  • 标准记忆存储:每条对话保存为独立的合法JSON对象(如{"role":"user","content":"你的提问"}),去掉多余符号,确保读取后可直接拼接成JSON数组。
  • 正确拼接历史对话:读取记忆时将所有历史对话拼接成逗号分隔的JSON对象字符串,直接插入到请求的messages数组中,符合Groq API的上下文传递规范。
  • 修复变量引用:用!ai_response!替代%ai_response%,确保延迟扩展环境下变量值被正确读取。
  • 优化请求结构:system prompt仅保留角色设定,历史对话作为独立的messages元素传递,让模型能正确识别上下文序列。

内容的提问来源于stack exchange,提问作者Hacxer_2016

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:49:58