libkysdk-ai-private/0000775000175000017500000000000015160473263013362 5ustar fengfenglibkysdk-ai-private/ai-assistant/0000775000175000017500000000000015160473263015762 5ustar fengfenglibkysdk-ai-private/ai-assistant/error.cpp0000664000175000017500000000745515160473263017632 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "osassistant/error.h" // #include "nlp.h" // #include "vision.h" namespace kyai { namespace assistant { enum NlpResult { NLP_SUCCESS = 0, NLP_SESSION_ERROR, // session 错误 NLP_NET_ERROR, // 网络错误 NLP_SERVER_ERROR, // 服务错误或者不可用 NLP_UNAUTHORIZED, // 权限限制,鉴权失败,无权访问 NLP_REQUEST_TOO_MANY, // 请求频率过高 NLP_REQUEST_FAILED, // 请求失败 NLP_INPUT_TEXT_LENGTH_INVAILD, // 输入文本长度超限 NLP_PARAM_ERROR, // 参数错误 }; ErrorCode Error::getCodeFromNlpError(int errorCode) { switch (errorCode) { case NLP_SUCCESS: return ErrorCode::Ok; case NLP_SESSION_ERROR: return ErrorCode::ServerError; case NLP_NET_ERROR: return ErrorCode::NetError; case NLP_SERVER_ERROR: return ErrorCode::ServerError; case NLP_UNAUTHORIZED: return ErrorCode::UnAuthorized; case NLP_REQUEST_TOO_MANY: return ErrorCode::RequestTooMany; case NLP_REQUEST_FAILED: return ErrorCode::RequestFailed; case NLP_INPUT_TEXT_LENGTH_INVAILD: return ErrorCode::InputTextLengthInvaild; case NLP_PARAM_ERROR: return ErrorCode::ParamError; default: return ErrorCode::Ok; } return ErrorCode::Ok; } enum VisionResult { VISION_SUCCESS = 0, VISION_SESSION_ERROR, VISION_NET_ERROR, // 网络错误 VISION_SERVER_ERROR, // 服务错误或者不可用 VISION_UNAUTHORIZED, // 权限限制,鉴权失败,无权访问 VISION_REQUEST_TOO_MANY, // 请求频率过高 VISION_REQUEST_FAILED, // 请求失败 VISION_TASK_TIMEOUT, // 任务超时 VISION_INPUT_TEXT_LENGTH_INVAILD, // 输入文本长度超限 VISION_GENERATE_IMAGE_FAILED, // 生成图片失败 VISION_GENERATE_IMAGE_BLOCKED, // 图片审核失败 VISION_PARAM_ERROR, // 参数错误 }; ErrorCode Error::getCodeFromVisionError(int errorCode) { switch (errorCode) { case VISION_SUCCESS: return ErrorCode::Ok; case VISION_SESSION_ERROR: return ErrorCode::ServerError; case VISION_NET_ERROR: return ErrorCode::NetError; case VISION_SERVER_ERROR: return ErrorCode::ServerError; case VISION_UNAUTHORIZED: return ErrorCode::UnAuthorized; case VISION_REQUEST_TOO_MANY: return ErrorCode::RequestTooMany; case VISION_REQUEST_FAILED: return ErrorCode::RequestFailed; case VISION_TASK_TIMEOUT: return ErrorCode::TaskTimeout; case VISION_INPUT_TEXT_LENGTH_INVAILD: return ErrorCode::InputTextLengthInvaild; case VISION_GENERATE_IMAGE_FAILED: return ErrorCode::GenerateImageFailed; case VISION_GENERATE_IMAGE_BLOCKED: return ErrorCode::GenerateImageBlocked; default: return ErrorCode::Ok; } return ErrorCode::Ok; } } // namespace assistant } // namespace kyai libkysdk-ai-private/ai-assistant/serverproxy.cpp0000664000175000017500000000367015160473263021104 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "serverproxy.h" namespace { const std::string serverUnixPath = "unix:path=/tmp/.kylin-ai-runtime-unix/" + std::to_string(getuid()) + "/assistant.sock"; } ServerProxy &ServerProxy::getInstance() { static ServerProxy instance{}; return instance; } ServerProxy::ServerProxy() { init(); } ServerProxy::~ServerProxy() { destroy(); } const std::string ServerProxy::getUnixPath() { return serverUnixPath; } void ServerProxy::exec() { loop_ = g_main_loop_new(nullptr, false); g_main_loop_run(loop_); } void ServerProxy::quit() { if (loop_ == nullptr) { return; } g_main_loop_quit(loop_); } void ServerProxy::init() { GError *error = nullptr; connection_ = g_dbus_connection_new_for_address_sync( serverUnixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, /* GDBusAuthObserver */ nullptr, /* GCancellable */ &error); if (connection_ == nullptr) { g_printerr("Error connecting to D-Bus address %s: %s\n", serverUnixPath.c_str(), error->message); g_error_free(error); return; } } void ServerProxy::destroy() { if (connection_ != nullptr) { g_object_unref(connection_); } } libkysdk-ai-private/ai-assistant/CMakeLists.txt0000664000175000017500000000405515160473263020526 0ustar fengfengcmake_minimum_required(VERSION 3.5) project(kyai-assistant LANGUAGES CXX C) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) ####################################################################### # Options ####################################################################### option(ENABLE_TEST "Build Test" OFF) # jsoncpp find_package(jsoncpp REQUIRED) # pkg-config find_package(PkgConfig REQUIRED) # glib pkg_check_modules(GIO REQUIRED gio-unix-2.0) include_directories(${GIO_INCLUDE_DIRS}) # kylin-ai-proto find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(COMMON_PROTO_FILES assistantservice) include_directories(include) include_directories(src) include_directories(include/kylin-ai/private) add_library(kyai-assistant SHARED include/kylin-ai/private/osassistant/kyaiexport.h include/kylin-ai/private/osassistant/osassistant.h include/kylin-ai/private/osassistant/error.h promptidmanager.h promptidmanager.cpp error.cpp osassistant.cpp assistantserviceproxy.cpp serverproxy.cpp ${COMMON_PROTO_FILES} ) # 添加库导出宏定义 target_compile_definitions(kyai-assistant PRIVATE KYAI_ASSISTANT_BUILDING_LIB) # 设置符号可见性 if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") endif () if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9) target_link_libraries(kyai-assistant stdc++fs) endif () endif () if (ENABLE_TEST) enable_testing() add_subdirectory(test) endif () set_target_properties(kyai-assistant PROPERTIES VERSION 1.0.0 SOVERSION 1 ) target_link_libraries( kyai-assistant ${GIO_LIBRARIES} jsoncpp ) include(CMakePackageConfigHelpers) include(GNUInstallDirs) install(TARGETS kyai-assistant DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(DIRECTORY include/kylin-ai DESTINATION include) install(DIRECTORY usr/ DESTINATION /usr) libkysdk-ai-private/ai-assistant/osassistant.cpp0000664000175000017500000000677715160473263021062 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "osassistant/osassistant.h" #include #include "assistantserviceproxy.h" namespace kyai { namespace assistant { class OsAssistantPrivate { public: OsAssistantPrivate(); Error init(); Error initWithChatHistory(std::vector messages, int promptId); ChatResultCallback chatResultCallabck; AssistantServiceProxy proxy; private: std::tuple getNlpAndVisionConfigs(); }; OsAssistantPrivate::OsAssistantPrivate() {} Error OsAssistantPrivate::init() { return proxy.init(); } Error OsAssistantPrivate::initWithChatHistory(std::vector messages, int promptId) { return proxy.initWithChatHistory(messages, promptId); } OsAssistant::OsAssistant() : assistantPrivate_(std::make_unique()) {} OsAssistant::~OsAssistant() = default; Error OsAssistant::init() { return assistantPrivate_->init(); } Error OsAssistant::initWithChatHistory(std::vector messages, int promptId) { return assistantPrivate_->initWithChatHistory(messages, promptId); } void OsAssistant::setChatAsyncCallback(ChatResultCallback callback) { assistantPrivate_->chatResultCallabck = std::move(callback); assistantPrivate_->proxy.setChatResultCallback( assistantPrivate_->chatResultCallabck); } Features OsAssistant::supportedFeatures() const { return assistantPrivate_->proxy.supportedFeatures(); } void OsAssistant::chatAsync(const std::string &message) { assistantPrivate_->proxy.chatAsync(message); } void OsAssistant::stopChat() { assistantPrivate_->proxy.stopChat(); } void OsAssistant::setPromptId(int promptId) { assistantPrivate_->proxy.setPromptId(promptId); } void OsAssistant::clearContext() { assistantPrivate_->proxy.clearContext(); } std::vector OsAssistant::prompts() { return assistantPrivate_->proxy.prompts(); } bool OsAssistant::setPromptOrder(std::list promptIdList) { return assistantPrivate_->proxy.setPromptOrder(promptIdList); } int OsAssistant::createPrompt(std::string name, std::string content) { return assistantPrivate_->proxy.createPrompt(name, content); } bool OsAssistant::deletePrompt(int promptId) { return assistantPrivate_->proxy.deletePrompt(promptId); } bool OsAssistant::updatePrompt(int promptId, std::string name, std::string content) { return assistantPrivate_->proxy.updatePrompt(promptId, name, content); } std::string OsAssistant::getConfiguredNlpModelInfos() const { return assistantPrivate_->proxy.getConfiguredNlpModelInfos(); } void OsAssistant::setCurrentNlpModel(const std::string &modelName) const { assistantPrivate_->proxy.setCurrentNlpModel(modelName); } } // namespace assistant } // namespace kyai libkysdk-ai-private/ai-assistant/assistantserviceproxy.cpp0000664000175000017500000004063615160473263023173 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "assistantserviceproxy.h" #include #include #include #include #include #include #include "assistantserviceglue.h" #include "osassistant/error.h" #include "serverproxy.h" namespace { const char *serverCloseErrorMessage = R"( { "error_code": 2, "error_message": "服务异常,请检查后台服务是否正常运行。" } )"; } namespace kyai { namespace assistant { const char *objectPath = "/com/kylin/AiRuntime/Assistant"; const char *assistantResultInterface = "com.kylin.AiRuntime.Assistant"; void AssistantServiceProxy::onChatResult( GDBusConnection *connection, const gchar *sender_name, const gchar *object_path, const gchar *interface_name, const gchar *signal_name, GVariant *parameters, gpointer user_data) { auto *proxy = static_cast(user_data); GVariantIter iter; g_variant_iter_init(&iter, parameters); GVariant *char_result = g_variant_iter_next_value(&iter); GVariant *int_errorCode = g_variant_iter_next_value(&iter); if (!char_result || !int_errorCode) { fprintf(stderr, "set chat result callback error: result is nullptr!\n"); return; } char *result = (char *)g_variant_get_data(char_result); int *errorCode = (int *)g_variant_get_data(int_errorCode); if (!result || !errorCode) { fprintf(stderr, "set chat result callback error: error code is nullptr!\n"); return; } if (proxy->chatResultCallback_) { proxy->chatResultCallback_(result); } } AssistantServiceProxy::AssistantServiceProxy() { initServerProxy(); } AssistantServiceProxy::~AssistantServiceProxy() { if (delegate_ != nullptr) { g_object_unref(delegate_); } } void AssistantServiceProxy::initServerProxy() { if (!ServerProxy::getInstance().available()) { std::string errMessage{ "Error creating sssistant service proxy: Server proxy " "connection is unavailable.\n"}; std::fprintf(stderr, "%s", errMessage.c_str()); if (!retryConnectToServer()) { return; } } createDelegate(); } Error AssistantServiceProxy::init() { gint errorCode; gchar *errorMessage{nullptr}; GError *gError{nullptr}; std::fprintf(stdout, "Init assistant service proxy...\n"); if (!delegate_) { return {ErrorCode::ServerError, "Server delegate no inited."}; } bool ret = ai_runtime_assistant_call_init_sync( delegate_, &sessionId_, &errorCode, &errorMessage, nullptr, &gError); if (sessionId_ > 0) { std::fprintf(stdout, "Init assistant service proxy success...%d\n", sessionId_); connectSignal(); } if (gError) { std::fprintf(stderr, "Error: %s\n", gError->message); const std::string errMessage{gError->message}; g_error_free(gError); return {ErrorCode::ServerError, errMessage}; } std::fprintf(stdout, "Session ID: %d\n", sessionId_); if (errorCode != (int)ErrorCode::Ok) { std::fprintf(stderr, "Error: %s\n", errorMessage); return {ErrorCode(errorCode), errorMessage}; } return {ErrorCode::Ok}; } Error AssistantServiceProxy::initWithChatHistory( const std::vector &messages, int promptId) { if (!delegate_) { return {ErrorCode::ServerError, "Server delegate no inited."}; } gint errorCode; gchar *errorMessage{nullptr}; GError *gError{nullptr}; gboolean success = ai_runtime_assistant_call_init_with_chat_history_sync( delegate_, messageVectorToJson(messages).c_str(), promptId, &sessionId_, &errorCode, &errorMessage, nullptr, &gError); if (gError) { std::fprintf(stderr, "Error: %s\n", gError->message); const std::string errMessage{gError->message}; g_error_free(gError); return {ErrorCode::ServerError, errMessage}; } if (!success) { std::fprintf(stderr, "Error: %s\n", "initWithChatHistory failed."); return {ErrorCode(errorCode), errorMessage}; } std::fprintf(stdout, "Session ID: %d\n", sessionId_); if (errorCode != (int)ErrorCode::Ok) { std::fprintf(stderr, "Error: %s\n", errorMessage); return {ErrorCode(errorCode), errorMessage}; } connectSignal(); return {ErrorCode::Ok}; } void AssistantServiceProxy::setChatResultCallback(ChatResultCallback callback) { chatResultCallback_ = std::move(callback); } Features AssistantServiceProxy::supportedFeatures() const { if (!delegate_) { return Features{0}; } gint features{0}; GError *error{nullptr}; gboolean success = ai_runtime_assistant_call_supported_features_sync( delegate_, sessionId_, &features, nullptr, &error); if (error) { std::fprintf(stderr, "Error calling supportedFuntions: %s\n", error->message); g_error_free(error); return Features{0}; } if (!success) { std::fprintf( stderr, "Call to supportedFeatures failed without an error message.\n"); return Features{0}; } return Features{features}; } void AssistantServiceProxy::onCallFinished(GObject *source_object, GAsyncResult *res, gpointer user_data) { GError *error = nullptr; GDBusProxy *proxy = G_DBUS_PROXY(source_object); GVariant *result; result = g_dbus_proxy_call_finish(proxy, res, &error); if (!error) { return; } g_printerr("Error during call: %s\n", error->message); AssistantServiceProxy *asssistantServiceproxy = static_cast(user_data); // server closed if (error->code == 18) { asssistantServiceproxy->handleServerClosed(); } g_error_free(error); } void AssistantServiceProxy::chatAsync(const std::string &message) { if (!delegate_) { return; } currentMessage_ = message; ai_runtime_assistant_call_chat(delegate_, message.c_str(), sessionId_, nullptr, onCallFinished, this); } void AssistantServiceProxy::stopChat() { if (!delegate_) { return; } ai_runtime_assistant_call_stop_chat(delegate_, sessionId_, nullptr, nullptr, nullptr); } void AssistantServiceProxy::setPromptId(int id) { if (!delegate_) { return; } currentActorId_ = id; ai_runtime_assistant_call_set_prompt_id(delegate_, sessionId_, id, nullptr, onCallFinished, this); } void AssistantServiceProxy::clearContext() { if (!delegate_) { return; } currentActorId_ = -1; currentMessage_.clear(); ai_runtime_assistant_call_clear_context(delegate_, sessionId_, nullptr, nullptr, nullptr); } std::vector AssistantServiceProxy::prompts() { if (!delegate_) { return {}; } gchar *allPrompts = nullptr; GError *error = nullptr; std::vector promptVector{}; gboolean success = ai_runtime_assistant_call_prompts_sync( delegate_, sessionId_, &allPrompts, nullptr, &error); if (!success) { std::fprintf(stderr, "Call to prompts failed without an error message.\n"); return {}; } if (error) { std::fprintf(stderr, "Error calling prompts: %s\n", error->message); g_error_free(error); return {}; } parseJsonStringToVector(allPrompts, promptVector); if (promptIdManager_.promptIdList().empty()) { setDefaultPromptIdList(promptVector); } adjustPromptOrder(promptVector); return promptVector; } bool AssistantServiceProxy::setPromptOrder(std::list promptIdList) { if (!delegate_) { return false; } return promptIdManager_.updatePromptIdOrder(promptIdList); } int AssistantServiceProxy::createPrompt(const std::string &name, const std::string &content) { if (!delegate_) { return -1; } gint promptId = -1; GError *error = nullptr; gboolean success = ai_runtime_assistant_call_create_prompt_sync( delegate_, name.c_str(), content.c_str(), &promptId, nullptr, &error); if (!success) { std::fprintf(stderr, "Call to createPrompt failed without an error " "message.\n"); return -1; } if (error) { std::fprintf(stderr, "Error calling createPrompt: %s\n", error->message); g_error_free(error); return -1; } if (promptId == -1) { return -1; } if (!promptIdManager_.addPromptId(promptId)) { return -1; } return (int)promptId; } bool AssistantServiceProxy::deletePrompt(int promptId) { if (!delegate_) { return false; } GError *error = nullptr; gboolean success = false; if (!promptIdManager_.deletePromptId(promptId)) { return false; } gboolean ret = ai_runtime_assistant_call_delete_prompt_sync( delegate_, promptId, &success, nullptr, &error); if (error) { std::fprintf(stderr, "Error calling deletePrompt: %s\n", error->message); g_error_free(error); return false; } if (!ret) { std::fprintf(stderr, "Call to deletePrompt failed without an error " "message.\n"); return false; } return success; } bool AssistantServiceProxy::updatePrompt(int promptId, const std::string &name, const std::string &content) { if (!delegate_) { return false; } GError *error = nullptr; gboolean success = false; gboolean ret = ai_runtime_assistant_call_update_prompt_sync( delegate_, promptId, name.c_str(), content.c_str(), &success, nullptr, &error); if (error) { std::fprintf(stderr, "Error calling updatePrompt: %s\n", error->message); g_error_free(error); return false; } if (!ret) { std::fprintf(stderr, "Call to updatePrompt failed without an error " "message.\n"); return false; } return success; } void AssistantServiceProxy::connectSignal() { auto *connection = ServerProxy::getInstance().getConnection(); std::string interfaceName = assistantResultInterface + std::to_string(sessionId_); g_dbus_connection_signal_subscribe( connection, nullptr, interfaceName.c_str(), "ChatResult", objectPath, NULL, G_DBUS_SIGNAL_FLAGS_NONE, onChatResult, this, nullptr); } void AssistantServiceProxy::createDelegate() { GError *error = nullptr; auto *connection = ServerProxy::getInstance().getConnection(); delegate_ = ai_runtime_assistant_proxy_new_sync( connection, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath, nullptr, &error); if (delegate_ == nullptr) { g_printerr("Error creating speech processor proxy %s: %s\n", objectPath, error->message); g_error_free(error); } } void AssistantServiceProxy::handleServerClosed() { if (retryConnectToServer()) { if (currentActorId_ != -1) { setPromptId(currentActorId_); } if (!currentMessage_.empty()) { chatAsync(currentMessage_); } } else { if (chatResultCallback_) { chatResultCallback_(serverCloseErrorMessage); } } } bool AssistantServiceProxy::retryConnectToServer() { std::fprintf(stdout, "Server closed, retrying to connect...\n"); int retryCount = 0; while (retryCount < 10) { ServerProxy::getInstance().init(); if (ServerProxy::getInstance().available()) { createDelegate(); init(); return true; } std::this_thread::sleep_for(std::chrono::seconds(1)); retryCount++; } return false; } void AssistantServiceProxy::setDefaultPromptIdList( const std::vector prompts) { std::list idList; for (auto prompt : prompts) { idList.push_back(prompt.id); } promptIdManager_.setDefaultPromptIdList(idList); } void AssistantServiceProxy::parseJsonStringToVector( const std::string &jsonString, std::vector &prompts) { if (jsonString.empty()) { fprintf(stderr, "AssistantServiceProxy parseJsonStringToVector: jsonString is " "empty!\n"); return; } Json::Value root; Json::CharReaderBuilder builder; Json::CharReader *reader = builder.newCharReader(); std::string errors; bool parsingSuccessful = reader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), &root, &errors); delete reader; if (!parsingSuccessful) { fprintf(stderr, "AssistantServiceProxy parseJsonStringToVector: failed to " "parse JSON: %s\n", errors.c_str()); return; } prompts.clear(); for (const auto &item : root) { Prompt newPrompt; newPrompt.id = item["id"].asInt(); newPrompt.name = item["name"].asString(); newPrompt.content = item["content"].asString(); newPrompt.type = (kyai::assistant::PromptContentAccessType)item["type"].asInt(); newPrompt.active = item["active"].asBool(); prompts.push_back(newPrompt); } } std::string AssistantServiceProxy::messageVectorToJson( const std::vector &messages) { Json::Value jsonArray(Json::arrayValue); for (const auto &message : messages) { Json::Value jsonMessage; jsonMessage["user"] = message.user; jsonMessage["assistant"] = message.assistant; jsonArray.append(jsonMessage); } Json::StyledWriter writer; return writer.write(jsonArray); } void AssistantServiceProxy::adjustPromptOrder(std::vector &prompts) { std::list promptIdList = promptIdManager_.promptIdList(); if (promptIdList.empty()) { return; } std::vector newPrompts{}; for (int promptId : promptIdList) { for (const auto &prompt : prompts) { if (prompt.id != promptId) { continue; } newPrompts.push_back(prompt); } } // 找到没有在promptIdList中的prompt for (const auto &prompt : prompts) { if (promptIdList.end() == std::find(promptIdList.begin(), promptIdList.end(), prompt.id)) { newPrompts.push_back(prompt); } } prompts = newPrompts; } std::string AssistantServiceProxy::getConfiguredNlpModelInfos() const { gchar *configuredNlpModelInfos{nullptr}; GError *error = nullptr; ai_runtime_assistant_call_get_configured_nlp_model_list_sync( delegate_, sessionId_, &configuredNlpModelInfos, nullptr, &error); if (error != nullptr) { std::fprintf(stderr, "Error calling getConfiguredNlpModelInfos: %s\n", error->message); g_error_free(error); return ""; } if (configuredNlpModelInfos == nullptr) { return ""; } std::string ret(configuredNlpModelInfos); g_free(configuredNlpModelInfos); return ret; } void AssistantServiceProxy::setCurrentNlpModel( const std::string &modelName) const { GError *error = nullptr; ai_runtime_assistant_call_set_current_nlp_model_sync( delegate_, sessionId_, modelName.c_str(), nullptr, &error); if (error != nullptr) { std::fprintf(stderr, "Error calling setCurrentNlpModel: %s\n", error->message); g_error_free(error); } } } // namespace assistant } // namespace kyai libkysdk-ai-private/ai-assistant/usr/0000775000175000017500000000000015160473263016573 5ustar fengfenglibkysdk-ai-private/ai-assistant/usr/share/0000775000175000017500000000000015160473263017675 5ustar fengfenglibkysdk-ai-private/ai-assistant/usr/share/pkgconfig/0000775000175000017500000000000015160473263021644 5ustar fengfenglibkysdk-ai-private/ai-assistant/usr/share/pkgconfig/kyai-assistant.pc0000664000175000017500000000021515160473263025132 0ustar fengfengName: libkyai-assistant Description: Kylin ai assistant library Version: 1.0.0 Libs: -lkyai-assistant Cflags: -I/usr/include/kylin-ai/privatelibkysdk-ai-private/ai-assistant/serverproxy.h0000664000175000017500000000235515160473263020550 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef SERVICES_SERVERPOXY_H #define SERVICES_SERVERPOXY_H #include #include class ServerProxy { public: static ServerProxy &getInstance(); ~ServerProxy(); static const std::string getUnixPath(); bool available() const { return connection_ != nullptr; } GDBusConnection *getConnection() const { return connection_; } void exec(); void quit(); void init(); private: ServerProxy(); void destroy(); private: GDBusConnection *connection_ = nullptr; GMainLoop *loop_ = nullptr; }; #endif libkysdk-ai-private/ai-assistant/promptidmanager.h0000664000175000017500000000300715160473263021324 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef PROMPTIDMANAGER_H #define PROMPTIDMANAGER_H #include #include #include #include #include #include #include class PromptIdManager { public: PromptIdManager(); void setDefaultPromptIdList(const std::list& idList); std::list promptIdList(); bool addPromptId(int id); bool deletePromptId(int id); bool updatePromptIdOrder(const std::list& newOrder); private: void loadPromptIdList(); bool savePromptIdList(); void createConfigFile(); void readConfigFile(); private: const std::string configDir_ = std::string(getenv("HOME")) + "/.config/kylin-ai"; const std::string configPath_ = std::string(getenv("HOME")) + "/.config/kylin-ai/promptOrder.conf"; std::list promptIdList_; }; #endif libkysdk-ai-private/ai-assistant/assistantserviceproxy.h0000664000175000017500000000625115160473263022633 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef ASSISTANTSERVICEPROXY_H #define ASSISTANTSERVICEPROXY_H #include "assistantserviceglue.h" #include "osassistant/error.h" #include "osassistant/osassistant.h" #include "promptidmanager.h" namespace kyai { namespace assistant { class AssistantServiceProxy { public: AssistantServiceProxy(); ~AssistantServiceProxy(); void initServerProxy(); Error init(); Error initWithChatHistory(const std::vector &messages, int promptId); void setChatResultCallback(ChatResultCallback callback); Features supportedFeatures() const; void chatAsync(const std::string &message); void stopChat(); void setPromptId(int id); void clearContext(); std::vector prompts(); bool setPromptOrder(std::list promptIdList); int createPrompt(const std::string &name, const std::string &content); bool deletePrompt(int promptId); bool updatePrompt(int promptId, const std::string &name, const std::string &content); std::string getConfiguredNlpModelInfos() const; void setCurrentNlpModel(const std::string &modelName) const; private: void connectSignal(); void createDelegate(); void handleServerClosed(); bool retryConnectToServer(); void setDefaultPromptIdList(const std::vector prompts); static void onChatResult(GDBusConnection *connection, const gchar *sender_name, const gchar *object_path, const gchar *interface_name, const gchar *signal_name, GVariant *parameters, gpointer user_data); static void onCallFinished(GObject *source_object, GAsyncResult *res, gpointer user_data); void parseJsonStringToVector(const std::string &jsonString, std::vector &prompts); std::string messageVectorToJson(const std::vector &messages); void adjustPromptOrder(std::vector &prompts); private: struct EngineConfig { std::string nlpEngineName; std::string nlpConfig; std::string visionEngineName; std::string visionConfig; }; private: AiRuntimeAssistant *delegate_{nullptr}; int sessionId_{0}; ChatResultCallback chatResultCallback_; std::string currentMessage_; int currentActorId_{-1}; PromptIdManager promptIdManager_; }; } // namespace assistant } // namespace kyai #endif // ASSISTANTSERVICEPROXY_H libkysdk-ai-private/ai-assistant/promptidmanager.cpp0000664000175000017500000000724615160473263021670 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "promptidmanager.h" #include #include #include PromptIdManager::PromptIdManager() { loadPromptIdList(); } void PromptIdManager::setDefaultPromptIdList(const std::list& idList) { if (!promptIdList_.empty()) { return; } promptIdList_ = idList; savePromptIdList(); } std::list PromptIdManager::promptIdList() { return promptIdList_; } bool PromptIdManager::addPromptId(int id) { if (std::find(promptIdList_.begin(), promptIdList_.end(), id) != promptIdList_.end()) { fprintf(stderr, "Add prompt failed, %i %s", id, "already exists!\n"); return false; } promptIdList_.push_back(id); return savePromptIdList(); } bool PromptIdManager::deletePromptId(int id) { if (std::find(promptIdList_.begin(), promptIdList_.end(), id) == promptIdList_.end()) { fprintf(stderr, "Failed to delete prompt word id, %i %s", id, "not exists!\n"); return false; } promptIdList_.remove(id); return savePromptIdList(); } bool PromptIdManager::updatePromptIdOrder(const std::list& newOrder) { promptIdList_ = newOrder; return savePromptIdList(); } void PromptIdManager::loadPromptIdList() { struct stat buffer; bool fileExists = (stat(configPath_.c_str(), &buffer) == 0); if (!fileExists) { createConfigFile(); } else { if (buffer.st_size == 0) { createConfigFile(); } else { readConfigFile(); } } } bool PromptIdManager::savePromptIdList() { std::ofstream file(configPath_, std::ios::out | std::ios::trunc); if (!file.is_open()) { fprintf(stderr, "Failed to open configuration file: %s\n", configPath_.c_str()); return false; } for (auto it = promptIdList_.begin(); it != promptIdList_.end(); ++it) { file << *it; file << ","; } file.close(); return true; } void PromptIdManager::createConfigFile() { namespace fs = std::filesystem; if (!fs::exists(configDir_)) { if (!fs::create_directories(configDir_)) { fprintf(stderr, "Failed to create directory: %s\n", configDir_.c_str()); return; } } std::ofstream file(configPath_); if (!file.is_open()) { fprintf(stderr, "Failed to create configuration file: %s\n", configPath_.c_str()); return; } file.close(); } void PromptIdManager::readConfigFile() { std::ifstream file(configPath_); if (!file.is_open()) { fprintf(stderr, "Failed to read configuration file: %s\n", configPath_.c_str()); return; } std::string line; if (std::getline(file, line)) { std::stringstream ss(line); std::string idStr; promptIdList_.clear(); while (std::getline(ss, idStr, ',')) { int id = std::stoi(idStr); promptIdList_.push_back(id); } } file.close(); } libkysdk-ai-private/ai-assistant/include/0000775000175000017500000000000015160473263017405 5ustar fengfenglibkysdk-ai-private/ai-assistant/include/kylin-ai/0000775000175000017500000000000015160473263021122 5ustar fengfenglibkysdk-ai-private/ai-assistant/include/kylin-ai/private/0000775000175000017500000000000015160473263022574 5ustar fengfenglibkysdk-ai-private/ai-assistant/include/kylin-ai/private/osassistant/0000775000175000017500000000000015160473263025147 5ustar fengfenglibkysdk-ai-private/ai-assistant/include/kylin-ai/private/osassistant/kyaiexport.h0000664000175000017500000000271015160473263027517 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_PRIVATE_EXPORT_H__ #define __KYLIN_AI_PRIVATE_EXPORT_H__ // 定义导出宏 #if defined(_WIN32) || defined(__CYGWIN__) #ifdef KYAI_ASSISTANT_BUILDING_LIB #ifdef __GNUC__ #define KYAI_ASSISTANT_EXPORT __attribute__ ((dllexport)) #else #define KYAI_ASSISTANT_EXPORT __declspec(dllexport) #endif #else #ifdef __GNUC__ #define KYAI_ASSISTANT_EXPORT __attribute__ ((dllimport)) #else #define KYAI_ASSISTANT_EXPORT __declspec(dllimport) #endif #endif #else #if __GNUC__ >= 4 #define KYAI_ASSISTANT_EXPORT __attribute__ ((visibility ("default"))) #else #define KYAI_ASSISTANT_EXPORT #endif #endif #endif // __KYLIN_AI_PRIVATE_EXPORT_H__libkysdk-ai-private/ai-assistant/include/kylin-ai/private/osassistant/error.h0000664000175000017500000000376615160473263026465 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_PRIVATE_OS_ASSISTANT_ERROR_H__ #define __KYLIN_AI_PRIVATE_OS_ASSISTANT_ERROR_H__ #include #include "kyaiexport.h" namespace kyai { namespace assistant { enum class ErrorCode { Ok = 0, NetError, ServerError, UnAuthorized, RequestTooMany, RequestFailed, InputTextLengthInvaild, TaskTimeout, GenerateImageFailed, GenerateImageBlocked, ParamError, InputTextInvaild, FileNotFound, IntentServerError, NlpServerError, VisionServerError, InputTextBlocked, OutputTextBlocked, SystemOperationFailed, IntentionRecognitionFailed, NlpModelNotFound, VisionModelNotFound, FileExceedSizeLimit, FileParseFailed, CreateScheduleFailed, CreateToDoListFailed, IntentNlpModelNotFound, FreeAllocatedQuotaExceeded, LocalNlpModelNotLoaded, SslCertificateError, FileDatabaseCorrupted, UnknownError = 10000, }; class KYAI_ASSISTANT_EXPORT Error { public: ErrorCode code = ErrorCode::Ok; std::string message{}; explicit operator bool() const { return code != ErrorCode::Ok; } static ErrorCode getCodeFromNlpError(int errorCode); static ErrorCode getCodeFromVisionError(int errorCode); }; } // namespace assistant } // namespace kyai #endif // __KYLIN_AI_PRIVATE_OS_ASSISTANT_ERROR_H__ libkysdk-ai-private/ai-assistant/include/kylin-ai/private/osassistant/osassistant.h0000664000175000017500000000531515160473263027677 0ustar fengfeng/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_PRIVATE_OS_ASSISTANT_H__ #define __KYLIN_AI_PRIVATE_OS_ASSISTANT_H__ #include #include #include #include #include "error.h" #include "kyaiexport.h" namespace kyai { namespace assistant { // json chat result using ChatResultCallback = std::function; enum PromptContentAccessType { ReadOnly = 1, ReadWrite, NoAccess }; struct KYAI_ASSISTANT_EXPORT Prompt { int id; std::string name; std::string content; PromptContentAccessType type; bool active : 8; }; struct KYAI_ASSISTANT_EXPORT Message { std::string user; std::string assistant; }; class KYAI_ASSISTANT_EXPORT Features { public: enum Feature { TextChat = 1, TextToImage = 2, ImageProcessing = 4, DocumentQA = 8 }; explicit Features(int features) : features_(features) {} bool containsFeature(Feature feature) const { return features_ & feature; } private: int features_; }; class OsAssistantPrivate; class KYAI_ASSISTANT_EXPORT OsAssistant { public: OsAssistant(); ~OsAssistant(); // blocked init Error init(); Error initWithChatHistory(std::vector messages, int promptId = -1); void setChatAsyncCallback(ChatResultCallback callback); Features supportedFeatures() const; // json message void chatAsync(const std::string &message); void stopChat(); void setPromptId(int promptId); void clearContext(); std::vector prompts(); bool setPromptOrder(std::list promptIdList); // 创建失败返回-1 int createPrompt(std::string name, std::string content); bool deletePrompt(int promptId); bool updatePrompt(int promptId, std::string name, std::string content); std::string getConfiguredNlpModelInfos() const; void setCurrentNlpModel(const std::string &modelName) const; private: std::unique_ptr assistantPrivate_; }; } // namespace assistant } // namespace kyai #endif // __KYLIN_AI_PRIVATE_OS_ASSISTANT_H__ libkysdk-ai-private/.clang-format0000664000175000017500000000012715160473263015735 0ustar fengfeng Language: Cpp BasedOnStyle: Google AccessModifierOffset: -4 IndentWidth: 4 TabWidth: 4libkysdk-ai-private/LICENSE0000664000175000017500000010451315160473263014373 0ustar fengfeng GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . libkysdk-ai-private/README.md0000664000175000017500000000221715160473263014643 0ustar fengfeng# libkyai-config #### 介绍 本仓库提供 Kylin AI 相关的配置与助手能力库,包括: - `kyai-config`:模型配置与配置服务代理相关能力 - `kyai-assistant`:助手服务代理与 OS Assistant 相关能力 #### 软件架构 - `ai-config/`:配置库实现与安装文件 - `ai-assistant/`:助手库实现与安装文件 - `debian/`:打包相关配置 #### 依赖 - CMake >= 3.5 - C++17 编译器 - `jsoncpp` - `glib` / `gio-unix-2.0` - `KylinAiProto` #### 编译安装 1. 生成构建目录 2. 编译 3. 安装 ```bash cmake -S . -B build cmake --build build cmake --install build ``` #### 构建选项 - `BUILD_AI_CONFIG`:是否构建 `kyai-config`(默认 `ON`) - `BUILD_AI_ASSISTANT`:是否构建 `kyai-assistant`(默认 `ON`) - `ENABLE_TEST`:是否启用测试(默认 `OFF`) 示例:只构建 `kyai-config` ```bash cmake -S . -B build -DBUILD_AI_ASSISTANT=OFF cmake --build build ``` #### 使用说明 - 头文件安装在 `include/kylin-ai/` 下 - 库文件安装在系统库目录(例如 `lib`) #### 参与贡献 1. Fork 本仓库 2. 新建 `Feat_xxx` 分支 3. 提交代码 4. 新建 Pull Request libkysdk-ai-private/CMakeLists.txt0000664000175000017500000000047615160473263016131 0ustar fengfengcmake_minimum_required(VERSION 3.5) project(libkysdk-ai-private LANGUAGES C CXX) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_subdirectory(ai-config) add_subdirectory(ai-assistant) add_subdirectory(libkyai-data-management-client)libkysdk-ai-private/README.en.md0000664000175000017500000000234415160473263015245 0ustar fengfeng# libkyai-config #### Description This repository provides Kylin AI configuration and assistant libraries, including: - `kyai-config`: model configuration and config service proxy - `kyai-assistant`: assistant service proxy and OS Assistant integration #### Software Architecture - `ai-config/`: config library implementation and install files - `ai-assistant/`: assistant library implementation and install files - `debian/`: packaging configuration #### Dependencies - CMake >= 3.5 - C++17 compiler - `jsoncpp` - `glib` / `gio-unix-2.0` - `KylinAiProto` #### Build & Install 1. Generate build directory 2. Build 3. Install ```bash cmake -S . -B build cmake --build build cmake --install build ``` #### Build Options - `BUILD_AI_CONFIG`: build `kyai-config` (default `ON`) - `BUILD_AI_ASSISTANT`: build `kyai-assistant` (default `ON`) - `ENABLE_TEST`: enable tests (default `OFF`) Example: build only `kyai-config` ```bash cmake -S . -B build -DBUILD_AI_ASSISTANT=OFF cmake --build build ``` #### Usage - Headers are installed under `include/kylin-ai/` - Libraries are installed into the system library directory (e.g. `lib`) #### Contribution 1. Fork the repository 2. Create a `Feat_xxx` branch 3. Commit your code 4. Create a Pull Request libkysdk-ai-private/.gitignore0000664000175000017500000000151715160473263015356 0ustar fengfeng# This file is used to ignore files which are generated # ---------------------------------------------------------------------------- *~ *.autosave *.a *.core *.moc *.o *.obj *.orig *.rej *.so *.so.* *_pch.h.cpp *_resource.rc *.qm .#* *.*# core !core/ tags .DS_Store .directory *.debug Makefile* *.prl *.app moc_*.cpp ui_*.h qrc_*.cpp Thumbs.db *.res *.rc /.qmake.cache /.qmake.stash # qtcreator generated files *.pro.user* CMakeLists.txt.user* # xemacs temporary files *.flc # Vim temporary files .*.swp # Visual Studio generated files *.ib_pdb_index *.idb *.ilk *.pdb *.sln *.suo *.vcproj *vcproj.*.*.user *.ncb *.sdf *.opensdf *.vcxproj *vcxproj.* # MinGW generated files *.Debug *.Release # Python byte code *.pyc # Binaries # -------- *.dll *.exe build .vscode .cache .reuse # third-party third-party/llama.cpp/common/build-info.cpplibkysdk-ai-private/ai-config/0000775000175000017500000000000015160473263015216 5ustar fengfenglibkysdk-ai-private/ai-config/modelconfig.cpp0000664000175000017500000001211315160473263020206 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "modelconfig.h" #include "configserviceproxy.h" namespace kyai { namespace config { namespace model { struct ModelConfigPrivate { std::unique_ptr configServiceProxy{ new ConfigServiceProxy()}; }; ModelConfig::ModelConfig() : modelConfigPrivate_(std::make_unique()) {} ModelConfig::~ModelConfig() = default; std::vector ModelConfig::getModels(AiCapability capability) const { return modelConfigPrivate_->configServiceProxy->getModels(capability); } std::vector ModelConfig::getModels(DeployType deployType) const { return modelConfigPrivate_->configServiceProxy->getModels(deployType); } std::vector ModelConfig::getExtendedModels( AiCapability capability) const { return modelConfigPrivate_->configServiceProxy->getExtendedModels( capability); } std::vector ModelConfig::getExtendedModels( DeployType deployType) const { return modelConfigPrivate_->configServiceProxy->getExtendedModels( deployType); } std::string ModelConfig::getCurrentModelName(AiCapability capability, DeployType deployType) const { return modelConfigPrivate_->configServiceProxy->getCurrentModelName( capability, deployType); } std::vector ModelConfig::getModelAuthentications( const std::string &modelName) const { return modelConfigPrivate_->configServiceProxy->getModelAuthentications( modelName); } int ModelConfig::getModelSchedulingPriority(DeployType deployType) const { return modelConfigPrivate_->configServiceProxy->getModelSchedulingPriority( deployType); } bool ModelConfig::getModelDeployEnabled(DeployType deployType) const { return modelConfigPrivate_->configServiceProxy->getModelDeployEnabled( deployType); } bool ModelConfig::setCurrentModelName(AiCapability capability, DeployType deployType, const std::string &modelName) { return modelConfigPrivate_->configServiceProxy->setCurrentModelName( capability, deployType, modelName); } bool ModelConfig::setModelAuthentications( const std::string &modelName, const std::vector authentications) { return modelConfigPrivate_->configServiceProxy->setModelAuthentications( modelName, authentications); } bool ModelConfig::setCustomModelApiUrl(const std::string &modelName, const std::string &apiUrl) { return modelConfigPrivate_->configServiceProxy->setCustomModelApiUrl( modelName, apiUrl); } bool ModelConfig::setCustomModelVersion(const std::string &modelName, const std::string &modelVersion) { return modelConfigPrivate_->configServiceProxy->setCustomModelVersion( modelName, modelVersion); } bool ModelConfig::setModelSchedulingPriority(DeployType deployType, int priority) { return modelConfigPrivate_->configServiceProxy->setModelSchedulingPriority( deployType, priority); } bool ModelConfig::setModelDeployEnabled(DeployType deployType, bool enabled) { return modelConfigPrivate_->configServiceProxy->setModelDeployEnabled( deployType, enabled); } bool ModelConfig::clearModelAuthentications( const std::string &modelName) const { return modelConfigPrivate_->configServiceProxy->clearModelAuthentications( modelName); } ModelStatus ModelConfig::getModelStatus(const std::string &modelName) const { return modelConfigPrivate_->configServiceProxy->getModelStatus(modelName); } bool ModelConfig::addCustomModel(const std::string &modelName, const std::string &model, const std::string &apiKey, const std::string &apiUrl) { return modelConfigPrivate_->configServiceProxy->addCustomModel( modelName, model, apiKey, apiUrl); } bool ModelConfig::deleteCustomModel(const std::string &modelName) { return modelConfigPrivate_->configServiceProxy->deleteCustomModel( modelName); } std::vector ModelConfig::getFreeTrialModels( AiCapability capability) const { return modelConfigPrivate_->configServiceProxy->getFreeTrialModels( capability); } } // namespace model } // namespace config } // namespace kyai libkysdk-ai-private/ai-config/CMakeLists.txt0000664000175000017500000000261015160473263017755 0ustar fengfengcmake_minimum_required(VERSION 3.5) project(ky-ai-config LANGUAGES CXX C) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) ####################################################################### # Options ####################################################################### option(ENABLE_TEST "Build Test" OFF) find_package(jsoncpp REQUIRED) find_package(PkgConfig REQUIRED) find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(COMMON_PROTO_FILES configservice) pkg_check_modules(GIO REQUIRED gio-unix-2.0) include_directories(${GIO_INCLUDE_DIRS}) include_directories(include) include_directories(src) include_directories(include/kylin-ai/private/aiconfig) set(SDK_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/modelconfig.cpp ${CMAKE_CURRENT_SOURCE_DIR}/configserviceproxy.cpp ${COMMON_PROTO_FILES} ) add_library(kyai-config SHARED ${SDK_SOURCES}) if (ENABLE_TEST) enable_testing() add_subdirectory(tests) endif () set_target_properties(kyai-config PROPERTIES VERSION 1.0.0 SOVERSION 1) target_link_libraries( kyai-config ${GIO_LIBRARIES} jsoncpp ) include(CMakePackageConfigHelpers) include(GNUInstallDirs) install(TARGETS kyai-config DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(DIRECTORY include/kylin-ai DESTINATION include) install(DIRECTORY usr/ DESTINATION /usr) libkysdk-ai-private/ai-config/configserviceproxy.h0000664000175000017500000000624415160473263021325 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #pragma once #include #include #include "configserviceglue.h" #include "modelconfig.h" namespace kyai { namespace config { namespace model { class ConfigServer { public: static ConfigServer &getInstance(); ~ConfigServer(); bool available() const { return connection_ != nullptr; } GDBusConnection *getConnection() const { return connection_; } private: ConfigServer(); void init(const std::string &unixPath); void destroy() const; private: GDBusConnection *connection_{nullptr}; mutable std::mutex mutex_; }; class ConfigServiceProxy { public: ConfigServiceProxy(); std::vector getModels(AiCapability capability) const; std::vector getModels(DeployType deployType) const; std::vector getExtendedModels(AiCapability capability) const; std::vector getExtendedModels(DeployType deployType) const; std::string getCurrentModelName(AiCapability capability, DeployType deployType) const; std::vector getModelAuthentications( const std::string &modelName) const; int getModelSchedulingPriority(DeployType deployType) const; bool getModelDeployEnabled(DeployType deployType) const; bool setCurrentModelName(AiCapability capability, DeployType deployType, const std::string &modelName); bool setModelAuthentications( const std::string &modelName, const std::vector authentications); bool setCustomModelApiUrl(const std::string &modelName, const std::string &apiUrl); bool setCustomModelVersion(const std::string &modelName, const std::string &modelVersion); bool setModelSchedulingPriority(DeployType deployType, int priority); bool setModelDeployEnabled(DeployType deployType, bool enabled); bool clearModelAuthentications(const std::string &modelName); ModelStatus getModelStatus(const std::string &modelName) const; bool addCustomModel(const std::string &modelName, const std::string &model, const std::string &apiKey, const std::string &apiUrl); bool deleteCustomModel(const std::string &modelName); std::vector getFreeTrialModels(AiCapability capability) const; private: bool connectToServer(); private: AiRuntimeConfigService *proxy_{nullptr}; }; } // namespace model } // namespace config } // namespace kyai libkysdk-ai-private/ai-config/usr/0000775000175000017500000000000015160473263016027 5ustar fengfenglibkysdk-ai-private/ai-config/usr/share/0000775000175000017500000000000015160473263017131 5ustar fengfenglibkysdk-ai-private/ai-config/usr/share/pkgconfig/0000775000175000017500000000000015160473263021100 5ustar fengfenglibkysdk-ai-private/ai-config/usr/share/pkgconfig/kyai-config.pc0000664000175000017500000000020615160473263023622 0ustar fengfengName: libkyai-config Description: Kylin ai config component Version: 1.0.0 Libs: -lkyai-config Cflags: -I/usr/include/kylin-ai/privatelibkysdk-ai-private/ai-config/configserviceproxy.cpp0000664000175000017500000004564415160473263021667 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "configserviceproxy.h" #include namespace kyai { namespace config { namespace model { const std::string serverUnixPath = "unix:path=/tmp/.kylin-ai-runtime-unix/" + std::to_string(getuid()) + "/config.sock"; const char *objectPath = "/com/kylin/AiRuntime/Config"; const char *interface = "com.kylin.AiRuntime.Config"; Json::Value parseJsonString(const std::string &jsonString) { Json::Value root; Json::Reader reader; if (!reader.parse(jsonString, root)) { std::fprintf(stderr, "Error parsing JSON string\n"); return {}; } return root; } std::vector createModelsFromJsonString(const std::string &jsonString) { const auto jsonModels = parseJsonString(jsonString); if (jsonModels.empty()) { return {}; } std::vector models; for (const auto &model : jsonModels) { Model m; m.capability = static_cast(model["capability"].asInt()); m.deployType = static_cast(model["deployType"].asInt()); m.modelName = model["modelName"].asString(); m.vendor = model["vendor"].asString(); models.push_back(m); } return models; } std::vector createExtendedModelsFromJsonString( const std::string &jsonString) { const auto jsonModels = parseJsonString(jsonString); if (jsonModels.empty()) { return {}; } std::vector models; for (const auto &model : jsonModels) { ExtendedModel m; m.capability = static_cast(model["capability"].asInt()); m.deployType = static_cast(model["deployType"].asInt()); m.modelName = model["modelName"].asString(); m.vendor = model["vendor"].asString(); m.modelVersion = model["modelVersion"].asString(); m.apiUrl = model["apiUrl"].asString(); m.debName = model["debName"].asString(); m.is3rdModel = model["is3rdModel"].asBool(); models.push_back(m); } return models; } std::string authenticationsToJsonString( const std::vector &authentications) { Json::Value root; for (const auto &auth : authentications) { Json::Value authen; authen["itemName"] = auth.itemName; for (const auto &auth : auth.authentications) { Json::Value value; value["friendlyKeyName"] = auth.friendlyKeyName; value["key"] = auth.key; value["value"] = auth.value; authen["authentications"].append(value); } root.append(authen); } return root.toStyledString(); } std::vector jsonStringToAuthentications( const std::string &jsonString) { Json::Value root; Json::Reader reader; if (!reader.parse(jsonString, root)) { std::fprintf(stderr, "Error parsing JSON string\n"); return {}; } std::vector authentications; for (const auto &auth : root) { MultiAuthentication au; if (!auth.isMember("itemName") || !auth.isMember("authentications") || !auth["authentications"].isArray()) { std::fprintf(stderr, "Error parsing JSON string\n"); return {}; } au.itemName = auth["itemName"].asString(); for (const auto &auth : auth["authentications"]) { Authentication a; a.friendlyKeyName = auth["friendlyKeyName"].asString(); a.key = auth["key"].asString(); a.value = auth["value"].asString(); au.authentications.push_back(a); } authentications.push_back(au); } return authentications; } ConfigServer &ConfigServer::getInstance() { static ConfigServer instance{}; return instance; } ConfigServer::ConfigServer() { init(serverUnixPath); } ConfigServer::~ConfigServer() { destroy(); } void ConfigServer::init(const std::string &unixPath) { std::lock_guard locker(mutex_); if (connection_ != nullptr && !g_dbus_connection_is_closed(connection_)) { return; } GError *error = nullptr; connection_ = g_dbus_connection_new_for_address_sync( unixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, /* GDBusAuthObserver */ nullptr, /* GCancellable */ &error); if (connection_ == nullptr) { g_printerr("Error connecting to D-Bus address %s: %s\n", unixPath.c_str(), error->message); g_error_free(error); return; } } void ConfigServer::destroy() const { std::lock_guard locker(mutex_); if (connection_ != nullptr) { g_object_unref(connection_); } } ConfigServiceProxy::ConfigServiceProxy() { if (!connectToServer()) { std::fprintf(stderr, "Failed to connect to server\n"); } } bool ConfigServiceProxy::connectToServer() { if (!ConfigServer::getInstance().available()) { g_printerr( "Error creating core speech server proxy: Server proxy " "connection is unavailable.\n"); return false; } GError *error = nullptr; auto *connection = ConfigServer::getInstance().getConnection(); proxy_ = ai_runtime_config_service_proxy_new_sync( connection, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath, nullptr, &error); if (proxy_ == nullptr) { g_printerr("Error creating config service proxy %s: %s\n", objectPath, error->message); g_error_free(error); return true; } return true; } std::vector ConfigServiceProxy::getModels( AiCapability capability) const { gchar *modelInfo{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_models_by_capability_sync( proxy_, (int)capability, &modelInfo, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelsByCapability: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelsByCapability\n"); } return {}; } auto models = createModelsFromJsonString(modelInfo); g_free(modelInfo); return models; } std::vector ConfigServiceProxy::getModels(DeployType deployType) const { gchar *modelInfo{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_models_by_deploy_type_sync( proxy_, (int)deployType, &modelInfo, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelsByDeployType: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelsByDeployType\n"); } return {}; } auto models = createModelsFromJsonString(modelInfo); g_free(modelInfo); return models; } std::string ConfigServiceProxy::getCurrentModelName( AiCapability capability, DeployType deployType) const { gchar *modelName{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_current_model_name_sync( proxy_, (int)capability, (int)deployType, &modelName, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetCurrentModelName: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetCurrentModelName\n"); } return {}; } std::string result = modelName; g_free(modelName); return result; } std::vector ConfigServiceProxy::getModelAuthentications( const std::string &modelName) const { gchar *authenticationsJsonString{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_model_authentications_sync( proxy_, modelName.c_str(), &authenticationsJsonString, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelAuthentications: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelAuthentications\n"); } return {}; } auto authentications = jsonStringToAuthentications(authenticationsJsonString); g_free(authenticationsJsonString); return authentications; } int ConfigServiceProxy::getModelSchedulingPriority( DeployType deployType) const { int priority; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_model_scheduling_priority_sync( proxy_, (int)deployType, &priority, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelSchedulingPriority: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelSchedulingPriority\n"); } return -1; } return priority; } bool ConfigServiceProxy::getModelDeployEnabled(DeployType deployType) const { gboolean enabled = false; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_model_deploy_enabled_sync( proxy_, (int)deployType, &enabled, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelDeployEnabled: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelDeployEnabled\n"); } return false; } return enabled; } bool ConfigServiceProxy::setCurrentModelName(AiCapability capability, DeployType deployType, const std::string &modelName) { gboolean success = false; GError *error = nullptr; bool ret = ai_runtime_config_service_call_set_current_model_name_sync( proxy_, (int)capability, (int)deployType, modelName.c_str(), &success, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetCurrentModelName: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetCurrentModelName\n"); } return false; } return success; } bool ConfigServiceProxy::setModelAuthentications( const std::string &modelName, const std::vector authentications) { const std::string authenticationsJsonString = authenticationsToJsonString(authentications); GError *error = nullptr; bool ret = ai_runtime_config_service_call_set_model_authentication_sync( proxy_, modelName.c_str(), authenticationsJsonString.c_str(), nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetModelAuthentication: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetModelAuthentication\n"); } return false; } return true; } bool ConfigServiceProxy::setCustomModelApiUrl(const std::string &modelName, const std::string &apiUrl) { GError *error = nullptr; gboolean success = false; bool ret = ai_runtime_config_service_call_set_custom_model_api_url_sync( proxy_, modelName.c_str(), apiUrl.c_str(), &success, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetCustomModelApiUrl: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetCustomModelApiUrl\n"); } return false; } return success; } bool ConfigServiceProxy::setCustomModelVersion( const std::string &modelName, const std::string &modelVersion) { GError *error = nullptr; gboolean success = false; bool ret = ai_runtime_config_service_call_set_custom_model_version_sync( proxy_, modelName.c_str(), modelVersion.c_str(), &success, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetCustomModelVersion: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetCustomModelVersion\n"); } return false; } return success; } bool ConfigServiceProxy::setModelSchedulingPriority(DeployType deployType, int priority) { GError *error = nullptr; bool ret = ai_runtime_config_service_call_set_model_scheduling_priority_sync( proxy_, (int)deployType, priority, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetModelSchedulingPriority: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetModelSchedulingPriority\n"); } return false; } return true; } bool ConfigServiceProxy::setModelDeployEnabled(DeployType deployType, bool enabled) { GError *error = nullptr; bool ret = ai_runtime_config_service_call_set_model_deploy_enabled_sync( proxy_, (int)deployType, enabled, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling SetModelDeployEnabled: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling SetModelDeployEnabled\n"); } return false; } return true; } bool ConfigServiceProxy::clearModelAuthentications( const std::string &modelName) { GError *error = nullptr; bool isOk = ai_runtime_config_service_call_clear_model_authentication_sync( proxy_, modelName.c_str(), nullptr, &error); if (!isOk) { if (error) { g_printerr("Error calling ClearModelAuthentications: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling ClearModelAuthentications\n"); } return false; } return true; } ModelStatus ConfigServiceProxy::getModelStatus( const std::string &modelName) const { gint status = -1; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_model_status_sync( proxy_, modelName.c_str(), &status, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetModelStatus: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetModelStatus\n"); } return ModelStatus::Unknown; } return static_cast(status); } bool ConfigServiceProxy::addCustomModel(const std::string &modelName, const std::string &model, const std::string &apiKey, const std::string &apiUrl) { GError *error = nullptr; gboolean success = false; bool ret = ai_runtime_config_service_call_add_custom_model_sync( proxy_, modelName.c_str(), model.c_str(), apiKey.c_str(), apiUrl.c_str(), &success, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling AddCustomModel: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling AddCustomModel\n"); } return false; } return success; } bool ConfigServiceProxy::deleteCustomModel(const std::string &modelName) { GError *error = nullptr; gboolean success = false; bool ret = ai_runtime_config_service_call_delete_custom_model_sync( proxy_, modelName.c_str(), &success, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling DeleteCustomModel: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling DeleteCustomModel\n"); } return false; } return success; } std::vector ConfigServiceProxy::getExtendedModels( AiCapability capability) const { gchar *modelInfo{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_models_by_capability_sync( proxy_, (int)capability, &modelInfo, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetExtendedModels by capability: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetExtendedModels by capability\n"); } return {}; } auto models = createExtendedModelsFromJsonString(modelInfo); g_free(modelInfo); return models; } std::vector ConfigServiceProxy::getExtendedModels( DeployType deployType) const { gchar *modelInfo{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_models_by_deploy_type_sync( proxy_, (int)deployType, &modelInfo, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling GetExtendedModels by deploy type: %s\n", error->message); g_error_free(error); } else { g_printerr("Error calling GetExtendedModels by deploy type\n"); } return {}; } auto models = createExtendedModelsFromJsonString(modelInfo); g_free(modelInfo); return models; } std::vector ConfigServiceProxy::getFreeTrialModels( AiCapability capability) const { gchar *modelInfo{nullptr}; GError *error = nullptr; bool ret = ai_runtime_config_service_call_get_free_trial_models_sync( proxy_, (int)capability, &modelInfo, nullptr, &error); if (!ret) { if (error) { g_printerr("Error calling getFreeTrialModels: %s\n", error->message); g_error_free(error); } else { std::fprintf(stderr, "Error calling getFreeTrialModels\n"); } return {}; } auto models = createModelsFromJsonString(modelInfo); g_free(modelInfo); return models; } } // namespace model } // namespace config } // namespace kyai libkysdk-ai-private/ai-config/include/0000775000175000017500000000000015160473263016641 5ustar fengfenglibkysdk-ai-private/ai-config/include/kylin-ai/0000775000175000017500000000000015160473263020356 5ustar fengfenglibkysdk-ai-private/ai-config/include/kylin-ai/private/0000775000175000017500000000000015160473263022030 5ustar fengfenglibkysdk-ai-private/ai-config/include/kylin-ai/private/aiconfig/0000775000175000017500000000000015160473263023607 5ustar fengfenglibkysdk-ai-private/ai-config/include/kylin-ai/private/aiconfig/modelconfig.h0000664000175000017500000000675215160473263026260 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #pragma once #include #include #include namespace kyai { namespace config { namespace model { enum class AiCapability { Nlp, Vision, Speech, }; enum class DeployType { Ondevice, PublicCloud, PrivateCloud, Custom = PrivateCloud, }; enum class ModelStatus { Idle, Running, Unknown, }; struct Authentication { std::string friendlyKeyName; std::string key; std::string value; }; struct Model { std::string modelName; std::string vendor; AiCapability capability; DeployType deployType; }; struct ExtendedModel : public Model { std::string modelVersion; std::string apiUrl; std::string debName; bool is3rdModel{false}; }; struct MultiAuthentication { std::string itemName; std::vector authentications; }; class ModelConfigPrivate; class ModelConfig { public: ModelConfig(); ~ModelConfig(); std::vector getModels(AiCapability capability) const; std::vector getModels(DeployType deployType) const; std::vector getExtendedModels(AiCapability capability) const; std::vector getExtendedModels(DeployType deployType) const; std::string getCurrentModelName(AiCapability capability, DeployType deployType) const; std::vector getModelAuthentications( const std::string &modelName) const; int getModelSchedulingPriority(DeployType deployType) const; bool getModelDeployEnabled(DeployType deployType) const; bool setCurrentModelName(AiCapability capability, DeployType deployType, const std::string &modelName); bool setModelAuthentications( const std::string &modelName, const std::vector authentications); bool setModelSchedulingPriority(DeployType deployType, int priority); bool setModelDeployEnabled(DeployType deployType, bool enabled); bool clearModelAuthentications(const std::string &modelName) const; ModelStatus getModelStatus(const std::string &modelName) const; bool setCustomModelApiUrl(const std::string &modelName, const std::string &apiUrl); bool setCustomModelVersion(const std::string &modelName, const std::string &modelVersion); bool addCustomModel(const std::string &modelName, const std::string &modelVersion, const std::string &apiKey, const std::string &apiUrl); bool deleteCustomModel(const std::string &modelName); std::vector getFreeTrialModels(AiCapability capability) const; private: std::unique_ptr modelConfigPrivate_; }; } // namespace model } // namespace config } // namespace kyai libkysdk-ai-private/libkyai-data-management-client/0000775000175000017500000000000015160473263021303 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/src/0000775000175000017500000000000015160473263022072 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/src/_datamanagementsession.cpp0000664000175000017500000002135415160473263027314 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "_datamanagementsession.h" #include #include #include #include DataManagementStatus InitializeStatus(bool success, int errorCode, const char *errorMsg) { DataManagementStatus status; status.success = success; status.errorCode = errorCode; std::strncpy(status.errorMsg, errorMsg, sizeof(status.errorMsg) - 1); status.errorMsg[sizeof(status.errorMsg) - 1] = '\0'; // 确保字符串以null终止 return status; } namespace { std::string generateFormatCheckResult(bool supported, const std::string &format) { nlohmann::json root; root["supported"] = supported; root["format"] = format; return root.dump(); } std::string getFileExtension(const std::string &filePath) { size_t pos = filePath.find_last_of('.'); if (pos != std::string::npos) { return filePath.substr(pos + 1); } return std::string(); } bool isSupportedFormat(const std::string &extension) { const std::vector supportTextFormat = {"txt", "pdf", "docx", "pptx", "xlsx", "xls", "xlsd", "html", "xml", "md", "json"}; const std::vector supportImageFormat = {"png", "jpg", "jpeg", "jpe", "bmp", "dib"}; for (const auto &format : supportTextFormat) { if (format == extension) return true; } for (const auto &format : supportImageFormat) { if (format == extension) return true; } return false; } DataManagementStatus parseResponse(const std::string &response, nlohmann::json &data) { nlohmann::json jsonValue = nlohmann::json::parse(response, nullptr, false); std::string msg = "Parse response error: " + response; if (jsonValue.is_discarded()) { return STATUS_FAILURE(ErrorCode::DM_ERROR_UNKNOWN, msg.c_str()); } bool hasError = jsonValue.contains("err_no"); bool hasErrorMsg = jsonValue.contains("err_msg"); bool hasData = jsonValue.contains("data") && !jsonValue["data"].is_null(); if (!hasError || !hasErrorMsg) { return STATUS_FAILURE(ErrorCode::DM_ERROR_UNKNOWN, msg.c_str()); } if (!jsonValue["err_no"].is_number_integer()) { return STATUS_FAILURE(ErrorCode::DM_ERROR_UNKNOWN, msg.c_str()); } if (!jsonValue["err_msg"].is_string()) { return STATUS_FAILURE(ErrorCode::DM_ERROR_UNKNOWN, msg.c_str()); } if (hasData) { data = jsonValue["data"]; } return jsonValue["err_no"] == ErrorCode::SUCCESS ? STATUS_SUCCESS : STATUS_FAILURE(jsonValue["err_no"], jsonValue["err_msg"].get().c_str()); } DataManagementStatus parseResponse(const std::string &response) { nlohmann::json v; return parseResponse(response, v); } DataManagementStatus parseResponse(const std::string &response, std::string &data, const std::string &key = "") { nlohmann::json result; DataManagementStatus ret = parseResponse(response, result); if (!ret.success) { return ret; } data = key.empty() ? result.dump() : result[key].get(); return STATUS_SUCCESS; } DataManagementStatus parseResponse(const std::string &response, int &data, const std::string &key) { nlohmann::json result; DataManagementStatus ret = parseResponse(response, result); if (!ret.success) { return ret; } data = result[key].get(); return STATUS_SUCCESS; } DataManagementStatus parseResponse(const std::string &response, bool &data, const std::string &key) { nlohmann::json result; DataManagementStatus ret = parseResponse(response, result); if (!ret.success) { return ret; } data = result[key].get(); return STATUS_SUCCESS; } } // namespace namespace datamanagement { DataManagementStatus _DataManagementSession::checkFileFormat(const std::string &filePath, std::string &formatResult) { if (!std::filesystem::exists(filePath)) { std::string msg = filePath + " not exist."; return STATUS_FAILURE(PARSE_PARAM_FAILED, msg.c_str()); } std::string format = getFileExtension(filePath); bool isSupported = isSupportedFormat(format); formatResult = generateFormatCheckResult(isSupported, format); return STATUS_SUCCESS; } DataManagementStatus _DataManagementSession::similaritySearch(const std::string &searchConditions, std::string &searchResult) { std::string response = proxy_->similaritySearch(searchConditions); return parseResponse(response, searchResult); } DataManagementStatus _DataManagementSession::addTextFiles(const std::string &fileinfos) { std::string response = proxy_->addTextFiles(fileinfos); return parseResponse(response); } DataManagementStatus _DataManagementSession::addImageFiles(const std::string &fileinfos) { std::string response = proxy_->addImageFiles(fileinfos); return parseResponse(response); } DataManagementStatus _DataManagementSession::deleteFiles(const std::string &fileinfos) { std::string response = proxy_->deleteFiles(fileinfos); return parseResponse(response); } DataManagementStatus _DataManagementSession::updateFilesName(const std::string &fileinfos) { std::string response = proxy_->updateFilesName(fileinfos); return parseResponse(response); } DataManagementStatus _DataManagementSession::updateContentData(const std::string &fileinfos) { std::string response = proxy_->updateContentData(fileinfos); return parseResponse(response); } DataManagementStatus _DataManagementSession::getAllFileinfos(std::string &result) { std::string response = proxy_->getAllFileinfos(); return parseResponse(response, result); } DataManagementStatus _DataManagementSession::getFeatureStatus(int &status) { std::string response = proxy_->getFeatureStatus(); return parseResponse(response, status, "result"); } DataManagementStatus _DataManagementSession::getTagsOfFiles(const std::string &files, std::string &result) { std::string response = proxy_->getTagsOfFiles(files); return parseResponse(response, result); } DataManagementStatus _DataManagementSession::getAllTags(std::string &result) { std::string response = proxy_->getAllTags(); return parseResponse(response, result); } DataManagementStatus _DataManagementSession::searchSimilarTags(const std::string &tags, std::string &result) { std::string response = proxy_->searchSimilarTags(tags); return parseResponse(response, result); } DataManagementStatus _DataManagementSession::searchFilesAboutTags(const std::string &tags, std::string &result) { std::string response = proxy_->searchFilesAboutTags(tags); return parseResponse(response, result); } DataManagementStatus _DataManagementSession::isFileRelevantToTags(const std::string &fileInfos, bool &isRelevant) { std::string response = proxy_->isFileRelevantToTags(fileInfos); return parseResponse(response, isRelevant, "is_relevant"); } DataManagementStatus _DataManagementSession::isFileRelevantToDescription(const std::string &fileInfos, bool &isRelevant) { std::string response = proxy_->isFileRelevantToDescription(fileInfos); return parseResponse(response, isRelevant, "is_relevant"); } DataManagementStatus _DataManagementSession::extractSearchConditions(const std::string &description, std::string &conditions) { std::string response = proxy_->extractSearchConditions(description); return parseResponse(response, conditions); } DataManagementStatus _DataManagementSession::getSummarysOfFiles(const std::string &files, std::string &summary) { std::string response = proxy_->getSummarysOfFiles(files); return parseResponse(response, summary); } bool _DataManagementSession::connect() { bool ret = proxy_->connect(); if (!ret) { std::fprintf(stderr, "ERROR: connect data-management server failed.\n"); return false; } std::fprintf(stdout, "INFO: connect data-management server success.\n"); return true; } } // namespace datamanagement libkysdk-ai-private/libkyai-data-management-client/src/datamanagement.cpp0000664000175000017500000003065115160473263025551 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "kylin-ai/business/data-management/datamanagement.h" #include #include #include #include #include "_datamanagementsession.h" #define STATUS_SESSION_ERROR (DataManagementStatus){false, ErrorCode::DM_SESSION_ERROR, "Invalit session"} namespace { bool is_valid_datamanagement_session(void* session) { auto* dataManagementSession = static_cast(session); return dataManagementSession != nullptr; } std::string get_uname() { std::array buffer{}; std::string result; std::unique_ptr pipe(popen("uname -m", "r"), pclose); if (!pipe) { std::cerr << "ERROR: DataManagement popen uname failed!" << std::endl; return std::string(); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } // 移除可能存在的换行符 result.erase(result.find_last_not_of("\n\r") + 1); return result; } bool is_subsystem_plugin_installed() { const std::string command = "LC_ALL=C /usr/bin/dpkg -s kylin-ai-subsystem-plugin 2>/dev/null"; std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); if (!pipe) { std::cerr << "ERROR: DataManagement popen dpkg failed!" << std::endl; return false; } std::array buffer{}; while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { std::string line(buffer.data()); if (line.find("Status: install ok installed") != std::string::npos) { return true; } } return false; } } // namespace /** * @return true: 当前架构支持且子系统插件已安装;false:当前架构不支持或子系统插件未安装 */ bool data_management_is_feature_supported() { // 目前只支持 x86_64 和 arm64 const std::set supportedUname = { "x86_64", "aarch64", }; std::string uname = get_uname(); bool is_installed = is_subsystem_plugin_installed(); bool is_uname_supported = supportedUname.find(uname) != supportedUname.end(); std::cout << "DataManagement: uname is " << uname.c_str() << ", " << (is_uname_supported ? "supported" : "not supported") << std::endl; std::cout << "DataManagement: subsystem plugin is " << (is_installed ? "installed" : "not installed") << std::endl; return is_installed && is_uname_supported; } DataManagementSession* data_management_create_session() { auto* dataManagementSession = new datamanagement::_DataManagementSession(); if (dataManagementSession->connect()) { return reinterpret_cast(dataManagementSession); } else { delete dataManagementSession; return nullptr; } } void data_management_destroy_session(DataManagementSession* session) { if (session == nullptr) { return; } auto* dataManagementSession = reinterpret_cast(session); delete dataManagementSession; } DataManagementStatus data_management_get_feature_status(DataManagementSession* session, FeatureStatus* status) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } int status_int; DataManagementStatus getResult = dataManagementSession->getFeatureStatus(status_int); *status = static_cast(status_int); return getResult; } DataManagementStatus data_management_check_file_format(DataManagementSession* session, const char* filepath, char** check_result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string formatResult; DataManagementStatus checkResult = dataManagementSession->checkFileFormat(filepath, formatResult); if (!formatResult.empty()) { size_t length = formatResult.size() + 1; *check_result = new char[length]; std::strcpy(*check_result, formatResult.c_str()); } return checkResult; } DataManagementStatus data_management_similarity_search(DataManagementSession* session, const char* search_conditions, char** search_result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string searchResult; DataManagementStatus result = dataManagementSession->similaritySearch(search_conditions, searchResult); size_t length = searchResult.size() + 1; *search_result = new char[length]; std::strcpy(*search_result, searchResult.c_str()); return result; } DataManagementStatus data_management_add_text_files(DataManagementSession* session, const char* fileinfos) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->addTextFiles(fileinfos); } DataManagementStatus data_management_add_image_files(DataManagementSession* session, const char* fileinfos) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->addImageFiles(fileinfos); } DataManagementStatus data_management_delete_files(DataManagementSession* session, const char* fileinfos) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->deleteFiles(fileinfos); } DataManagementStatus data_management_update_files_name(DataManagementSession* session, const char* fileinfos) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->updateFilesName(fileinfos); } DataManagementStatus data_management_update_files_content(DataManagementSession* session, const char* fileinfos) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->updateContentData(fileinfos); } DataManagementStatus data_management_get_all_fileinfos(DataManagementSession* session, char** fileinfos_result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string fileinfosResult; DataManagementStatus result = dataManagementSession->getAllFileinfos(fileinfosResult); size_t length = fileinfosResult.size() + 1; *fileinfos_result = new char[length]; std::strcpy(*fileinfos_result, fileinfosResult.c_str()); return result; } void data_management_destroy_result(char* result) { delete[] result; } DataManagementStatus data_management_get_tags_of_files(DataManagementSession* session, const char* files, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string tags; DataManagementStatus status = dataManagementSession->getTagsOfFiles(files, tags); size_t length = tags.size() + 1; *result = new char[length]; std::strcpy(*result, tags.c_str()); return status; } DataManagementStatus data_management_get_all_tags(DataManagementSession* session, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string tags; DataManagementStatus status = dataManagementSession->getAllTags(tags); size_t length = tags.size() + 1; *result = new char[length]; std::strcpy(*result, tags.c_str()); return status; } DataManagementStatus data_management_search_similar_tags(DataManagementSession* session, const char* tags, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string similarTags; DataManagementStatus status = dataManagementSession->searchSimilarTags(tags, similarTags); size_t length = similarTags.size() + 1; *result = new char[length]; std::strcpy(*result, similarTags.c_str()); return status; } DataManagementStatus data_management_search_files_about_tags(DataManagementSession* session, const char* tags, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string files; DataManagementStatus status = dataManagementSession->searchFilesAboutTags(tags, files); size_t length = files.size() + 1; *result = new char[length]; std::strcpy(*result, files.c_str()); return status; } DataManagementStatus data_management_is_file_relevant_to_tags(DataManagementSession* session, const char* fileInfos, bool* isRelevant) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->isFileRelevantToTags(fileInfos, *isRelevant); } DataManagementStatus data_management_is_file_relevant_to_description(DataManagementSession* session, const char* fileInfos, bool* isRelevant) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } return dataManagementSession->isFileRelevantToDescription(fileInfos, *isRelevant); } DataManagementStatus data_management_extract_search_conditions(DataManagementSession* session, const char* description, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string conditions; DataManagementStatus status = dataManagementSession->extractSearchConditions(description, conditions); size_t length = conditions.size() + 1; *result = new char[length]; std::strcpy(*result, conditions.c_str()); return status; } DataManagementStatus data_management_get_summarys_of_files(DataManagementSession* session, const char* files, char** result) { auto* dataManagementSession = reinterpret_cast(session); if (!dataManagementSession) { return STATUS_SESSION_ERROR; } std::string summary; DataManagementStatus status = dataManagementSession->getSummarysOfFiles(files, summary); size_t length = summary.size() + 1; *result = new char[length]; std::strcpy(*result, summary.c_str()); return status; } libkysdk-ai-private/libkyai-data-management-client/src/datamanagementserviceproxy.h0000664000175000017500000000502515160473263027676 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef DATAMANAGEMENTSERVICEPROXY_H #define DATAMANAGEMENTSERVICEPROXY_H #include #include "datamanagementserviceglue.h" typedef gboolean (*AiBusinessDataManagementCallSyncFunc)(AiBusinessDataManagement* proxy, const gchar* arg_input, GDBusCallFlags call_flags, gint timeout_msec, gchar** out_output, GCancellable* cancellable, GError** error); class DataManagementServiceProxy { public: DataManagementServiceProxy() = default; ~DataManagementServiceProxy(); std::string similaritySearch(const std::string& input); std::string addTextFiles(const std::string& input); std::string addImageFiles(const std::string& input); std::string deleteFiles(const std::string& input); std::string updateFilesName(const std::string& input); std::string updateContentData(const std::string& input); std::string getAllFileinfos(); std::string getFeatureStatus(); std::string getTagsOfFiles(const std::string& input); std::string getAllTags(); std::string searchSimilarTags(const std::string& input); std::string searchFilesAboutTags(const std::string& input); std::string isFileRelevantToTags(const std::string& input); std::string isFileRelevantToDescription(const std::string& input); std::string extractSearchConditions(const std::string& input); std::string getSummarysOfFiles(const std::string& input); bool connect(); private: void destroy(); std::string syncFuncCall(const std::string& input, gint timeout_msec, AiBusinessDataManagementCallSyncFunc func); private: const std::string objectPath_ = "/com/kylin/AiBusiness/DataManagement"; GDBusConnection* connection_ = nullptr; AiBusinessDataManagement* delegate_ = nullptr; }; #endif // DATAMANAGEMENTSERVICEPROXY_H libkysdk-ai-private/libkyai-data-management-client/src/datamanagementserviceproxy.cpp0000664000175000017500000001712715160473263030237 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "datamanagementserviceproxy.h" #include #include #include #include namespace { const int CALL_DATA_MANAGEMENT_RETRY_TIME = 5; std::string createResponse(const std::string &data, int errorCode, const std::string &errorMsg) { nlohmann::json root; root["err_no"] = errorCode; root["err_msg"] = errorMsg; root["data"] = data; return root.dump(); } } // namespace std::string DataManagementServiceProxy::syncFuncCall(const std::string &input, gint timeout_msec, AiBusinessDataManagementCallSyncFunc func) { char *output = nullptr; GError *gError = nullptr; std::string errorMsg; int retryTime = 0; bool success = func(delegate_, input.c_str(), G_DBUS_CALL_FLAGS_NONE, timeout_msec, &output, nullptr, &gError); while (!success && retryTime <= CALL_DATA_MANAGEMENT_RETRY_TIME) { if (retryTime == CALL_DATA_MANAGEMENT_RETRY_TIME) { if (gError) { // 测试过程中有发现过失败但error为空的情况 std::fprintf(stderr, "ERROR: call data-management server retry failed, code: %d, msg: %s.\n", gError->code, gError->message); errorMsg = gError->message; g_error_free(gError); gError = nullptr; } else { std::fprintf(stderr, "ERROR: call data-management server retry failed.\n"); } return createResponse(std::string(), ErrorCode::DM_SESSION_ERROR, errorMsg); } if (gError) { // 测试过程中有发现过失败但error为空的情况 std::fprintf(stdout, "WARN: call data-management server failed, code: %d, msg: %s, retry: %d\n", gError->code, gError->message, retryTime); errorMsg = gError->message; g_error_free(gError); gError = nullptr; } else { std::fprintf(stdout, "WARN: call data-management server failed, retry: %d\n", retryTime); } // 断开连接 destroy(); sleep(1); retryTime++; // 重连 if (!connect()) { continue; } success = func(delegate_, input.c_str(), G_DBUS_CALL_FLAGS_NONE, timeout_msec, &output, nullptr, &gError); } std::string response; if (output != nullptr) response = output; return response; } DataManagementServiceProxy::~DataManagementServiceProxy() { destroy(); } bool DataManagementServiceProxy::connect() { GError *error = nullptr; std::string serverUnixPath = "unix:abstract=/tmp/.kylin-ai-business-unix/" + std::to_string(geteuid()) + "/DataManagement.sock"; connection_ = g_dbus_connection_new_for_address_sync( serverUnixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, nullptr, &error); if (connection_ == nullptr) { g_printerr("ERROR: connecting to data-management D-Bus address %s failed, code: %d, msg: %s.\n", serverUnixPath.c_str(), error->code, error->message); g_error_free(error); error = nullptr; return false; } delegate_ = ai_business_data_management_proxy_new_sync(connection_, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath_.c_str(), nullptr, &error); if (delegate_ == nullptr) { g_printerr("ERROR: creating data-management processor proxy %s failed, code: %d, msg: %s.\n", objectPath_.c_str(), error->code, error->message); g_error_free(error); error = nullptr; return false; } return true; } void DataManagementServiceProxy::destroy() { if (delegate_ != nullptr) { g_object_unref(delegate_); delegate_ = nullptr; } if (connection_ != nullptr) { g_object_unref(connection_); connection_ = nullptr; } } std::string DataManagementServiceProxy::similaritySearch(const std::string &input) { return syncFuncCall(input, -1, ai_business_data_management_call_similarity_search_sync); } std::string DataManagementServiceProxy::addTextFiles(const std::string &input) { return syncFuncCall(input, 3600000, ai_business_data_management_call_add_text_files_sync); } std::string DataManagementServiceProxy::addImageFiles(const std::string &input) { return syncFuncCall(input, 3600000, ai_business_data_management_call_add_image_files_sync); } std::string DataManagementServiceProxy::deleteFiles(const std::string &input) { return syncFuncCall(input, -1, ai_business_data_management_call_delete_files_sync); } std::string DataManagementServiceProxy::updateFilesName(const std::string &input) { return syncFuncCall(input, 600000, ai_business_data_management_call_update_files_name_sync); } std::string DataManagementServiceProxy::updateContentData(const std::string &input) { return syncFuncCall(input, 600000, ai_business_data_management_call_update_files_content_data_sync); } std::string DataManagementServiceProxy::getAllFileinfos() { const std::string emptyInput = "{}"; return syncFuncCall(emptyInput, -1, ai_business_data_management_call_get_all_file_infos_sync); } std::string DataManagementServiceProxy::getFeatureStatus() { const std::string emptyInput = "{}"; return syncFuncCall(emptyInput, -1, ai_business_data_management_call_get_feature_status_sync); } std::string DataManagementServiceProxy::getTagsOfFiles(const std::string &input) { return syncFuncCall(input, 600000, ai_business_data_management_call_get_tags_of_files_sync); } std::string DataManagementServiceProxy::getAllTags() { const std::string emptyInput = "{}"; return syncFuncCall(emptyInput, 600000, ai_business_data_management_call_get_all_tags_sync); } std::string DataManagementServiceProxy::searchSimilarTags(const std::string &input) { return syncFuncCall(input, -1, ai_business_data_management_call_search_similar_tags_sync); } std::string DataManagementServiceProxy::searchFilesAboutTags(const std::string &input) { return syncFuncCall(input, -1, ai_business_data_management_call_search_files_about_tags_sync); } std::string DataManagementServiceProxy::isFileRelevantToTags(const std::string &input) { return syncFuncCall(input, 3600000, ai_business_data_management_call_is_file_relevant_to_tags_sync); } std::string DataManagementServiceProxy::isFileRelevantToDescription(const std::string &input) { return syncFuncCall(input, 3600000, ai_business_data_management_call_is_file_relevant_to_description_sync); } std::string DataManagementServiceProxy::extractSearchConditions(const std::string &input) { return syncFuncCall(input, 600000, ai_business_data_management_call_extract_search_conditions_sync); } std::string DataManagementServiceProxy::getSummarysOfFiles(const std::string &input) { return syncFuncCall(input, 600000, ai_business_data_management_call_get_summarys_of_files_sync); } libkysdk-ai-private/libkyai-data-management-client/src/_datamanagementsession.h0000664000175000017500000000542515160473263026762 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _DATAMANAGEMENTSESSION_H #define _DATAMANAGEMENTSESSION_H #include #include #include "datamanagementserviceproxy.h" #define STATUS_SUCCESS InitializeStatus(true, 0, "") #define STATUS_FAILURE(errorCode, errorMsg) InitializeStatus(false, errorCode, errorMsg) extern DataManagementStatus InitializeStatus(bool success, int errorCode, const char* errorMsg); namespace datamanagement { class _DataManagementSession { public: _DataManagementSession() : proxy_(std::make_shared()) {}; DataManagementStatus checkFileFormat(const std::string& filePath, std::string& formatResult); DataManagementStatus similaritySearch(const std::string& searchConditions, std::string& searchResult); DataManagementStatus addTextFiles(const std::string& fileinfos); DataManagementStatus addImageFiles(const std::string& fileinfos); DataManagementStatus deleteFiles(const std::string& fileinfos); DataManagementStatus updateFilesName(const std::string& fileinfos); DataManagementStatus updateContentData(const std::string& fileinfos); DataManagementStatus getAllFileinfos(std::string& result); DataManagementStatus getFeatureStatus(int& status); DataManagementStatus getTagsOfFiles(const std::string& files, std::string& result); DataManagementStatus getAllTags(std::string& result); DataManagementStatus searchSimilarTags(const std::string& tags, std::string& result); DataManagementStatus searchFilesAboutTags(const std::string& tags, std::string& result); DataManagementStatus isFileRelevantToTags(const std::string& fileInfos, bool& isRelevant); DataManagementStatus isFileRelevantToDescription(const std::string& fileInfos, bool& isRelevant); DataManagementStatus extractSearchConditions(const std::string& description, std::string& conditions); DataManagementStatus getSummarysOfFiles(const std::string& files, std::string& summary); bool connect(); private: std::shared_ptr proxy_; }; } // namespace datamanagement #endif // _DATAMANAGEMENTSESSION_H libkysdk-ai-private/libkyai-data-management-client/CMakeLists.txt0000664000175000017500000000315615160473263024050 0ustar fengfengcmake_minimum_required(VERSION 3.16) project(kyai-data-management-client LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(PkgConfig REQUIRED) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-unix-2.0) find_package(nlohmann_json REQUIRED) find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(DATA_MANAGEMENT_PROTO_FILES --glib-min-required=2.64 datamanagementservice) include_directories( ${PROJECT_SOURCE_DIR}/include ${GIO_INCLUDE_DIRS}) file(GLOB_RECURSE SOURCE_FLIES ${PROJECT_SOURCE_DIR}/src/*.cpp) add_library(kyai-data-management-client SHARED ${SOURCE_FLIES} ${DATA_MANAGEMENT_PROTO_FILES}) set_target_properties(kyai-data-management-client PROPERTIES VERSION 1.0.0 SOVERSION 1) target_link_libraries(kyai-data-management-client PRIVATE PkgConfig::GIO PRIVATE nlohmann_json::nlohmann_json) # 解决龙芯架构不支持 fstream 标准库问题 if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9) target_link_libraries(kyai-data-management-client PRIVATE stdc++fs) endif () endif () install(TARGETS kyai-data-management-client LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) install(DIRECTORY include/ DESTINATION include) install(FILES pkgconf/kyai-data-management-client.pc DESTINATION /usr/share/pkgconfig) if (DEFINED ENABLE_TEST) unset(ENABLE_TEST CACHE) endif(DEFINED ENABLE_TEST) option(ENABLE_TEST "Build Test" OFF) if (ENABLE_TEST) add_subdirectory(test) endif (ENABLE_TEST) libkysdk-ai-private/libkyai-data-management-client/include/0000775000175000017500000000000015160473263022726 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/0000775000175000017500000000000015160473263024443 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/0000775000175000017500000000000015160473263026276 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/data-management/0000775000175000017500000000000015160473263031321 5ustar fengfeng././@LongLink0000644000000000000000000000015600000000000011605 Lustar rootrootlibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/data-management/datamanagement.hlibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/data-management/dataman0000664000175000017500000003304115160473263032652 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef DATAMANAGEMENT_DATAMANAGEMENT_H #define DATAMANAGEMENT_DATAMANAGEMENT_H #include #ifdef __cplusplus extern "C" { #endif typedef struct _DataManagementSession DataManagementSession; /** * \brief 判断当前系统架构是否支持AI功能 */ bool data_management_is_feature_supported(); /*! * \brief 创建数据管理会话 * \return 失败将返回 nullptr */ DataManagementSession* data_management_create_session(); /*! * \brief 销毁数据管理会话 */ void data_management_destroy_session(DataManagementSession* session); /*! * \brief 释放请求返回的结果 */ void data_management_destroy_result(char* result); /*! * \brief 获取当前会话支持的功能状态 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param status 获取到的功能状态,入参不能为 nullptr,函数内会修改 status 的值 * \return 成功将返回 SearchResult::SEARCH_SUCCESS,失败则会返回对应错误码 * \example 示例用法 * FeatureStatus status = FeatureStatus::UNKNOWN; * DataManagementStatus status = data_management_get_feature_status(session, * &status); if (status.success && status == FeatureStatus::AVAILABLE) { * do_something(); * } */ DataManagementStatus data_management_get_feature_status(DataManagementSession* session, FeatureStatus* status); /*! * \brief 检查文件是否支持,返回识别到的文件格式,需要在调用 * data_management_add_files 前使用 \param session 请求所使用的会话,通过 * data_management_create_session 创建 \param filepath 检查的文件绝对路径 \param * result 检查的格式结果,为 json 格式,格式如下 * { * "supported": true * "format" : "txt" * } * supported 字段代表当前文件是否支持,对于不支持的文件在 * data_management_add_files 时会返回 DATA_MANAGEMENT_FILE_FORMAT_ERROR format * 字段代表识别到的格式,可以用作 data_management_add_files 时入参的 fileformat * result 需要使用 data_management_destroy_result 释放 * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_check_file_format(DataManagementSession* session, const char* filepath, char** check_result); /*! * \brief 会通过语意相似度搜索文件内容,返回包含相关内容的文件 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param search_conditions 要搜索的内容,是一个 json 格式的字符串,格式如下: * { * "text": "linux内核安全选项" * "similarity-threshold" : 0.6 * } * similarity-threshold * 代表相似度阈值,只会返回超过这个阈值的结果,如果不写则使用 默认的相似度阈值 * \param search_result * 返回搜索结果,一般传入一个空指针,由SDK申请内存,在使用完后 通过 * data_management_destroy_result 进行销毁。 搜索结果为一段 json * 格式的文件列表,包含"filepath"和"similarity" 两个字段,格式如下: * [ * { * "filepath": "/path/to/file1.txt", * "similarity": 0.92 * }, * { * "filepath": "/path/to/file2.txt", * "similarity": 0.85 * } * ] * 结果默认会根据相似度进行排序,越接近1认为相似度越高 * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_similarity_search(DataManagementSession* session, const char* search_conditions, char** search_result); /*! * \brief 将新文件增加到会话的数据范围中 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos 要增加到搜索范围里的文件列表,使用 json 格式,格式参考如下: * [ * { * "filepath": "/path/to/file3.pdf", * "fileformat": "pdf" * }, * { * "filepath": "/path/to/file1.txt", * "fileformat": "txt" * } * ] * filepath 字段要求是文件的绝对路径 * fileformat 字段目前支持 pdf, txt, docx, pptx 格式,可以通过 * data_management_check_file_format 获取 如果 fileformat * 为空会默认使用文件的后缀 \return 成功 DataManagementStatus::success 为 * true,失败则会返回对应错误码 */ DataManagementStatus data_management_add_text_files(DataManagementSession* session, const char* fileinfos); /*! * \brief 将新文件增加到会话的数据中 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos 要增加到搜索范围里的文件列表,使用 json 格式,格式参考如下: * [ * { * "filepath": "/path/to/file3.jpeg", * "fileformat": "jpeg" * }, * { * "filepath": "/path/to/file2.png", * "fileformat": "png" * } * ] * fileformat 目前支持 png, jpg, jepg 格式 * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_add_image_files(DataManagementSession* session, const char* fileinfos); /*! * \brief 将文件从会话的数据中删除 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos 要从会话的文件里删除的文件列表,字符串为 json * 格式,其中路径为绝对路径 * [ * { * "filepath": "/path/to/file2.png" * }, * { * "filepath": "/path/to/file1.pdf" * } * ] * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_delete_files(DataManagementSession* session, const char* fileinfos); /*! * \brief 更新文件名,不重建向量 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos 要从会话的文件里重命名的文件列表,字符串为 json * 格式,其中路径为绝对路径 * [ * { * "old_filepath": "/path/to/file2.png", * "new_filepath": "/path/to/newfile2.png" * }, * { * "old_filepath": "/path/to/file1.txt", * "new_filepath": "/path/to/newfile1.txt" * } * ] * \param new_fileinfos * 新文件文件列表,格式和旧文件列表一致,和旧文件列表需要是一一对应关系 \return * 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_update_files_name(DataManagementSession* session, const char* fileinfos); /*! * \brief 更新文件的向量数据 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos 要从会话的文件要更新的文件列表,字符串为 json * 格式,其中路径为绝对路径 * [ * { * "filepath": "/path/to/file2.png", * "fileformat": "png" * }, * { * "filepath": "/path/to/file1.pdf", * "fileformat": "pdf" * } * ] * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_update_files_content(DataManagementSession* session, const char* fileinfos); /*! * \brief 获取当前会话所有文件及修改时间列表 * \param session 请求所使用的会话,通过 data_management_create_session 创建 * \param fileinfos_result 文件列表,返回查询结果,一般传入一个 * nullptr,由SDK申请内存, 需要通过 data_management_destroy_result 销毁 * 返回的结果为 json 格式,包含文件的绝对路径和文件修改时间的UNIX时间戳 * [ * { * "filepath": "/path/to/file3.jpeg", * "timestamp": 123456 * }, * { * "filepath": "/path/to/file2.png", * "timestamp": 654321 * } * ] * \return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_get_all_fileinfos(DataManagementSession* session, char** fileinfos_result); /** * @brief 获取文件的标签 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] files 'files'做为key的Json字符串,示例: * { * "files": ["xxxx1","xxxx2"...] * } * @param [out] result 返回的Json array字符串,示例: * [ * { * "filepath": xxx, * "tags": ["xxxx1","xxxx2"...] * }, * ... * ] * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_get_tags_of_files(DataManagementSession* session, const char* files, char** result); /** * @brief 获取当前存储的所有标签名称 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [out] tags_result 返回的Json array字符串,示例:["xxxx1","xxxx2"...] * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_get_all_tags(DataManagementSession* session, char** result); /** * @brief 搜索相似标签 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] tags 'tags'做为key的Json字符串,示例: * { * "tags": ["xxxx1","xxxx2"...] * } * @param [out] result 返回的Json array字符串,示例:["xxxx1","xxxx2"...] * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_search_similar_tags(DataManagementSession* session, const char* tags, char** result); /** * @brief 根据标签搜索文件 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] tags 'tags'做为key的Json字符串,示例: * { * "tags": ["xxxx1","xxxx2"...] * } * @param [out] result 返回的Json array字符串,示例:["xxxx1","xxxx2"...] * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_search_files_about_tags(DataManagementSession* session, const char* tags, char** result); /** * @brief 判断文件和标签是否相关 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] fileinfos 'file' 'tags'做为key的Json字符串,示例: * { * "file": xxxx, * "tags": ["xxxx1","xxxx2"...] * } * @param [out] isRelevant true 相关;false 不相关 * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_is_file_relevant_to_tags(DataManagementSession* session, const char* fileInfos, bool* isRelevant); /** * @brief 判断文件和内容是否相关 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] fileinfos 'file' 'description'做为key的Json字符串,示例: * { * "file": xxxx, * "description": xxxxx * } * @param [out] isRelevant true 相关;false 不相关 * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_is_file_relevant_to_description(DataManagementSession* session, const char* fileInfos, bool* isRelevant); /** * @brief 根据描述生成搜索条件结构 * @param session 请求所使用的会话,通过 data_management_create_session 创建 * @param description 'description'做为key的Json字符串,示例: * { * "description": xxxxx * } * @param result 搜索条件结构 * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_extract_search_conditions(DataManagementSession* session, const char* description, char** result); /** * @brief 获取文件的摘要 * @param [in] session 请求所使用的会话,通过 data_management_create_session 创建 * @param [in] files 'files'做为key的Json字符串,示例: * { * "files": ["xxxx1","xxxx2"...] * } * @param [out] result 返回的Json array字符串,示例: * [ * { * "filepath": xxxx1, * "summary": xxxxxxxxx * }, * ... * ] * @return 成功 DataManagementStatus::success 为 true,失败则会返回对应错误码 */ DataManagementStatus data_management_get_summarys_of_files(DataManagementSession* session, const char* files, char** result); #ifdef __cplusplus } #endif #endif // DATAMANAGEMENT_DATAMANAGEMENT_H ././@LongLink0000644000000000000000000000014600000000000011604 Lustar rootrootlibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/data-management/common.hlibkysdk-ai-private/libkyai-data-management-client/include/kylin-ai/business/data-management/common.0000664000175000017500000000236315160473263032616 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef DATAMANAGEMENT_COMMON_H #define DATAMANAGEMENT_COMMON_H #ifdef __cplusplus extern "C" { #endif typedef enum { UNKNOWN = -1, AVAILABLE = 0, NOT_INSTALLED } FeatureStatus; typedef enum { SUCCESS = 0, PARSE_PARAM_FAILED = 14, DM_ERROR_UNKNOWN = 100, DM_SESSION_ERROR = 101, } ErrorCode; typedef struct { bool success; // 表示操作是否成功 int errorCode; // 错误代码,0表示无错误 char errorMsg[500]; // 错误消息 } DataManagementStatus; #ifdef __cplusplus } #endif #endif // DATAMANAGEMENT_COMMON_H libkysdk-ai-private/libkyai-data-management-client/test/0000775000175000017500000000000015160473263022262 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/test/CMakeLists.txt0000664000175000017500000000053015160473263025020 0ustar fengfengcmake_minimum_required(VERSION 3.16) project(test LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) include_directories( ${PROJECT_SOURCE_DIR}/../include ) find_package(GTest) add_executable(units-test test.cpp) target_link_libraries(units-test PUBLIC kyai-data-management-client GTest::GTest GTest::Main) libkysdk-ai-private/libkyai-data-management-client/test/test.cpp0000664000175000017500000001567015160473263023756 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "test.h" void checkStatus(DataManagementStatus status) { ASSERT_EQ(status.success, true) << "errno: " << status.errorCode << ", errmsg: " << status.errorMsg; } // 清空数据 TEST_F(DataManagementTest, delete_files) { std::cout << "Testing delete_files..." << std::endl; std::string input = R"([ { "filepath": "/usr/lib/xorg/protocol.txt" }, { "filepath": "/" } ])"; DataManagementStatus status = data_management_delete_files(session, input.c_str()); checkStatus(status); // 所有数据库应该都没有数据 status = data_management_get_all_fileinfos(session, &result); checkStatus(status); ASSERT_STREQ("[]", result) << result; } TEST_F(DataManagementTest, add_text_files) { std::cout << "Testing add_text_files..." << std::endl; std::string input = R"([ { "filepath": "/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txt", "fileformat": "txt" }, { "filepath": "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt", "fileformat": "txt" }, { "filepath": "/home/hezhe/文档/操作系统大会演示素材v0.2/测试素材/纯图片文件.docx", "fileformat": "docx" } ])"; DataManagementStatus status = data_management_add_text_files(session, input.c_str()); checkStatus(status); } TEST_F(DataManagementTest, get_all_fileinfos) { std::cout << "Testing get_all_fileinfos..." << std::endl; DataManagementStatus status = data_management_get_all_fileinfos(session, &result); checkStatus(status); // [{"filepath":"/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txt","timestamp":1721056006},{"filepath":"/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt","timestamp":1721931246}] } TEST_F(DataManagementTest, get_tags_of_files) { std::cout << "Testing get_tags_of_files..." << std::endl; std::string input = R"({ "files": [ "/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txt", "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt" ] })"; DataManagementStatus status = data_management_get_tags_of_files(session, input.c_str(), &result); checkStatus(status); } TEST_F(DataManagementTest, get_all_tags) { std::cout << "Testing get_all_tags..." << std::endl; DataManagementStatus status = data_management_get_all_tags(session, &result); checkStatus(status); } TEST_F(DataManagementTest, search_similar_tags) { std::cout << "Testing search_similar_tags..." << std::endl; std::string input = R"({ "tags": [ "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txttag1", "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txttag2" ] })"; DataManagementStatus status = data_management_search_similar_tags(session, input.c_str(), &result); checkStatus(status); } TEST_F(DataManagementTest, search_files_about_tags) { std::cout << "Testing search_files_about_tags..." << std::endl; std::string input = R"({ "tags": [ "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txttag1", "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txttag2" ] })"; DataManagementStatus status = data_management_search_files_about_tags(session, input.c_str(), &result); checkStatus(status); } TEST_F(DataManagementTest, is_file_relevant_to_tags) { std::cout << "Testing is_file_relevant_to_tags..." << std::endl; std::string input = R"({ "file": "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt", "tags": [ "/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txt", "/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txttag" ] })"; bool isRelevant; DataManagementStatus status = data_management_is_file_relevant_to_tags(session, input.c_str(), &isRelevant); checkStatus(status); std::cout << "isRelevant: " << isRelevant << std::endl; ASSERT_TRUE(isRelevant); } TEST_F(DataManagementTest, is_file_relevant_to_description) { std::cout << "Testing is_file_relevant_to_description..." << std::endl; std::string input = R"({ "file": "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt", "description": "定期定额投资" })"; bool isRelevant; DataManagementStatus status = data_management_is_file_relevant_to_description(session, input.c_str(), &isRelevant); checkStatus(status); std::cout << "isRelevant: " << isRelevant << std::endl; ASSERT_TRUE(isRelevant); } TEST_F(DataManagementTest, extract_search_conditions) { std::cout << "Testing extract_search_conditions..." << std::endl; std::string input = R"({ "description": "搜索一下狗狗的图片" })"; DataManagementStatus status = data_management_extract_search_conditions(session, input.c_str(), &result); checkStatus(status); EXPECT_STREQ( result, R"({"0":{"condition type":3,"content":"搜索一下狗狗的图片","orCondition":false},"conditions count":1,"labels":[]})"); } TEST_F(DataManagementTest, get_summarys_of_files) { std::cout << "Testing get_summarys_of_files..." << std::endl; std::string input = R"({ "files": [ "/home/hezhe/文档/操作系统大会演示素材v0.2/待办.txt", "/home/hezhe/文档/操作系统大会演示素材v0.2/金信-金融问答.txt" ] })"; DataManagementStatus status = data_management_get_summarys_of_files(session, input.c_str(), &result); checkStatus(status); } TEST_F(DataManagementTest, get_feature_status) { std::cout << "Testing get_feature_status..." << std::endl; FeatureStatus status; DataManagementStatus ret = data_management_get_feature_status(session, &status); std::cout << "FeatureStatus: " << status << std::endl; checkStatus(ret); } TEST_F(DataManagementTest, is_feature_supported) { std::cout << "Testing is_feature_supported..." << std::endl; EXPECT_TRUE(data_management_is_feature_supported()); } libkysdk-ai-private/libkyai-data-management-client/test/test.h0000664000175000017500000000263715160473263023422 0ustar fengfeng/* * Copyright (C) 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #pragma once #include #include class DataManagementTest : public testing::Test { protected: // 每个案例之前执行 void SetUp() override { std::cout << "SetUp..." << std::endl; session = data_management_create_session(); result = nullptr; } // 每个案例之后执行 void TearDown() override { std::cout << "TearDown..." << std::endl; data_management_destroy_session(session); if (result != nullptr) { std::cout << "Result is " << result << std::endl; data_management_destroy_result(result); } } public: DataManagementSession* session; char* result; }; libkysdk-ai-private/libkyai-data-management-client/pkgconf/0000775000175000017500000000000015160473263022732 5ustar fengfenglibkysdk-ai-private/libkyai-data-management-client/pkgconf/kyai-data-management-client.pc0000664000175000017500000000024115160473263030505 0ustar fengfengName: kyai-data-management-client Description: Kylin ai data management client Version: 1.0.0 Libs: -lkyai-data-management-client Cflags: -I/usr/include/kylin-ai