Spaces:
Build error
Build error
File size: 11,867 Bytes
1dd0e3b 4942ce4 1dd0e3b 4942ce4 1dd0e3b 4942ce4 1dd0e3b 4942ce4 18b5ace 4942ce4 1dd0e3b 4942ce4 1dd0e3b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | #ifdef _WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#endif
#include "llm_client.h"
#include <httplib.h>
#include <nlohmann/json.hpp>
#include <iostream>
#include <sstream>
#include <thread>
namespace hhb {
namespace core {
struct LLMClient::Impl {
std::string endpoint;
std::string api_key;
std::string model = "gpt-4o-mini";
int timeout_ms = 60000;
mutable std::string last_error;
mutable std::mutex mutex;
// 具身智能工具注册表:存储 LLM 可调用的 C++ 能力
std::map<std::string, ToolDefinition> tools;
std::string buildToolsJson() const {
nlohmann::json tools_arr = nlohmann::json::array();
for (const auto& [name, tool] : tools) {
nlohmann::json tool_obj;
tool_obj["type"] = "function";
tool_obj["function"]["name"] = tool.name;
tool_obj["function"]["description"] = tool.description;
nlohmann::json params;
try {
params = nlohmann::json::parse(tool.parameters_json_schema);
} catch (...) {
params = nlohmann::json::parse(R"({"type":"object","properties":{}})");
}
tool_obj["function"]["parameters"] = params;
tools_arr.push_back(tool_obj);
}
return tools_arr.dump();
}
std::string sendHttpRequest(const std::string& json_body) const {
last_error.clear();
try {
httplib::Client client(endpoint);
client.set_timeout_sec(timeout_ms / 1000);
httplib::Headers headers;
headers["Content-Type"] = "application/json";
if (!api_key.empty()) {
headers["Authorization"] = "Bearer " + api_key;
}
auto res = client.Post("/v1/chat/completions", headers, json_body, "application/json");
if (res) {
if (res->status == 200) {
return res->body;
} else {
last_error = "HTTP " + std::to_string(res->status) + ": " + res->body.substr(0, 500);
return "";
}
} else {
last_error = client.get_last_error();
if (last_error.empty()) last_error = "Connection failed";
return "";
}
} catch (const std::exception& e) {
last_error = std::string("Exception: ") + e.what();
return "";
}
}
// 解析 LLM 返回的 tool_calls,将语义指令映射为 C++ 可执行结构
std::vector<ToolCall> parseToolCallsFromResponse(const std::string& jsonResponse) const {
std::vector<ToolCall> result;
try {
auto json = nlohmann::json::parse(jsonResponse);
if (!json.contains("choices") || json["choices"].empty()) return result;
auto& message = json["choices"][0].contains("message") ? json["choices"][0]["message"] : json["choices"][0];
// 修复点:不能用 auto& 绑定到临时对象
nlohmann::json tool_calls_json;
if (message.contains("tool_calls")) {
tool_calls_json = message["tool_calls"];
} else {
tool_calls_json = nlohmann::json::array();
}
for (auto& tc : tool_calls_json) {
ToolCall call;
call.id = tc.contains("id") ? tc["id"].get<std::string>() : ("call_" + std::to_string(result.size()));
if (tc.contains("function")) {
auto& func = tc["function"];
call.name = func.contains("name") ? func["name"].get<std::string>() : "";
call.arguments_json = func.contains("arguments") ? func["arguments"].get<std::string>() : "{}";
}
result.push_back(call);
}
} catch (const std::exception& e) {
std::cerr << "Error parsing ToolCalls: " << e.what() << std::endl;
}
return result;
}
// 提取 LLM 文本回复
std::string extractTextContent(const std::string& jsonResponse) const {
try {
auto json = nlohmann::json::parse(jsonResponse);
if (!json.contains("choices") || json["choices"].empty()) return "";
auto& message = json["choices"][0].contains("message") ? json["choices"][0]["message"] : json["choices"][0];
if (message.contains("content")) {
return message["content"].get<std::string>();
}
} catch (const std::exception& e) {
std::cerr << "Error extracting TextContent: " << e.what() << std::endl;
}
return "";
}
// 执行工具调用:将 LLM 的语义参数传入 C++ 回调,获取几何分析结果
ToolResult executeToolCall(const ToolCall& call) const {
ToolResult result;
result.tool_call_id = call.id;
auto it = tools.find(call.name);
if (it == tools.end()) {
result.success = false;
result.result_json = R"({"error": "Unknown tool: )" + call.name + R"("})";
return result;
}
try {
std::string exec_result = it->second.execute(call.arguments_json);
result.success = true;
result.result_json = exec_result;
} catch (const std::exception& e) {
result.success = false;
result.result_json = R"({"error": ")" + std::string(e.what()) + R"("})";
}
return result;
}
};
private:
std::string apiKey_;
std::string endpoint_;
};
LLMClient::LLMClient() : impl_(std::make_unique<Impl>()) {}
LLMClient::~LLMClient() = default;
LLMClient& LLMClient::getInstance() {
static LLMClient instance;
return instance;
}
void LLMClient::setEndpoint(const std::string& endpoint) {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->endpoint = endpoint;
}
void LLMClient::setApiKey(const std::string& api_key) {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->api_key = api_key;
}
void LLMClient::setModel(const std::string& model) {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->model = model;
}
void LLMClient::setTimeout(int timeout_ms) {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->timeout_ms = timeout_ms;
}
void LLMClient::registerTool(const ToolDefinition& tool) {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->tools[tool.name] = tool;
}
void LLMClient::clearTools() {
std::lock_guard<std::mutex> lock(impl_->mutex);
impl_->tools.clear();
}
std::string LLMClient::sendChat(const std::vector<std::map<std::string, std::string>>& messages) {
std::lock_guard<std::mutex> lock(impl_->mutex);
nlohmann::json request;
request["model"] = impl_->model;
request["temperature"] = 0.7;
request["max_tokens"] = 2048;
nlohmann::json msgs = nlohmann::json::array();
for (const auto& msg : messages) {
nlohmann::json m;
for (const auto& [key, val] : msg) {
m[key] = val;
}
msgs.push_back(m);
}
request["messages"] = msgs;
if (!impl_->tools.empty()) {
request["tools"] = nlohmann::json::parse(impl_->buildToolsJson());
request["tool_choice"] = "auto";
}
return impl_->sendHttpRequest(request.dump());
}
std::future<std::string> LLMClient::sendChatAsync(const std::vector<std::map<std::string, std::string>>& messages) {
return std::async(std::launch::async, [this, messages]() {
return sendChat(messages);
});
}
std::string LLMClient::embodiedQuery(const std::string& user_input, int max_rounds) {
std::lock_guard<std::mutex> lock(impl_->mutex);
// 构建初始消息列表
// 具身智能接口:将 3D 拓扑数据转换为 LLM 可理解的语义上下文
nlohmann::json messages = nlohmann::json::array();
nlohmann::json sys_msg;
sys_msg["role"] = "system";
sys_msg["content"] =
"You are an embodied AI CAD assistant. You can analyze 3D models using the provided tools. "
"When the user asks about model properties, weaknesses, or geometry, use the appropriate tool. "
"Always respond in the user's language. Be concise and specific about what you found.";
messages.push_back(sys_msg);
nlohmann::json user_msg;
user_msg["role"] = "user";
user_msg["content"] = user_input;
messages.push_back(user_msg);
for (int round = 0; round < max_rounds; ++round) {
// 构建 OpenAI 兼容的请求体
nlohmann::json request;
request["model"] = impl_->model;
request["temperature"] = 0.7;
request["max_tokens"] = 2048;
request["messages"] = messages;
if (!impl_->tools.empty()) {
request["tools"] = nlohmann::json::parse(impl_->buildToolsJson());
request["tool_choice"] = "auto";
}
std::string response_body = impl_->sendHttpRequest(request.dump());
if (response_body.empty()) {
return "[Error] " + impl_->last_error;
}
// 解析 LLM 响应,检查是否有工具调用
auto tool_calls = impl_->parseToolCallsFromResponse(response_body);
if (tool_calls.empty()) {
// LLM 没有调用工具,直接返回文本回复
return impl_->extractTextContent(response_body);
}
// 将 LLM 的 assistant 消息(含 tool_calls)加入上下文
nlohmann::json assistant_msg;
assistant_msg["role"] = "assistant";
// 重新解析原始响应以保留完整结构
try {
nlohmann::json resp = nlohmann::json::parse(response_body);
assistant_msg = resp["choices"][0]["message"];
} catch (...) {
assistant_msg["content"] = impl_->extractTextContent(response_body);
}
messages.push_back(assistant_msg);
// 执行每个工具调用,将结果反馈给 LLM
for (const auto& tc : tool_calls) {
std::cout << "[EmbodiedAI] Tool call: " << tc.name
<< " args: " << tc.arguments_json << std::endl;
ToolResult result = impl_->executeToolCall(tc);
std::cout << "[EmbodiedAI] Tool result: success=" << result.success
<< " result=" << result.result_json.substr(0, 200) << std::endl;
// 将工具执行结果作为 tool message 反馈给 LLM
nlohmann::json tool_msg;
tool_msg["role"] = "tool";
tool_msg["tool_call_id"] = result.tool_call_id;
tool_msg["content"] = result.result_json;
messages.push_back(tool_msg);
}
}
// 达到最大轮次,做最后一次请求获取最终文本回复
nlohmann::json final_request;
final_request["model"] = impl_->model;
final_request["temperature"] = 0.7;
final_request["max_tokens"] = 2048;
final_request["messages"] = messages;
std::string final_response = impl_->sendHttpRequest(final_request.dump());
if (final_response.empty()) {
return "[Error] " + impl_->last_error;
}
return impl_->extractTextContent(final_response);
}
std::future<std::string> LLMClient::embodiedQueryAsync(const std::string& user_input, int max_rounds) {
return std::async(std::launch::async, [this, user_input, max_rounds]() {
return embodiedQuery(user_input, max_rounds);
});
}
std::string LLMClient::getLastError() const {
return impl_->last_error;
}
std::vector<std::string> LLMClient::getRegisteredToolNames() const {
std::lock_guard<std::mutex> lock(impl_->mutex);
std::vector<std::string> names;
for (const auto& [name, _] : impl_->tools) {
names.push_back(name);
}
return names;
}
} // namespace core
} // namespace hhb
|