如题,基于上一篇实现对deepseek的接口调用,这次搞一个高级版的,主要目标:
1、实现对话的流式输出(减少长文本输出的等待,增加交互感)
2、实现对AI的定制,比如要求AI实现定向的对话内容(下文以调教一个text-to-sql 工具为例)
3、实现对AI返回的代码进行识别和截取,以便于后续的动作
ok,废话不多说,先上代码
关于代码方面:主要用到deepseek和智谱AI来帮助完善(帮我写)
#include <iostream>
#include <json/json.h>
#include <curl/curl.h>
#include <vector>
#include <Windows.h>
#include <sstream>
#include <regex>
using namespace std;
// 流式输出专用变量
struct StreamContext {
string buffer; // 原始数据缓冲区
string accumulated; // 累积的完整内容
string currentCode; // 当前代码块内容
vector<string> codes; // 所有提取的代码块
bool inCodeBlock = false; // 代码块状态标记
};
// 回调函数处理流式数据
static size_t WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata) {
StreamContext* ctx = static_cast<StreamContext*>(userdata);
size_t realSize = size * nmemb;
// 累积原始数据
ctx->buffer.append(ptr, realSize);
// 处理完整事件(SSE格式以\n\n结尾)
while (true) {
size_t pos = ctx->buffer.find("\n\n");
if (pos == string::npos) break;
string event = ctx->buffer.substr(0, pos);
ctx->buffer.erase(0, pos + 2);
// 处理有效数据(跳过心跳包等)
if (event.find("data:") == 0) {
string jsonStr = event.substr(5); // 去掉"data: "
if (jsonStr == "[DONE


2837

被折叠的 条评论
为什么被折叠?



