pax_global_header00006660000000000000000000000064152060001610014501gustar00rootroot0000000000000052 comment=6f72bf57223f6d5cac0610a6d92af159457cb99c kylin-ai-document-qa-service-1.2.0.0/000077500000000000000000000000001520600016100172255ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/.clang-format000066400000000000000000000002131520600016100215740ustar00rootroot00000000000000--- Language: Cpp BasedOnStyle: Google ColumnLimit: 120 IndentWidth: 4 AccessModifierOffset: -4 TabWidth: 4 #DerivePointerAlignment: false kylin-ai-document-qa-service-1.2.0.0/CMakeLists.txt000066400000000000000000000003031520600016100217610ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kylin-ai-document-qa-service LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) add_subdirectory(document-qa-service) add_subdirectory(document-qa-client) kylin-ai-document-qa-service-1.2.0.0/LICENSE000066400000000000000000001045141520600016100202370ustar00rootroot00000000000000 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 .kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/000077500000000000000000000000001520600016100234045ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/CMakeLists.txt000066400000000000000000000016221520600016100261450ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(knowledgebase_tool) set(TARGET knowledgebase_tool) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) file(GLOB_RECURSE SOURCE_LIST ${PROJECT_SOURCE_DIR}/service/*.cpp main.cpp) include_directories(${PROJECT_SOURCE_DIR}/service) find_package(PkgConfig REQUIRED) pkg_check_modules(Embedding REQUIRED IMPORTED_TARGET kysdk-coreai-embedding) pkg_check_modules(VECTORDB REQUIRED IMPORTED_TARGET kysdk-vector-engine-client) pkg_check_modules(UUID REQUIRED IMPORTED_TARGET uuid) pkg_check_modules(KYDOCUMENT REQUIRED IMPORTED_TARGET kylin-ai-document-service) find_package(nlohmann_json REQUIRED) add_executable(${TARGET} ${SOURCE_LIST}) target_link_libraries(${TARGET} PRIVATE PkgConfig::Embedding PRIVATE PkgConfig::VECTORDB PRIVATE PkgConfig::KYDOCUMENT PRIVATE nlohmann_json::nlohmann_json PRIVATE PkgConfig::UUID)kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/README.md000066400000000000000000000047771520600016100247020ustar00rootroot00000000000000预制知识库工具 使用说明 为了保证数据的安全性 本工具所有接口都是操作拷贝出来的数据库文件 步骤1:首先停止系统自启动的向量数据库进程 systemctl --user stop kylin-ai-vector-engine.service 步骤2:为避免数据污染,每次更新预制知识库的时候,都需要拷贝一份干净的db文件 从/usr/share/kylin-ai-vector-engine/default.db 拷贝出一份 此时需要手动启动一个kylin-ai-vector-engine进程 命令如下: /usr/bin/kylin-ai-vector-engine /path/default.db localhost:19530 INFO 注: ①:/path/default.db是你拷贝出来的向量数据库路径 ②:路径不能有中文 步骤3:工具创建的默认向量数据库表结构如下:如果需要修改表结构,需要修改create和add接口内部与向量数据库相关的代码 CollectionSchema collection_schema(name); collection_schema.AddField(FieldSchema(DATABASE_FILE_PATH, DataType::VARCHAR, "file path").WithMaxLength(100)); collection_schema.AddField( FieldSchema(DATABASE_DOCUMENT, DataType::VARCHAR, "document contents").WithMaxLength(1024)); collection_schema.AddField(FieldSchema(DATABASE_ID, DataType::VARCHAR, "ids", true, false).WithMaxLength(40)); collection_schema.AddField( FieldSchema(DATABASE_VECTOR, DataType::FLOAT_VECTOR, "vectors").WithDimension(DIMENSION)); IndexDesc index_desc(DATABASE_VECTOR, "vector-index", 0); 步骤4:使用工具 创建默认知识库 参数:name --create 增加文件 参数: name --add filepath 删除文件 参数:name --delete filepath 更新文件 参数 name -- update filepath 搜索 参数 name --search text threshold 删除默认知识库 参数:name --drop example: ①: ./knowledgebase_tool kylin --create 创建一个名为 kylin 的collection ②: ./knowledgebase_tool kylin --add /home/kylin/xxx 在kylin 表中添加文件 文件路径为 /home/kylin/xxx(目录和路径均可,需要为本地真实路径文件) ③: ./knowledgebase_tool kylin --delete /home/kylin/xxx 在kylin 表中删除文件 文件路径为 /home/kylin/xxx(仅支持传入路径) ④: ./knowledgebase_tool kylin --update /home/kylin/xxx 在kylin 表中更新文件 文件路径为 /home/kylin/xxx(目录和路径均可,需要为本地真实路径文件) ⑤: ./knowledgebase_tool kylin --search 如何使用AI助手 0.7 在kylin 表中进行相似搜索 搜索条件为 如何使用AI助手 会返回阈值大于0.7的内容 ⑥: ./knowledgebase_tool kylin --drop 删除一个名为 kylin 的collection kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/main.cpp000066400000000000000000000160741520600016100250440ustar00rootroot00000000000000/* * 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 #include #include #include #include #include #include "service.h" namespace fs = std::filesystem; std::vector collectAllFiles(const std::string& path) { std::vector files; // 检查路径是否存在 if (!fs::exists(path)) { std::cerr << "Path does not exist." << std::endl; return files; } // 根据路径类型执行不同逻辑 if (fs::is_regular_file(path)) { // 输入是文件 std::cout << "input is filepath." << std::endl; files.push_back(path); } else if (fs::is_directory(path)) { // 输入是目录 // 递归遍历目录下的所有文件 std::cout << "input is directory." << std::endl; std::cout << "start to collect all filepahts." << std::endl; for (const auto& entry : fs::recursive_directory_iterator(path)) { if (entry.is_regular_file()) { files.push_back(entry.path().string()); } } } std::cout << "collect all filepahts sucess." << std::endl; return files; } void createCollection(const std::string& name) { std::cout << "createCollection start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->createCollection(name); if (!ret) { std::cerr << "createCollection failed." << std::endl; return; } std::cout << "createCollection sucess." << std::endl; std::cout << "createCollection name is: " << name << std::endl; } void addFiles(const std::string& name, const std::string& filepath) { std::vector input = collectAllFiles(filepath); if (input.empty()) { std::cerr << "Error: no file found in the directory." << std::endl; return; } std::cout << "addFiles start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->addFiles(name, input); if (!ret) { std::cerr << "addFiles failed." << std::endl; } std::cout << "addFiles sucess." << std::endl; } void deleteFiles(const std::string& name, const std::string& filepath) { std::vector input{filepath}; std::cout << "deleteFiles start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->deleteFiles(name, input); if (!ret) { std::cerr << "deleteFiles failed." << std::endl; } std::cout << "deleteFiles sucess." << std::endl; } void updateFiles(const std::string& name, const std::string& filepath) { std::cout << "updateFiles start." << std::endl; std::vector input = collectAllFiles(filepath); if (input.empty()) { std::cerr << "Error: no file found in the directory." << std::endl; return; } bool ret = knowledgebase_tool::Service::getInstance()->updateFiles(name, input); if (!ret) { std::cerr << "updateFiles failed." << std::endl; } std::cout << "updateFiles sucess." << std::endl; } void search(const std::string& name, const std::string& text, float threshold = 0.6) { std::cout << "search start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->search(name, text, threshold); if (!ret) { std::cerr << "search failed." << std::endl; } std::cout << "search sucess." << std::endl; } void dropCollection(const std::string& name) { std::cout << "dropCollection start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->dropCollection(name); if (!ret) { std::cerr << "dropCollection failed." << std::endl; } std::cout << "dropCollection sucess." << std::endl; } void query(const std::string& name) { std::cout << "query start." << std::endl; bool ret = knowledgebase_tool::Service::getInstance()->query(name); if (!ret) { std::cerr << "query failed." << std::endl; } std::cout << "query sucess." << std::endl; } void printUsage(const std::string& progName) { std::cerr << "Usage: " << progName << " [args...]\n"; std::cerr << "Commands:\n"; std::cerr << " [name] --create Create the collection\n"; std::cerr << " [name] --add Add a file\n"; std::cerr << " [name] --delete Delete a file\n"; std::cerr << " [name] --update Update a file\n"; std::cerr << " [name] --search Search for text\n"; std::cerr << " [name] --query Query the collection\n"; std::cerr << " [name] --drop Drop the collection\n"; } int main(int argc, char* argv[]) { if (argc < 3) { printUsage(argv[0]); return 1; } std::string dbName = argv[1]; std::string command = argv[2]; if (command == "--create") { if (argc != 3) { std::cerr << "Error: --create does not require additional arguments\n"; return 1; } createCollection(dbName); } else if (command == "--add") { if (argc < 4) { std::cerr << "Error: --add does not require additional arguments\n"; return 1; } addFiles(dbName, argv[3]); } else if (command == "--delete") { if (argc < 4) { std::cerr << "Error: --delete does not require additional arguments\n"; return 1; } deleteFiles(dbName, argv[3]); } else if (command == "--update") { if (argc < 4) { std::cerr << "Error: --update does not require additional arguments\n\n"; return 1; } updateFiles(dbName, argv[3]); } else if (command == "--search") { if (argc < 4) { std::cerr << "Error: --search does not require additional arguments\n\n"; return 1; } double threshold = atof(argv[4]); search(dbName, argv[3], threshold); } else if (command == "--drop") { if (argc != 3) { std::cerr << "Error: --drop does not require additional arguments\n"; return 1; } dropCollection(dbName); } else if (command == "--query") { if (argc != 3) { std::cerr << "Error: --query does not require additional arguments\n"; return 1; } query(dbName); } else { std::cerr << "Error: Unknown command '" << command << "'\n"; printUsage(argv[0]); return 1; } return 0; }kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/service/000077500000000000000000000000001520600016100250445ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/service/service.cpp000066400000000000000000000452751520600016100272250ustar00rootroot00000000000000/* * 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 "service.h" #include #include #include #include #include #include #include #include namespace knowledgebase_tool { static const char* DATABASE_FILE_PATH = "filepath"; static const char* DATABASE_DOCUMENT = "document"; static const char* DATABASE_ID = "ids"; static const char* DATABASE_VECTOR = "vector"; static uint32_t DIMENSION = 768; const char* DOCUMENT_CHUNK_TEXT_TYPE = "TextChunker"; const char* DOCUMENT_RESPONSE_DATA = "responseData"; const int DOCUMENT_CHUNK_TEXT_SIZE = 800; const char* CHUNKS = "chunks"; const char* FILEPATH = "filePath"; using namespace VectorDB; std::string generateUUID() { uuid_t uuid; char uuid_str[37]; uuid_generate_random(uuid); uuid_unparse(uuid, uuid_str); std::string id = uuid_str; return id; } bool Service::checkStatus(std::string&& prefix, const Status& status) { if (!status.IsOk()) { std::cerr << prefix << ",errMsg: " << status.Message() << std::endl; return false; } return true; } Service::Service() { client_ = Database::Create(); } Service::~Service() { disconnect(); } bool Service::disconnect() { auto status = client_->Disconnect(); if (!checkStatus("Failed to disconnect vector db ", status)) { return false; } return true; } bool Service::hasCollection(const std::string& name) { bool exist; auto status = client_->HasCollection(name, exist); // 数据库接口有问题,临时兼容下,如果返回报错也认为不存在,Failed to has TEST collection: 1002: collection not found if (!status.IsOk()) { return false; } return exist; } bool Service::createCollection(const std::string& name) { ConnectParam connect_param("localhost:19530"); // 19539 milvus-lite官方推荐端口 auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } if (hasCollection(name)) { return true; } CollectionSchema collection_schema(name); collection_schema.AddField(FieldSchema(DATABASE_FILE_PATH, DataType::VARCHAR, "file path").WithMaxLength(100)); collection_schema.AddField( FieldSchema(DATABASE_DOCUMENT, DataType::VARCHAR, "document contents").WithMaxLength(1024)); collection_schema.AddField(FieldSchema(DATABASE_ID, DataType::VARCHAR, "ids", true, false).WithMaxLength(40)); collection_schema.AddField( FieldSchema(DATABASE_VECTOR, DataType::FLOAT_VECTOR, "vectors").WithDimension(DIMENSION)); IndexDesc index_desc(DATABASE_VECTOR, "vector-index", 0); status = client_->CreateCollection(collection_schema, index_desc); if (!checkStatus("Failed to create collection " + name, status)) { return false; } return true; } bool Service::addFiles(const std::string& name, const std::vector& filepaths) { ConnectParam connect_param("localhost:19530"); // 19539 milvus-lite官方推荐端口 auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } // 分块 获得向量化结果 std::vector chunkResult = getChunkResult(filepaths, DOCUMENT_CHUNK_TEXT_SIZE); if (chunkResult.empty()) { std::cerr << "Failed to add files, chunkResult is empty." << std::endl; return false; } std::vector infos; for (const auto& item : chunkResult) { std::vector> embeddingResult = embedding(item.chunk); KnowledgeFileInfo info{name, item.filePath, item.chunk, embeddingResult}; infos.push_back(info); } // 结果存入向量数据库 for (const KnowledgeFileInfo& fileinfo : infos) { std::vector ids; std::vector filepaths; std::vector> embeddings = fileinfo.vectors; std::vector documents = fileinfo.documents; for (int i = 0; i < embeddings.size(); i++) { ids.emplace_back(generateUUID()); filepaths.emplace_back(fileinfo.filePath); } std::vector fields_data{std::make_shared(DATABASE_ID, ids), std::make_shared(DATABASE_FILE_PATH, filepaths), std::make_shared(DATABASE_DOCUMENT, documents), std::make_shared(DATABASE_VECTOR, embeddings)}; DmlResults dml_results; auto status = client_->Insert(fileinfo.collectionName, fields_data, dml_results); if (!checkStatus("Failed to insert files", status)) { return false; } } return true; } bool Service::deleteFiles(const std::string& name, const std::vector& filepaths) { // std::cout << port << " 1111111111111" << std::endl; ConnectParam connect_param("localhost:19530"); // 19530 milvus-lite官方推荐端口 auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } for (const auto& filepath : filepaths) { std::string expression = std::string(DATABASE_FILE_PATH) + " == \"" + filepath + "\""; DmlResults results; auto status = client_->Delete(name, expression, results); if (!checkStatus("Failed to delete files: " + filepath, status)) { return false; } } // std::cout << port << " 22222222222222" << std::endl; return true; } bool Service::updateFiles(const std::string& name, const std::vector& filepaths) { // 先删在加 if (!deleteFiles(name, filepaths)) return false; if (!addFiles(name, filepaths)) return false; return true; } bool Service::search(const std::string& name, const std::string& text, float threshold) { ConnectParam connect_param("localhost:19530"); auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } // 向量化 std::vector> vectors = embedding(std::vector{text}); SearchArguments arguments{}; arguments.SetCollectionName(name); arguments.SetTopK(10); arguments.AddOutputField(DATABASE_DOCUMENT); arguments.AddOutputField(DATABASE_FILE_PATH); arguments.SetGuaranteeTimestamp(GuaranteeStrongTs()); arguments.AddTargetVector(DATABASE_VECTOR, vectors[0]); SearchResults results{}; status = client_->Search(arguments, results); if (!checkStatus("Failed to search", status)) { return false; } KnowledgebaseSearchResults output; for (const auto& result : results.Results()) { auto& ids = result.Ids().StrIDArray(); if (ids.empty()) { std::cerr << "SearchMetadata result is empty" << std::endl; continue; } auto similarity = result.Scores(); if (ids.size() != similarity.size()) { std::cerr << "Illegal search result" << std::endl; continue; } auto documentResult = result.OutputField(DATABASE_DOCUMENT); auto filepathResult = result.OutputField(DATABASE_FILE_PATH); VarCharFieldDataPtr documentResult_ptr = std::static_pointer_cast(documentResult); VarCharFieldDataPtr filepathResult_ptr = std::static_pointer_cast(filepathResult); auto documentResult_data = documentResult_ptr->Data(); auto filepathResult_data = filepathResult_ptr->Data(); for (int i = 0; i < ids.size(); i++) { // 根据相似度阈值筛选结果,数据库查询结果是按照相似度倒排的,如果出现相似度小于阈值的,后面的结果都比阈值小 if (similarity[i] < threshold) { std::cout << "SearchMetadata similarity " << similarity[i] << " less than threshold " << threshold << std::endl; break; } output.emplace_back( KnowledgebaseSearchResult{documentResult_data[i], std::string(filepathResult_data[i]), similarity[i]}); } } if (output.empty()) { std::cerr << "Search result is empty." << std::endl; return false; } std::cout << "Start print search result." << std::endl; for (const auto& item : output) { std::cout << "[filepath] :" << item.source << std::endl; std::cout << "[similarity] :" << item.similarity << std::endl; std::cout << "[document]: " << item.documents << std::endl; std::cout << std::endl; } std::cout << "Print search result end." << std::endl; return true; } bool Service::dropCollection(const std::string& name) { ConnectParam connect_param("localhost:19530"); auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } if (!hasCollection(name)) { return true; } status = client_->DropCollection(name); return checkStatus("Failed to drop collection " + name, status); } bool Service::query(const std::string& name) { ConnectParam connect_param("localhost:19530"); auto status = client_->Connect(connect_param); if (!checkStatus("Failed to connect vector db ", status)) { return false; } if (!hasCollection(name)) { return false; } QueryArguments arguments; arguments.SetCollectionName(name); // 查询输出哪些列 arguments.AddOutputField(DATABASE_FILE_PATH); // arguments.AddOutputField(DATABASE_DOCUMENT); // arguments.AddOutputField(DATABASE_ID); // arguments.AddOutputField(DATABASE_VECTOR); // 分两次查询 arguments.SetExpression("filepath LIKE '/%'"); std::cout << "First query" << std::endl; QueryResults queryResults; status = client_->Query(arguments, queryResults); checkStatus("Failed to query:", status); std::cout << "Query success. output field num: " << queryResults.OutputFields().size() << std::endl; FieldDataPtr filepath = queryResults.GetFieldByName(DATABASE_FILE_PATH); std::shared_ptr filepathFieldPtr = std::static_pointer_cast(filepath); auto& filepathData = filepathFieldPtr->Data(); std::cout << "Query filepath rows: " << filepathData.size() << std::endl; // FieldDataPtr ids = queryResults.GetFieldByName(DATABASE_ID); // std::shared_ptr idsFieldPtr = std::static_pointer_cast(ids); // auto& idsData = idsFieldPtr->Data(); // std::cout << "Query ids rows: " << idsData.size() << std::endl; // FieldDataPtr document = queryResults.GetFieldByName(DATABASE_DOCUMENT); // std::shared_ptr docFieldPtr = std::static_pointer_cast(document); // auto& docData = docFieldPtr->Data(); // std::cout << "Query document rows: " << docData.size() << std::endl; // FieldDataPtr vec = queryResults.GetFieldByName(DATABASE_VECTOR); // std::shared_ptr vecFieldPtr = std::static_pointer_cast(vec); // auto& vecData = vecFieldPtr->Data(); // std::cout << "Query vec rows: " << vecData.size() << std::endl; if (filepathData.empty()) { std::cout << "First query result is empty" << std::endl; return false; } std::unordered_set filepaths; // 过滤重复 for (int i = 0; i < filepathData.size(); ++i) { // std::cout << filepathFieldPtr->Name() << ": " << filepathData[i] << std::endl; filepaths.insert(filepathData[i]); } std::cout << "filepath 过滤后的结果:" << std::endl; // 输出所有路径 for (const auto& path : filepaths) { std::cout << "filepath: " << path << std::endl; } QueryArguments argumentsSec; argumentsSec.SetCollectionName(name); // 查询输出哪些列 argumentsSec.AddOutputField(DATABASE_FILE_PATH); std::cout << "Second query" << std::endl; // 分两次查询 argumentsSec.SetExpression("filepath LIKE 'F%'"); QueryResults queryResultsSecond; status = client_->Query(argumentsSec, queryResultsSecond); checkStatus("Failed to query:", status); std::cout << "Query success. output field num: " << queryResultsSecond.OutputFields().size() << std::endl; FieldDataPtr filepathSec = queryResultsSecond.GetFieldByName(DATABASE_FILE_PATH); std::shared_ptr filepathFieldPtrSec = std::static_pointer_cast(filepathSec); auto& filepathDataSec = filepathFieldPtrSec->Data(); std::cout << "Query filepath rows: " << filepathDataSec.size() << std::endl; if (filepathDataSec.empty()) { std::cout << "Second query result is empty" << std::endl; return false; } std::unordered_set filepathsSec; // 过滤重复 for (int i = 0; i < filepathDataSec.size(); ++i) { filepathsSec.insert(filepathDataSec[i]); } std::cout << "filepath 过滤后的结果:" << std::endl; // 输出所有路径 for (const auto& path : filepathsSec) { std::cout << "filepath: " << path << std::endl; } // std::vector> fields_datas; // for (int i = 0; i < idsData.size(); ++i) { // std::cout << idsFieldPtr->Name() << ": " << idsData[i] << "\t" << filepathFieldPtr->Name() << ": " // << filepathData[i] << "\t" << docFieldPtr->Name() << ": " << docData[i] << vecFieldPtr->Name() // << ": ["; // for (const auto& item : vecData[i]) { // std::cout << item << ", "; // } // std::cout << "]" << std::endl; // // fields_datas.emplace_back(std::vector{ // // std::make_shared(DATABASE_ID, std::vector{idsData[i]}), // // std::make_shared(DATABASE_FILE_PATH, std::vector{filepathData[i]}), // // std::make_shared(DATABASE_DOCUMENT, std::vector{docData[i]}), // // std::make_shared(DATABASE_ID, std::vector>{vecData[i]})}); // } return true; } std::vector> Service::embedding(const std::vector& texts) { // 调用向量化服务,向量化文本 TextEmbeddingSession* session = text_embedding_create_session(); int initSession = text_embedding_init_session(session); if (initSession != COREAI_EMBEDDING_SUCESS) { std::cerr << "init embedding session failed" << std::endl; return std::vector>(); } std::vector> res; for (const auto& item : texts) { EmbeddingResult* result = nullptr; bool sucess = text_embedding(session, item.c_str(), &result); if (!result) { std::cerr << "text embedding result is nullptr" << std::endl; continue; } if (embedding_result_get_error_code(result) != COREAI_EMBEDDING_SUCESS) { const char* error_message = embedding_result_get_error_message(result); std::cout << "error_message :" << error_message << std::endl; continue; } int vectorLength = embedding_result_get_vector_length(result); float* vectorData = embedding_result_get_vector_data(result); std::vector vec = std::vector(vectorData, vectorData + vectorLength); embedding_result_destroy(&result); res.emplace_back(vec); } if (session) { text_embedding_destroy_session(&session); } return res; } std::vector Service::getChunkResult(const std::vector& filePaths, int32_t size) { nlohmann::json ret = syncChunkDocument(filePaths, size); if (ret.empty()) { std::cerr << "chunk document server something wrong" << std::endl; return std::vector(); } return parseChunkResult(ret); } nlohmann::json Service::syncChunkDocument(const std::vector& filePaths, int32_t size) { // 调用分块服务 获得分块文本 std::shared_ptr client = std::make_shared(); std::vector chunkTypes(filePaths.size(), DOCUMENT_CHUNK_TEXT_TYPE); std::vector chunkSizes(filePaths.size(), size); auto result = client->SyncChunkDocument(filePaths, chunkTypes, chunkSizes); // grpc 通信异常 if (result.errorCode != 0) { std::cerr << "DocumentClient connect failed, err: " << result.errorCode << ",msg: " << result.errorMsg << std::endl; return nlohmann::json::array(); } nlohmann::json root = nlohmann::json::parse(result.data); if (root.empty() || !root.contains(DOCUMENT_RESPONSE_DATA) || !root[DOCUMENT_RESPONSE_DATA].is_array() || root[DOCUMENT_RESPONSE_DATA].empty()) { std::cerr << "Failed to parse DocumentClient result: " << result.data << std::endl; return nlohmann::json::array(); } nlohmann::json& data = root[DOCUMENT_RESPONSE_DATA]; // 过滤掉 没有 filePath 或 chunks 的结果 data.erase(std::remove_if( data.begin(), data.end(), [](const nlohmann::json& value) { return !value.contains(FILEPATH) || !value.contains(CHUNKS); }), data.end()); return data; } std::vector Service::parseChunkResult(nlohmann::json& data) { std::vector res; // 解析分块结果 for (const auto& item : data) { ChunkResult chunkResult; std::string file_path = item["filePath"]; chunkResult.filePath = file_path; std::vector chunks; for (const auto& chunk : item["chunks"]) { chunks.push_back(chunk); } chunkResult.chunk = chunks; res.push_back(chunkResult); } return res; } } // namespace knowledgebase_tool kylin-ai-document-qa-service-1.2.0.0/defaultknowledgebase/service/service.h000066400000000000000000000050211520600016100266530ustar00rootroot00000000000000/* * 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 #include #include namespace knowledgebase_tool { struct ChunkResult { std::string filePath; std::vector chunk; }; struct KnowledgeFileInfo { const std::string collectionName; std::string filePath; std::vector documents; std::vector> vectors; }; struct KnowledgebaseSearchResult { std::string documents; std::string source; double similarity; }; using KnowledgebaseSearchResults = std::vector; class Service { public: static Service* getInstance() { static Service service; return &service; } bool createCollection(const std::string& name); bool addFiles(const std::string& name, const std::vector& filepaths); bool deleteFiles(const std::string& name, const std::vector& filepaths); bool updateFiles(const std::string& name, const std::vector& filepaths); bool search(const std::string& name, const std::string& text, float threshold); bool dropCollection(const std::string& name); bool query(const std::string& name); private: Service(); ~Service(); static bool checkStatus(std::string&& prefix, const VectorDB::Status& status); bool hasCollection(const std::string& name); bool disconnect(); private: std::vector> embedding(const std::vector& texts); std::vector getChunkResult(const std::vector& filePaths, int32_t size); nlohmann::json syncChunkDocument(const std::vector& filePaths, int32_t size); std::vector parseChunkResult(nlohmann::json& data); private: std::shared_ptr client_; }; } // namespace knowledgebase_tool kylin-ai-document-qa-service-1.2.0.0/document-qa-client/000077500000000000000000000000001520600016100227165ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/CMakeLists.txt000066400000000000000000000025531520600016100254630ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kyai-knowledgebase-client LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(PkgConfig REQUIRED) find_package(KylinAiProto REQUIRED) find_package(nlohmann_json REQUIRED) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-unix-2.0) kylin_ai_generate_gdbus_proto_code(RETURNED_GDBUS_GLUE_FILES --glib-min-required=2.64 knowledgebase) include_directories( ${PROJECT_SOURCE_DIR}/include ${GIO_INCLUDE_DIRS}) file(GLOB SOURCE_LIST ${PROJECT_SOURCE_DIR}/src/*.cpp) add_library(kyai-knowledgebase-client SHARED ${SOURCE_LIST} ${RETURNED_GDBUS_GLUE_FILES}) set_target_properties(kyai-knowledgebase-client PROPERTIES VERSION 1.0.0 SOVERSION 1) target_link_libraries(kyai-knowledgebase-client PRIVATE PkgConfig::GIO PRIVATE nlohmann_json::nlohmann_json ) if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9) target_link_libraries(kyai-knowledgebase-client PRIVATE stdc++fs) endif() endif() install(TARGETS kyai-knowledgebase-client LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) install(DIRECTORY include/ DESTINATION include) install(FILES pkgconf/kyai-knowledgebase-client.pc DESTINATION /usr/share/pkgconfig)kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/000077500000000000000000000000001520600016100243415ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/kylin-ai/000077500000000000000000000000001520600016100260565ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/kylin-ai/business/000077500000000000000000000000001520600016100277115ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/kylin-ai/business/knowledge-base/000077500000000000000000000000001520600016100326005ustar00rootroot00000000000000common.h000066400000000000000000000024521520600016100341650ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/kylin-ai/business/knowledge-base/* * 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 namespace knowledgebase { typedef enum : int { KNOWLEDGEBASE_SUCCESS = 0, KNOWLEDGEBASE_CONNECTION_ERROR, KNOWLEDGEBASE_PARSE_PARAM_FAILED, KNOWLEDGEBASE_EMBEDDING_FAILED, KNOWLEDGEBASE_CHUNK_FAILED, KNOWLEDGEBASE_DOCUMENT_EXCEEDS_LIMIT, KNOWLEDGEBASE_SEARCH_FILE_INFO_FAILED, KNOWLEDGEBASE_VECTOR_DATABASE_FAILED, KNOWLEDGEBASE_VECTOR_DATABASE_DATA_UNAVAILABLE, KNOWLEDGEBASE_ERROR_UNKNOWN = 99, } KnowledgebaseErrorCode; struct Status { bool success; KnowledgebaseErrorCode errorCode; std::string errorMsg; }; } // namespace knowledgebaseknowledgebase.h000066400000000000000000000076321520600016100355140ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/include/kylin-ai/business/knowledge-base/* * 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 namespace knowledgebase { class KnowledgebaseSession { public: KnowledgebaseSession(); ~KnowledgebaseSession(); /*! * \brief 判断知识库是否支持 * \param success [out] 出参,返回架构是否支持的标记位 * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status isSupported(bool& success) const; /*! * \brief 创建知识库 * \param knowledgebaseName [out] 出参,返回知识库名称 * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status createKnowledgebase(std::string& knowledgebaseName); /*! * \brief 删除知识库 * \param knowledgebaseName [in] 入参 * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status deleteKnowledgebase(const std::string& knowledgebaseName); /*! * \brief 相似搜索 * \param searchCondition [in] search conditional,字符串为json格式 * { * "knowledgebase_name": "name", * "search_condition": "linux内核安全选项" * } * \param searchResult [out] searchResult,字符串为json格式 * [ * { * "document": "xxxxxxx", * "filepath": "/path/to/file1.txt", * "similarity": 0.92 * }, * { * "document": "xxxxxxx", * "filepath": "/path/to/file2.txt", * "similarity": 0.88 * } * ] * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status similaritySearch(const std::string& searchCondition, std::string& searchResult); /*! * \brief 添加文件到知识库 * \param fileinfos [in] fileinfos 添加文件到知识库的信息,字符串为json格式 * [ * { * "knowledgebase_name": "name", * "filepath": "/path/to/file1.txt" * }, * { * "knowledgebase_name": "name", * "filepath": "/path/to/file2.txt" * } * ] * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status addTextFiles(const std::string& fileinfos); /*! * \brief 获得文件的内容 * \param filepaths [in] filepaths 文件路径,字符串为json格式 * [ * { * "filepath": "/path/to/file1.txt" * }, * { * "filepath": "/path/to/file2.txt" * } * ] * \param fileContent[out] 出参 fileContent 获得文件内容信息,字符串为json格式 * [ * { * "filepath": "/path/to/file1.txt", * "content": "file content" * }, * { * "filepath": "/path/to/file2.txt", * "content": "file content" * } * ] * \return 成功 Status::success 为 true,失败则会返回对应错误码 */ Status getTextFileContents(const std::string& input, std::string& result); private: struct KnowledgebaseImlp; std::unique_ptr impl_; }; } // namespace knowledgebasekylin-ai-document-qa-service-1.2.0.0/document-qa-client/pkgconf/000077500000000000000000000000001520600016100243455ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/pkgconf/kyai-knowledgebase-client.pc000066400000000000000000000002331520600016100317100ustar00rootroot00000000000000Name: kyai-knowledgebase-client Description: Kylin ai knowledgebase client Version: 1.0.0 Libs: -lkyai-knowledgebase-client Cflags: -I/usr/include/kylin-aikylin-ai-document-qa-service-1.2.0.0/document-qa-client/src/000077500000000000000000000000001520600016100235055ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-client/src/knowledgebaseproxy.cpp000066400000000000000000000315561520600016100301370ustar00rootroot00000000000000/* * 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 "knowledgebaseproxy.h" #include #include #include #include #include #include #include namespace { std::string serverUnixPath = "unix:abstract=/tmp/.kylin-ai-business-unix/" + std::to_string(getuid()) + "/Knowledgebase.sock"; const std::string objectPath = "/com/kylin/AiBusiness/Knowledgebase"; const int CALL_KNOWLEDGEBASE_RETRY_TIME = 3; } // namespace namespace knowledgebase { // 下面为服务端错误码汇总 禁止修改 enum ERROR_CODE : int { // 0 - 100 公共错误码 SYSTEM_ERR = -1, SUCCESS = 0, ASYNC_FLOW_END = 1, PARSE_CONFIG_FILE_FAIL = 11, INVALID_CONFIG = 12, INIT_DBUS_SERVER_FAIL = 13, PARSE_PARAM_FAILED = 14, PARSE_RESPONSE_FAILED = 15, CHUNK_FILE_INFO_FAILED = 50, EMBEDDING_FAILED = 51, INSERT_FILE_INFO_SQLITE_FAILED = 52, DELETE_FILE_INFO_SQLITE_FAILED = 53, UPDATE_FILE_INFO_SQLITE_FAILED = 54, CREATE_VECTOR_DATABASE_FAILED = 55, INSERT_VECTOR_DATABASE_FAILED = 56, DELETE_VECTOR_DATABASE_FAILED = 57, UPDATE_VECTOR_DATABASE_FAILED = 58, SEARCH_FILE_INFO_FAILED = 59, NLP_FAILED = 60, // 100 - 199 搜索场景和数据管家场景业务错误码 DM_ERROR_UNKNOWN = 100, // 未知错误 DM_SESSION_ERROR = 101, // 会话错误 DM_ERROR_INVALID_INPUT = 102, // 无效输入 DM_ERROR_PERMISSION_DENIED = 103, // 权限被拒绝 // 200 - 299 文档问答错误码 TEXT_CHUNKS_UNSUPPORT = 200, // 300 - 399 向量数据库错误码 VECTOR_DATABASE_DATA_UNAVAILABLE = 300, // 400 - 1000 xxx ERROR_MAX = 10000, }; // 服务端 -> 客户端 错误码映射表 const std::unordered_map ServerToClientErrorMap = { // 公共错误码 {0, KNOWLEDGEBASE_SUCCESS}, {14, KNOWLEDGEBASE_PARSE_PARAM_FAILED}, // 文件处理错误码 {50, KNOWLEDGEBASE_CHUNK_FAILED}, {51, KNOWLEDGEBASE_EMBEDDING_FAILED}, {200, KNOWLEDGEBASE_DOCUMENT_EXCEEDS_LIMIT}, // 向量数据库错误码 {55, KNOWLEDGEBASE_VECTOR_DATABASE_FAILED}, {56, KNOWLEDGEBASE_VECTOR_DATABASE_FAILED}, {57, KNOWLEDGEBASE_VECTOR_DATABASE_FAILED}, {300, KNOWLEDGEBASE_VECTOR_DATABASE_DATA_UNAVAILABLE}, // 搜索错误码 {59, KNOWLEDGEBASE_SEARCH_FILE_INFO_FAILED}, }; Status InitializeStatus(bool success, int errorCode, const std::string& errorMsg) { return Status{success, KnowledgebaseErrorCode(errorCode), errorMsg}; } std::string createResponse(const std::string& outputData, int errorCode, const std::string& errorMsg) { nlohmann::json root; root["err_no"] = errorCode; root["err_msg"] = errorMsg; root["data"] = outputData; return root.dump(); } Status handleJsonData(int serverErrorCode, std::string& serverErrorMsg, const nlohmann::json& jsonValue, nlohmann::json& outputData) { bool hasData = jsonValue.contains("data") && !jsonValue["data"].is_null(); KnowledgebaseErrorCode clientErrorCode; auto it = ServerToClientErrorMap.find(serverErrorCode); if (it != ServerToClientErrorMap.end()) { clientErrorCode = it->second; } else { clientErrorCode = KnowledgebaseErrorCode::KNOWLEDGEBASE_ERROR_UNKNOWN; serverErrorMsg += " knowledgebase error unknown"; } if (hasData) { outputData = jsonValue["data"]; } return (clientErrorCode == KnowledgebaseErrorCode::KNOWLEDGEBASE_SUCCESS) ? STATUS_SUCCESS : STATUS_FAILURE(clientErrorCode, serverErrorMsg); } Status parseResponse(const std::string& response, nlohmann::json& outputData) { nlohmann::json jsonValue = nlohmann::json::parse(response, nullptr, false); std::string msg = "Parse response error: " + response; if (jsonValue.is_discarded()) { return STATUS_FAILURE(KnowledgebaseErrorCode::KNOWLEDGEBASE_ERROR_UNKNOWN, msg); } bool hasError = jsonValue.contains("err_no") && jsonValue["err_no"].is_number_integer(); bool hasErrorMsg = jsonValue.contains("err_msg") && jsonValue["err_msg"].is_string(); if (!hasError || !hasErrorMsg) { return STATUS_FAILURE(KnowledgebaseErrorCode::KNOWLEDGEBASE_ERROR_UNKNOWN, msg); } int serverErrorCode = jsonValue["err_no"].get(); std::string serverErrorMsg = jsonValue["err_msg"].get(); // 如果是连接错误 json中是没有data的,所以这里直接返回错误 if (serverErrorCode == KnowledgebaseErrorCode::KNOWLEDGEBASE_CONNECTION_ERROR) { return STATUS_FAILURE(serverErrorCode, serverErrorMsg); } return handleJsonData(serverErrorCode, serverErrorMsg, jsonValue, outputData); } Status parseResponse(const std::string& response, std::string& outputData, const std::string& key) { nlohmann::json result; Status ret = parseResponse(response, result); if (!ret.success) { return ret; } if (!result.contains(key)) { return STATUS_FAILURE(KnowledgebaseErrorCode::KNOWLEDGEBASE_ERROR_UNKNOWN, "parse response failed"); } outputData = result[key].get(); return STATUS_SUCCESS; } Status parseResponse(const std::string& response) { nlohmann::json v; return parseResponse(response, v); } std::string KnowledgebaseProxy::handleGError(GError* gError, const std::string& fallbackMsg, KnowledgebaseErrorCode errorCode) { std::string errorMsg = fallbackMsg; // 存在失败 但是error为空的情况 if (gError) { errorMsg = gError->message; g_error_free(gError); gError = nullptr; } return createResponse(std::string(), errorCode, errorMsg); } Status KnowledgebaseProxy::handleDBusError(GError* gError, const std::string& contextMsg, KnowledgebaseErrorCode errorCode) { std::string fullErrorMsg = contextMsg; if (gError) { fullErrorMsg += " (GDBus Error: " + std::string(gError->message) + ")"; g_printerr("%s\n", fullErrorMsg.c_str()); // 集中日志记录 g_error_free(gError); } else { fullErrorMsg += " (Unknown error)"; g_printerr("%s\n", fullErrorMsg.c_str()); } return STATUS_FAILURE(errorCode, fullErrorMsg); } std::string KnowledgebaseProxy::syncFuncCall(const std::string& input, gint timeout_msec, AiBusinessKnowledgeBaseCallSyncFunc 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_KNOWLEDGEBASE_RETRY_TIME) { if (retryTime == CALL_KNOWLEDGEBASE_RETRY_TIME) { return handleGError(gError, "Unknown error (GError not set)", KnowledgebaseErrorCode::KNOWLEDGEBASE_CONNECTION_ERROR); } if (gError) { // 测试过程中有发现过失败但error为空的情况 std::fprintf(stdout, "WARN: call knowledgebase server failed, code: %d, msg: %s, retry: %d\n", gError->code, gError->message, retryTime); g_error_free(gError); gError = nullptr; } else { std::fprintf(stdout, "WARN: call knowledgebase server failed, retry: %d\n", retryTime); } // 断开连接 destroy(); sleep(2); retryTime++; // 重连 if (!connect().success) { 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; g_free(output); } return response; } KnowledgebaseProxy::KnowledgebaseProxy() { connect(); } KnowledgebaseProxy::~KnowledgebaseProxy() { destroy(); } void KnowledgebaseProxy::destroy() { if (delegate_ != nullptr) { g_object_unref(delegate_); delegate_ = nullptr; } if (connection_ != nullptr) { g_object_unref(connection_); connection_ = nullptr; } getConnection_ = false; } Status KnowledgebaseProxy::isSupported(bool& success) const { std::array buffer; std::string result; std::unique_ptr pipe(popen("uname -m", "r"), pclose); if (!pipe) { std::cerr << "popen failed!" << std::endl; success = false; return STATUS_SUCCESS; } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } // 移除可能存在的换行符 if (!result.empty() && (result.back() == '\n' || result.back() == '\r')) { result.pop_back(); if (!result.empty() && result.back() == '\r') { result.pop_back(); } } if (result != "x86_64" && result != "aarch64") { std::cerr << "unsupported architecture: " << result << std::endl; success = false; return STATUS_SUCCESS; } std::cout << "current architecture: " << result << std::endl; success = true; return STATUS_SUCCESS; } Status KnowledgebaseProxy::connect() { GError* error = nullptr; connection_ = g_dbus_connection_new_for_address_sync( serverUnixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, nullptr, &error); if (!connection_) { getConnection_ = false; return handleDBusError(error, "Failed to connect to D-Bus address: " + serverUnixPath, KnowledgebaseErrorCode::KNOWLEDGEBASE_CONNECTION_ERROR); } delegate_ = ai_business_knowledgebase_proxy_new_sync(connection_, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath.c_str(), nullptr, &error); if (!delegate_) { if (connection_) { // 防止delegate_失败了 但是connection_成功了 g_object_unref(connection_); connection_ = nullptr; } getConnection_ = false; return handleDBusError(error, "Failed to create proxy for object path: " + objectPath, KnowledgebaseErrorCode::KNOWLEDGEBASE_CONNECTION_ERROR); } getConnection_ = true; return STATUS_SUCCESS; } Status KnowledgebaseProxy::createKnowledgebase(std::string& knowledgebaseName) { if (!getConnection_) { Status ret = connect(); if (!ret.success) return ret; } const std::string emptyInput = "{}"; const std::string res = syncFuncCall(emptyInput, -1, ai_business_knowledgebase_call_create_knowledge_base_sync); return parseResponse(res, knowledgebaseName, "knowledgebase_name"); } Status KnowledgebaseProxy::deleteKnowledgebase(const std::string& knowledgebaseName) { if (!getConnection_) { Status ret = connect(); if (!ret.success) return ret; } nlohmann::json inputJson; inputJson["knowledgebase_name"] = knowledgebaseName; const std::string input = inputJson.dump(); const std::string res = syncFuncCall(input, -1, ai_business_knowledgebase_call_delete_knowledge_base_sync); return parseResponse(res); } Status KnowledgebaseProxy::similaritySearch(const std::string& searchCondition, std::string& result) { if (!getConnection_) { Status ret = connect(); if (!ret.success) return ret; } const std::string res = syncFuncCall(searchCondition, -1, ai_business_knowledgebase_call_similarity_search_sync); return parseResponse(res, result, "search_result"); } Status KnowledgebaseProxy::addTextFiles(const std::string& input) { if (!getConnection_) { Status ret = connect(); if (!ret.success) return ret; } const std::string res = syncFuncCall(input, 600000, ai_business_knowledgebase_call_add_text_files_sync); return parseResponse(res); } Status KnowledgebaseProxy::getTextFileContents(const std::string& input, std::string& result) { if (!getConnection_) { Status ret = connect(); if (!ret.success) return ret; } const std::string res = syncFuncCall(input, 600000, ai_business_knowledgebase_call_get_text_file_contents_sync); return parseResponse(res, result, "file_content"); } } // namespace knowledgebasekylin-ai-document-qa-service-1.2.0.0/document-qa-client/src/knowledgebaseproxy.h000066400000000000000000000051051520600016100275730ustar00rootroot00000000000000/* * 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 #include #include "knowledgebaseglue.h" namespace knowledgebase { typedef gboolean (*AiBusinessKnowledgeBaseCallSyncFunc)(AiBusinessKnowledgebase* proxy, const gchar* arg_input, GDBusCallFlags call_flags, gint timeout_msec, gchar** out_output, GCancellable* cancellable, GError** error); #define STATUS_SUCCESS InitializeStatus(true, 0, "success") #define STATUS_FAILURE(errorCode, errorMsg) InitializeStatus(false, errorCode, errorMsg) Status InitializeStatus(bool success, int errorCode, const std::string& errorMsg); extern const std::unordered_map ServerToClientErrorMap; class KnowledgebaseProxy { public: KnowledgebaseProxy(); ~KnowledgebaseProxy(); Status isSupported(bool& success) const; Status createKnowledgebase(std::string& knowledgebaseName); Status deleteKnowledgebase(const std::string& knowledgebaseName); Status similaritySearch(const std::string& searchCondition, std::string& result); Status addTextFiles(const std::string& input); Status getTextFileContents(const std::string& input, std::string& result); private: Status connect(); void destroy(); std::string syncFuncCall(const std::string& input, gint timeout_msec, AiBusinessKnowledgeBaseCallSyncFunc func); std::string handleGError(GError* gError, const std::string& fallbackMsg, KnowledgebaseErrorCode errorCode); Status handleDBusError(GError* gError, const std::string& contextMsg, KnowledgebaseErrorCode errorCode); private: bool getConnection_ = false; GDBusConnection* connection_ = nullptr; AiBusinessKnowledgebase* delegate_ = nullptr; }; } // namespace knowledgebasekylin-ai-document-qa-service-1.2.0.0/document-qa-client/src/knowlegdebase.cpp000066400000000000000000000040061520600016100270230ustar00rootroot00000000000000/* * 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 "knowledgebaseproxy.h" #include "kylin-ai/business/knowledge-base/knowledgebase.h" namespace knowledgebase { struct KnowledgebaseSession::KnowledgebaseImlp { KnowledgebaseProxy* proxy; KnowledgebaseImlp() : proxy(new KnowledgebaseProxy()) {} ~KnowledgebaseImlp() { delete proxy; } }; KnowledgebaseSession::KnowledgebaseSession() : impl_(std::make_unique()) {} KnowledgebaseSession::~KnowledgebaseSession() = default; Status KnowledgebaseSession::isSupported(bool& success) const { return impl_->proxy->isSupported(success); } Status KnowledgebaseSession::createKnowledgebase(std::string& knowledgebaseName) { return impl_->proxy->createKnowledgebase(knowledgebaseName); } Status KnowledgebaseSession::deleteKnowledgebase(const std::string& knowledgebaseName) { return impl_->proxy->deleteKnowledgebase(knowledgebaseName); } Status KnowledgebaseSession::similaritySearch(const std::string& searchCondition, std::string& result) { return impl_->proxy->similaritySearch(searchCondition, result); } Status KnowledgebaseSession::addTextFiles(const std::string& input) { return impl_->proxy->addTextFiles(input); } Status KnowledgebaseSession::getTextFileContents(const std::string& input, std::string& result) { return impl_->proxy->getTextFileContents(input, result); } } // namespace knowledgebasekylin-ai-document-qa-service-1.2.0.0/document-qa-service/000077500000000000000000000000001520600016100231005ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-service/CMakeLists.txt000066400000000000000000000026111520600016100256400ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kylin-ai-document-qa-service LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) file(GLOB_RECURSE SOURCE_LIST ${PROJECT_SOURCE_DIR}/src/*.cpp server.cpp) find_package(PkgConfig REQUIRED) find_package(nlohmann_json REQUIRED) pkg_check_modules(KYDOCUMENT REQUIRED IMPORTED_TARGET kylin-ai-document-service) pkg_check_modules(BUSINESS REQUIRED IMPORTED_TARGET kyai-business-framework) pkg_check_modules(VECTOR_DB REQUIRED IMPORTED_TARGET kysdk-vector-engine-client) include_directories(${PROJECT_SOURCE_DIR}/src ${PROJECT_SOURCE_DIR}/src/service ${PROJECT_SOURCE_DIR}/src/dao) add_executable(kylin-ai-document-qa-service ${SOURCE_LIST}) target_link_libraries(kylin-ai-document-qa-service PUBLIC PkgConfig::BUSINESS PUBLIC PkgConfig::KYDOCUMENT PUBLIC nlohmann_json::nlohmann_json PUBLIC PkgConfig::VECTOR_DB ) if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9) target_link_libraries(kylin-ai-document-qa-service PRIVATE stdc++fs) endif() endif() install(FILES conf/KnowledgeBase.json DESTINATION /usr/share/kylin-ai/kyai-business-framework) install(FILES conf/kylin-ai-document-qa-service.service DESTINATION /usr/lib/systemd/user) install(TARGETS kylin-ai-document-qa-service RUNTIME DESTINATION /usr/bin)kylin-ai-document-qa-service-1.2.0.0/document-qa-service/conf/000077500000000000000000000000001520600016100240255ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-service/conf/KnowledgeBase.json000066400000000000000000000001611520600016100274300ustar00rootroot00000000000000{ "service_name": "Knowledgebase", "log_level": 4, "support_chunk_count": 30, "document_chunk_size":800 }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/conf/kylin-ai-document-qa-service.service000066400000000000000000000003571520600016100330020ustar00rootroot00000000000000[Unit] Description=Kylin Ai Document QA Service After=login@.service [Service] ExecStart=/usr/bin/kylin-ai-document-qa-service -s KnowledgeBase Restart=always StandardOutput=journal StandardError=journal [Install] WantedBy=default.targetkylin-ai-document-qa-service-1.2.0.0/document-qa-service/server.cpp000066400000000000000000000015161520600016100251150ustar00rootroot00000000000000/* * 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 int main(int argc, char *argv[]) { scene::Application::getInstance().exec(argc, argv); return 0; }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/000077500000000000000000000000001520600016100236675ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/000077500000000000000000000000001520600016100244325ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/database.cpp000066400000000000000000000223311520600016100267030ustar00rootroot00000000000000/* * 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 "database.h" #include #include using namespace VectorDB; const int TEXT_DIMENSION = 768; static const char* DATABASE_FILE_PATH = "filepath"; static const char* DATABASE_DOCUMENT = "document"; static const char* DATABASE_VECTOR = "vector"; static const char* DATABASE_ID = "ids"; KnowledgebaseVectorDatabase::KnowledgebaseVectorDatabase() : isConnected(false), client_(Database::Create()) {} VectorDatabaseErrorCode KnowledgebaseVectorDatabase::connect() { if (isConnected) return VectorDatabaseErrorCode(true); auto status = client_->Connect(); if (!status.IsOk()) { PRINT_ERROR("Failed to connect vector db,code: %d, message: %s\n", static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } isConnected = true; return VectorDatabaseErrorCode(true); } VectorDatabaseErrorCode KnowledgebaseVectorDatabase::disconnect() { if (!isConnected) return VectorDatabaseErrorCode(true); auto status = client_->Disconnect(); if (!status.IsOk()) { PRINT_ERROR("Failed to disconnect vector db,code: %d, message: %s\n", static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } isConnected = false; return VectorDatabaseErrorCode(true); } VectorDatabaseErrorCode KnowledgebaseVectorDatabase::createCollection(std::string& collectionName) { VectorDatabaseErrorCode errorCode = connect(); if (!errorCode.success) return errorCode; std::string knowledgeBaseName = Utils::generateUUID(); std::replace(knowledgeBaseName.begin(), knowledgeBaseName.end(), '-', '_'); collectionName = "_" + knowledgeBaseName; VectorDB::CollectionSchema collection_schema(collectionName); collection_schema.AddField(FieldSchema(DATABASE_FILE_PATH, DataType::VARCHAR, "file path").WithMaxLength(100)); collection_schema.AddField( FieldSchema(DATABASE_DOCUMENT, DataType::VARCHAR, "document contents").WithMaxLength(1024)); collection_schema.AddField(FieldSchema(DATABASE_ID, DataType::VARCHAR, "ids", true, false).WithMaxLength(40)); collection_schema.AddField( FieldSchema(DATABASE_VECTOR, DataType::FLOAT_VECTOR, "vectors").WithDimension(TEXT_DIMENSION)); IndexDesc index_desc(DATABASE_VECTOR, "vector-index", 0); // 先判断是否存在该collection 不存在在创建 bool exist; auto status = client_->HasCollection(collectionName, exist); if (!status.IsOk()) { PRINT_ERROR("Failed to check collection %s,code: %d, message: %s\n", collectionName.c_str(), static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } if (exist) return VectorDatabaseErrorCode(true); status = client_->CreateCollection(collection_schema, index_desc); if (!status.IsOk()) { PRINT_ERROR("Failed to create collection %s,code: %d, message: %s\n", collectionName.c_str(), static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } return VectorDatabaseErrorCode(true); } VectorDatabaseErrorCode KnowledgebaseVectorDatabase::deleteCollection(const std::string& collectionName) { VectorDatabaseErrorCode errorCode = connect(); if (!errorCode.success) return errorCode; bool exist; auto status = client_->HasCollection(collectionName, exist); if (!status.IsOk()) { PRINT_ERROR("Failed to check collection %s,code: %d, message: %s\n", collectionName.c_str(), static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } if (!exist) return VectorDatabaseErrorCode(true); status = client_->DropCollection(collectionName); if (!status.IsOk()) { PRINT_ERROR("Failed to delete collection %s,code: %d, message: %s\n", collectionName.c_str(), static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } return VectorDatabaseErrorCode(true); } VectorDatabaseErrorCode KnowledgebaseVectorDatabase::insertVectorData( const std::vector& vectorInfos) { VectorDatabaseErrorCode errorCode = connect(); if (!errorCode.success) return errorCode; for (const KnowledgeFileInfo& vectorInfo : vectorInfos) { std::vector ids; std::vector filepaths; std::vector> embeddings = vectorInfo.vectors; std::vector documents = vectorInfo.documents; for (int i = 0; i < embeddings.size(); i++) { ids.emplace_back(Utils::generateUUID()); filepaths.emplace_back(vectorInfo.filepath); } std::vector fields_data{std::make_shared(DATABASE_ID, ids), std::make_shared(DATABASE_FILE_PATH, filepaths), std::make_shared(DATABASE_DOCUMENT, documents), std::make_shared(DATABASE_VECTOR, embeddings)}; DmlResults dml_results; auto status = client_->Insert(vectorInfo.knowledgeBaseName, fields_data, dml_results); if (!status.IsOk()) { PRINT_ERROR("Failed to insert,code: %d, message: %s\n", static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } PRINT_DEBUG("%s vector insert rows: %zu\n", vectorInfo.knowledgeBaseName.c_str(), dml_results.IdArray().StrIDArray().size()); } return VectorDatabaseErrorCode(true); } KnowledgebaseSearchResults KnowledgebaseVectorDatabase::transformSearchResults(SearchResults results) const { KnowledgebaseSearchResults output; for (const auto& result : results.Results()) { auto& ids = result.Ids().StrIDArray(); if (ids.empty()) { PRINT_WARN("KnowledgebaseVectorDatabase error: searchMetadata result is empty.\n"); continue; } auto similarity = result.Scores(); if (ids.size() != similarity.size()) { PRINT_WARN("KnowledgebaseVectorDatabase error: illegal search result.\n"); continue; } auto documentResult = result.OutputField(DATABASE_DOCUMENT); auto filepathResult = result.OutputField(DATABASE_FILE_PATH); VarCharFieldDataPtr documentResult_ptr = std::static_pointer_cast(documentResult); VarCharFieldDataPtr filepathResult_ptr = std::static_pointer_cast(filepathResult); auto documentResult_data = documentResult_ptr->Data(); auto filepathResult_data = filepathResult_ptr->Data(); for (int i = 0; i < ids.size(); i++) { output.emplace_back( KnowledgebaseSearchResult{documentResult_data[i], std::string(filepathResult_data[i]), similarity[i]}); } } return output; } VectorDatabaseErrorCode KnowledgebaseVectorDatabase::similaritySearch(const std::string& knowledgeBaseName, const std::vector& vector, KnowledgebaseSearchResults& searchResult) { VectorDatabaseErrorCode errorCode = connect(); if (!errorCode.success) return errorCode; SearchArguments arguments{}; arguments.SetCollectionName(knowledgeBaseName); arguments.SetTopK(10); arguments.AddOutputField(DATABASE_DOCUMENT); arguments.AddOutputField(DATABASE_FILE_PATH); arguments.SetGuaranteeTimestamp(GuaranteeStrongTs()); arguments.AddTargetVector(DATABASE_VECTOR, vector); SearchResults results{}; auto status = client_->Search(arguments, results); if (!status.IsOk()) { PRINT_ERROR("Failed to search,code: %d, message: %s\n", static_cast(status.Code()), status.Message().c_str()); return VectorDatabaseErrorCode(false, status.Code(), status.Message()); } searchResult = transformSearchResults(results); return VectorDatabaseErrorCode(true); } KnowledgebaseVectorDatabase::~KnowledgebaseVectorDatabase() { disconnect(); }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/database.h000066400000000000000000000045261520600016100263560ustar00rootroot00000000000000/* * 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 struct KnowledgebaseSearchResult { std::string documents; std::string source; double similarity; }; using KnowledgebaseSearchResults = std::vector; struct KnowledgeFileInfo { std::string filepath; std::vector> vectors; std::vector documents; std::string knowledgeBaseName; }; struct InputParameters { std::string filepath; std::string knowledgeBaseName; }; struct VectorDatabaseErrorCode { VectorDatabaseErrorCode(bool success, VectorDB::StatusCode code = VectorDB::StatusCode::OK, std::string message = "Success") : success(success), code(code), message(message) {} bool success; VectorDB::StatusCode code; std::string message; }; class KnowledgebaseVectorDatabase { public: KnowledgebaseVectorDatabase(); VectorDatabaseErrorCode createCollection(std::string& collectionName); VectorDatabaseErrorCode deleteCollection(const std::string& collectionName); VectorDatabaseErrorCode insertVectorData(const std::vector& vectorInfos); VectorDatabaseErrorCode similaritySearch(const std::string& knowledgeBaseName, const std::vector& vector, KnowledgebaseSearchResults& searchResult); ~KnowledgebaseVectorDatabase(); private: KnowledgebaseSearchResults transformSearchResults(VectorDB::SearchResults results) const; VectorDatabaseErrorCode connect(); VectorDatabaseErrorCode disconnect(); private: std::shared_ptr client_; bool isConnected; };kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/embedding.cpp000066400000000000000000000040721520600016100270570ustar00rootroot00000000000000/* * 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 "embedding.h" #include #include #include Embedding::Embedding(scene::TaskPriority priority) : priority_(priority) { if (!scene::TextEmbeddingProcessor::getInstance().init()) { PRINT_ERROR("TextEmbeddingProcessor init failed\n"); inited_ = false; return; } inited_ = true; } std::vector Embedding::getTextEmbedding(const std::string& data) { if (!inited_) { PRINT_ERROR("EmbeddingProcessor not inited.\n"); return std::vector(); } if (data.empty()) { PRINT_ERROR("EmbeddingProcessor input data is empty.\n"); return std::vector(); } scene::TaskID taskID; std::vector ret; taskID = scene::TextEmbeddingProcessor::getInstance().addTask(data, scene::EmbeddingDataType::Text, priority_); ret = scene::TextEmbeddingProcessor::getInstance().getResult(taskID); if (ret.empty()) { PRINT_ERROR("Embedding result is empty, data: %s.\n", data.c_str()); } return ret; } std::vector> Embedding::getTextEmbeddings(const std::vector& texts) { std::vector> output; for (const auto& text : texts) { std::vector res = getTextEmbedding(text); output.push_back(res); } return output; }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/embedding.h000066400000000000000000000021701520600016100265210ustar00rootroot00000000000000/* * 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 class Embedding { public: Embedding(scene::TaskPriority priority = scene::TaskPriority::MEDIUM); std::vector getTextEmbedding(const std::string& data); std::vector> getTextEmbeddings(const std::vector& texts); ~Embedding() = default; private: scene::TaskPriority priority_; bool inited_; }; kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/parser.cpp000066400000000000000000000065331520600016100264410ustar00rootroot00000000000000/* * 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 "parser.h" #include #include #include #include #include "constant.h" const char* DOCUMENT_CHUNK_TEXT_TYPE = "TextChunker"; const char* DOCUMENT_RESPONSE_DATA = "responseData"; const char* CHUNKS = "chunks"; const char* FILEPATH = "filePath"; const char* DOCUMENT_CHUNK_SIZE = "document_chunk_size"; Parser::Parser() { client_ = std::make_shared(); if (client_ == nullptr) { PRINT_ERROR("Parser error: failed to create DocumentClient instance.\n"); } } std::vector Parser::chunkFiles(const std::vector& filePaths) { nlohmann::json ret = syncChunkDocument(filePaths); if (ret.empty()) { PRINT_ERROR("Parser error: chunk document server something wrong.\n"); return std::vector(); } return parseChunkResult(ret); } std::vector Parser::parseChunkResult(nlohmann::json& data) { std::vector res; // 解析分块结果 for (const auto& item : data) { ChunkResult chunkResult; std::string file_path = item["filePath"]; chunkResult.filePath = file_path; std::vector chunks; for (const auto& chunk : item["chunks"]) { chunks.push_back(chunk); } chunkResult.chunk = chunks; res.push_back(chunkResult); } return res; } nlohmann::json Parser::syncChunkDocument(const std::vector& filePaths) { std::vector chunkTypes(filePaths.size(), DOCUMENT_CHUNK_TEXT_TYPE); std::vector chunkSizes(filePaths.size(), Configuration::getInt(DOCUMENT_CHUNK_SIZE)); auto result = client_->SyncChunkDocument(filePaths, chunkTypes, chunkSizes); // grpc 通信异常 if (result.errorCode != 0) { PRINT_ERROR("DocumentClient connect failed, err: %d, msg: %s.\n", result.errorCode, result.errorMsg.c_str()); return nlohmann::json::array(); } nlohmann::json root = nlohmann::json::parse(result.data); if (root.empty() || !root.contains(DOCUMENT_RESPONSE_DATA) || !root[DOCUMENT_RESPONSE_DATA].is_array() || root[DOCUMENT_RESPONSE_DATA].empty()) { PRINT_ERROR("Failed to parse DocumentClient result: %s\n", result.data.c_str()); return nlohmann::json::array(); } nlohmann::json& data = root[DOCUMENT_RESPONSE_DATA]; // 过滤掉 没有 filePath 或 chunks 的结果 data.erase(std::remove_if( data.begin(), data.end(), [](const nlohmann::json& value) { return !value.contains(FILEPATH) || !value.contains(CHUNKS); }), data.end()); return data; }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/dao/parser.h000066400000000000000000000023551520600016100261040ustar00rootroot00000000000000/* * 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 struct ChunkResult { std::string filePath; std::vector chunk; }; class Parser { public: Parser(); std::vector chunkFiles(const std::vector& filePaths); ~Parser() = default; private: nlohmann::json syncChunkDocument(const std::vector& filePaths); std::vector parseChunkResult(nlohmann::json& data); private: std::shared_ptr client_; }; kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/handleAddTextFile.cpp000066400000000000000000000040531520600016100277060ustar00rootroot00000000000000/* * 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 #include "database.h" #include "service.h" Response handleAddTextFile(const Request& request) { PRINT_DEBUG("handleAddTextFile request: %s\n", request.toString().c_str()); nlohmann::json values = request.getValues(); if (!values.is_array() || values.empty()) { PRINT_ERROR("handleAddTextFile request is not array or is empty.\n"); return Response(PARSE_PARAM_FAILED); } std::vector inputParameters; for (const auto& item : values) { if (!item.is_object() || !item.contains("filepath") || !item["filepath"].is_string() || !item.contains("knowledgebase_name") || !item["knowledgebase_name"].is_string()) { PRINT_ERROR("HandleAddTextFiles request json is error.\n"); continue; } inputParameters.emplace_back( InputParameters{item["filepath"].get(), item["knowledgebase_name"].get()}); } KnowledgebaseService service; ERROR_CODE status; for (const auto& input : inputParameters) { status = service.addTexts(input.knowledgeBaseName, {input.filepath}); if (status != SUCCESS) { PRINT_ERROR("HandleAddTextFiles addTexts error.\n"); return Response(status); } } return Response::success(); } REGISTER_SERVICE_HANDLER("addTextFiles", handleAddTextFile) kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/handleCreateKnowledgeBase.cpp000066400000000000000000000032231520600016100314050ustar00rootroot00000000000000/* * 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 #include "database.h" Response handleCreateKnowledgeBase(const Request& request) { PRINT_DEBUG("handleCreateKnowledgeBase request: %s\n", request.toString().c_str()); std::string collectionName; KnowledgebaseVectorDatabase database; auto status = database.createCollection(collectionName); if (!status.success) { if (status.code == VectorDB::StatusCode::DATABASE_INIT_FAILED) { PRINT_ERROR("handleCreateKnowledgeBase failed: Database init error - %s\n", status.message.c_str()); return Response(VECTOR_DATABASE_DATA_UNAVAILABLE); } PRINT_ERROR("handleCreateKnowledgeBase failed: Unknown database create error - %s\n", status.message.c_str()); return Response(CREATE_VECTOR_DATABASE_FAILED); } Response output = Response::success(); output.add("knowledgebase_name", collectionName); return output; } REGISTER_SERVICE_HANDLER("createKnowledgeBase", handleCreateKnowledgeBase)kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/handleDeleteKnowledgeBase.cpp000066400000000000000000000035271520600016100314130ustar00rootroot00000000000000/* * 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 #include "database.h" Response handleDeleteKnowledgeBase(const Request& request) { PRINT_DEBUG("handleDeleteKnowledgeBase request: %s\n", request.toString().c_str()); nlohmann::json values = request.getValues(); if (values.empty() || !values.contains("knowledgebase_name")) { PRINT_ERROR("handleDeleteKnowledgeBase request param error.\n"); return Response(PARSE_PARAM_FAILED); } std::string knowledgeBaseName = values["knowledgebase_name"]; KnowledgebaseVectorDatabase database; auto status = database.deleteCollection(knowledgeBaseName); if (!status.success) { if (status.code == VectorDB::StatusCode::DATABASE_INIT_FAILED) { PRINT_ERROR("handleDeleteKnowledgeBase failed: Database init error - %s\n", status.message.c_str()); return Response(VECTOR_DATABASE_DATA_UNAVAILABLE); } PRINT_ERROR("handleDeleteKnowledgeBase failed: Unknown database delete error - %s\n", status.message.c_str()); return Response(DELETE_VECTOR_DATABASE_FAILED); } return Response::success(); } REGISTER_SERVICE_HANDLER("deleteKnowledgeBase", handleDeleteKnowledgeBase)kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/handleGetTextFileContents.cpp000066400000000000000000000036201520600016100314520ustar00rootroot00000000000000/* * 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 #include "service.h" Response handleGetTextFileContents(const Request& request) { PRINT_DEBUG("handleGetTextFileContents request: %s\n", request.toString().c_str()); nlohmann::json values = request.getValues(); if (!values.is_array() || values.empty()) { PRINT_ERROR("handleGetTextFileContents request is not array or is empty.\n"); return Response(PARSE_PARAM_FAILED); } std::vector filepaths; for (const auto& item : values) { if (!item.is_object() || !item.contains("filepath") || !item["filepath"].is_string()) { PRINT_ERROR("handleGetTextFileContents request json is error.\n"); continue; } filepaths.emplace_back(item["filepath"].get()); } KnowledgebaseService service; std::string fileContent; ERROR_CODE status = service.getFileContent(filepaths, fileContent); if (status != SUCCESS) { PRINT_ERROR("handleGetTextFileContents getFileContent error.\n"); return Response(status); } Response ret = Response::success(); ret.add("file_content", fileContent); return ret; } REGISTER_SERVICE_HANDLER("getTextFileContents", handleGetTextFileContents)kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/handleSimilaritySearch.cpp000066400000000000000000000033311520600016100310230ustar00rootroot00000000000000/* * 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 #include "service.h" Response handleSimilaritySearch(const Request& request) { PRINT_DEBUG("handleSimilaritySearch request: %s\n", request.toString().c_str()); nlohmann::json values = request.getValues(); if (!values.is_object() || !values.contains("knowledgebase_name") || !values.contains("search_condition")) { PRINT_ERROR("handleSimilaritySearch request param error.\n"); return Response(PARSE_PARAM_FAILED); } std::string knowledgeBaseName = values["knowledgebase_name"]; std::string searchCondition = values["search_condition"]; std::string searchResult; KnowledgebaseService service; ERROR_CODE status = service.similaritySearch(knowledgeBaseName, searchCondition, searchResult); if (status != SUCCESS) { PRINT_ERROR("handleSimilaritySearch error.\n"); return Response(status); } Response ret = Response::success(); ret.add("search_result", searchResult); return ret; } REGISTER_SERVICE_HANDLER("similaritySearch", handleSimilaritySearch)kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/service/000077500000000000000000000000001520600016100253275ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/service/service.cpp000066400000000000000000000134261520600016100275010ustar00rootroot00000000000000/* * 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 "service.h" #include #include #include #include #include "database.h" #include "embedding.h" #include "parser.h" const char* SUPPORT_CHUNK_COUNT = "support_chunk_count"; ERROR_CODE KnowledgebaseService::addTexts(const std::string& collectionName, const std::string& filepath) { std::vector infos; // 分块 并获得向量化结果 Parser parser; std::vector chunkResult = parser.chunkFiles({filepath}); if (chunkResult.empty()) { PRINT_ERROR("KnowledgebaseService: document parse result is empty.\n"); return CHUNK_FILE_INFO_FAILED; } Embedding textEmbedding; for (const auto& item : chunkResult) { if (item.chunk.empty()) { PRINT_ERROR("KnowledgebaseService: filepath:%s chunk result is empty.\n", item.filePath.c_str()); return CHUNK_FILE_INFO_FAILED; } if (item.chunk.size() > Configuration::getInt(SUPPORT_CHUNK_COUNT)) { PRINT_ERROR("KnowledgebaseService: unsupport chunk counts %d.\n", item.chunk.size()); return TEXT_CHUNKS_UNSUPPORT; } std::vector> embeddingResult = textEmbedding.getTextEmbeddings(item.chunk); if (embeddingResult.empty()) { PRINT_ERROR("KnowledgebaseService: embedding result is empty.\n"); return EMBEDDING_FAILED; } KnowledgeFileInfo info{item.filePath, embeddingResult, item.chunk, collectionName}; infos.push_back(info); } // insert vector data KnowledgebaseVectorDatabase database; auto status = database.insertVectorData(infos); if (!status.success) { if (status.code == VectorDB::StatusCode::DATABASE_INIT_FAILED) { PRINT_ERROR("KnowledgebaseService:insert vector data failed, Database init error - %s\n", status.message.c_str()); return VECTOR_DATABASE_DATA_UNAVAILABLE; } PRINT_ERROR("KnowledgebaseService:insert vector data failed, Unknown database insert error - %s\n", status.message.c_str()); return INSERT_VECTOR_DATABASE_FAILED; } return SUCCESS; } ERROR_CODE KnowledgebaseService::getFileContent(const std::vector& filepaths, std::string& output) { // 分块 Parser parser; std::vector chunkResult = parser.chunkFiles(filepaths); if (chunkResult.empty()) { PRINT_ERROR("KnowledgebaseService: document parse result is empty.\n"); return CHUNK_FILE_INFO_FAILED; } // 拼接 std::unordered_map fileContentMap; for (const auto& item : chunkResult) { std::ostringstream contentBuilder; for (const auto& str : item.chunk) { contentBuilder << str; } fileContentMap[item.filePath] = contentBuilder.str(); } output = getFileContentJson(fileContentMap); return SUCCESS; } std::string KnowledgebaseService::getFileContentJson(std::unordered_map& fileContents) const { nlohmann::json root = nlohmann::json::array(); for (const auto& result : fileContents) { nlohmann::json item = {{"filepath", result.first}, {"document", result.second}}; root.push_back(item); } return root.dump(); } std::string KnowledgebaseService::getSearchResultJson(std::vector& searchResult) const { nlohmann::json root = nlohmann::json::array(); for (const auto& result : searchResult) { nlohmann::json item = { {"filepath", result.source}, {"document", result.documents}, {"similarity", result.similarity}}; root.push_back(item); } return root.dump(); } ERROR_CODE KnowledgebaseService::similaritySearch(const std::string& collectionName, const std::string& searchCondition, std::string& output) const { // 向量化 Embedding textEmbedding; std::vector res = textEmbedding.getTextEmbedding(searchCondition); if (res.empty()) { PRINT_ERROR("KnowledgebaseService: embedding result is empty.\n"); return EMBEDDING_FAILED; } // 搜索 KnowledgebaseVectorDatabase database; KnowledgebaseSearchResults searchResult; auto status = database.similaritySearch(collectionName, res, searchResult); if (!status.success) { if (status.code == VectorDB::StatusCode::DATABASE_INIT_FAILED) { PRINT_ERROR("KnowledgebaseService: similarity search failed,, Database init error - %s\n", status.message.c_str()); return VECTOR_DATABASE_DATA_UNAVAILABLE; } PRINT_ERROR("KnowledgebaseService: similarity search failed, Unknown database search error - %s\n", status.message.c_str()); return SEARCH_FILE_INFO_FAILED; } if (searchResult.empty()) { PRINT_ERROR("KnowledgebaseService: searchResult is empty.\n"); return SEARCH_FILE_INFO_FAILED; } // 处理成json output = getSearchResultJson(searchResult); return SUCCESS; }kylin-ai-document-qa-service-1.2.0.0/document-qa-service/src/service/service.h000066400000000000000000000026341520600016100271450ustar00rootroot00000000000000/* * 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 #include #include "database.h" class KnowledgebaseService { public: ERROR_CODE addTexts(const std::string& collectionName, const std::string& filepath); ERROR_CODE getFileContent(const std::vector& filepaths, std::string& output); ERROR_CODE similaritySearch(const std::string& collectionName, const std::string& searchCondition, std::string& output) const; private: std::string getFileContentJson(std::unordered_map& fileContents) const; std::string getSearchResultJson(std::vector& searchResult) const; };kylin-ai-document-qa-service-1.2.0.0/test/000077500000000000000000000000001520600016100202045ustar00rootroot00000000000000kylin-ai-document-qa-service-1.2.0.0/test/CMakeLists.txt000066400000000000000000000011401520600016100227400ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(test LANGUAGES CXX C) set(CMAKE_CXX_STANDARD 17) find_package(PkgConfig REQUIRED) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-unix-2.0) pkg_check_modules(KnowledgeBase REQUIRED IMPORTED_TARGET kyai-knowledgebase-client) # 单元测试 # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage") # set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage") add_executable(test main.cpp) target_link_libraries(test PUBLIC PkgConfig::KnowledgeBase PUBLIC PkgConfig::GIO PUBLIC kyai-business-framework )kylin-ai-document-qa-service-1.2.0.0/test/auto_test.sh000077500000000000000000000036341520600016100225600ustar00rootroot00000000000000#!/bin/bash # 设置退出脚本当命令失败时 (非零退出状态) #set -e # 函数:运行单元测试 run_unit_tests() { # local pattern="unit_test_*" # # # 遍历所有匹配模式的目录 # for dir in $pattern; do # if [ -d "$dir" ] && [ -x "$dir/$(basename "$dir")" ]; then # echo "Running tests in $dir and Collecting coverage data..." # # 收集代码覆盖率数据 # (cd "$dir" && "./$(basename "$dir")" && (find ./ -name '*.o' | xargs gcov --preserve-paths)) # else # echo "Skipping non-existent or non-executable directory: $dir, $dir/$(basename "$dir")" # fi # done local pattern="/home/wangyan/mypro/kylin-ai-document-qa-service/test/build/CMakeFiles" # 检查模式是否为有效的目录 if [ -d "$pattern" ]; then echo "Processing directory: $pattern" (cd "$pattern" && { # 查找并处理每个 .gcda 文件 find . -name "*.gcda" -exec gcov --preserve-paths {} + || echo "No .gcda files found or gcov failed." }) else echo "Directory does not exist: $pattern" fi #Print Working Directory echo "current pwd : $(pwd)" # 收集覆盖率信息 lcov -d . -c -o r.info # 删除不需要的文件或路径 lcov -r r.info "/usr/include/*" "build/*" -o coverage.info # 生成html覆盖率报告 genhtml "$(pwd)/coverage.info" -o result } # 上传 result.zip 到平台 upload_result() { # 打包 zip -r result.zip result # 上传平台 curl --insecure -X POST -F "file=@/$(pwd)/result.zip" -F "package=kylin-baidu-speech-engine" -F "username=$1" $2 echo "all parameter : $@" } # 编译项目 echo "Compiling the project..." #qmake && make # 运行各个单元测试 echo "Running unit tests..." run_unit_tests # 上传到平台 #upload_result echo "All tests have been run successfully, and coverage data has been collected." kylin-ai-document-qa-service-1.2.0.0/test/main.cpp000066400000000000000000000111141520600016100216320ustar00rootroot00000000000000/* * 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 #include #include #include #include // 定义一个回调函数,当定时器触发时调用该函数 gboolean quit_loop(gpointer data) { GMainLoop* loop = static_cast(data); g_main_loop_quit(loop); return G_SOURCE_REMOVE; // 返回 G_SOURCE_REMOVE 以移除定时器 } int main() { std::cout << " test start " << std::endl; std::cout << "test isSupported start." << std::endl; /*平台支持与否判断*/ knowledgebase::KnowledgebaseSession d; bool ok = false; knowledgebase::Status status = d.isSupported(ok); if (!ok) { std::cout << "test isSupported failed." << std::endl; } std::cout << "test isSupported end." << std::endl; std::cout << "test createKnowledgebase start." << std::endl; std::string name; status = d.createKnowledgebase(name); if (!status.success) { std::cout << "test createKnowledgebase failed, errorCode:" << status.errorCode << " errorMsg:" << status.errorMsg << std::endl; } std::cout << "name: " << name << std::endl; std::cout << "test createKnowledgebase end." << std::endl; std::cout << "test addFiles start." << std::endl; /*添加数据*/ namespace fs = std::filesystem; fs::path dir = fs::path(__FILE__).parent_path(); fs::path path = dir / "公司报销制度及流程.docx"; std::string filepath = path.string(); std::ostringstream first; first << R"( [ { "knowledgebase_name": ")" << name << R"(", "filepath": ")" << filepath << R"(" } ] )"; std::string files = first.str(); status = d.addTextFiles(files); if (!status.success) { std::cout << "test addFiles failed, errorMsg: " << status.errorCode << " errorMsg:" << status.errorMsg << std::endl; } std::cout << "test addFiles end." << std::endl; #if 1 /*获得所有数据*/ std::string contents; std::cout << "test getTextFileContents start." << std::endl; std::ostringstream second; second << R"( [ { "filepath": ")" << filepath << R"(" } ] )"; std::string filesContent = second.str(); status = d.getTextFileContents(filesContent, contents); if (!status.success) { std::cout << "test getTextFileContents failed, errorMsg: " << status.errorMsg << std::endl; } std::cout << "contents: " << contents << std::endl; std::cout << "test getTextFileContents end." << std::endl; #endif #if 1 /*搜索*/ std::string searchResult; std::ostringstream oss; oss << R"({ "knowledgebase_name": ")" << name << R"(", "search_condition": "公司报销" })"; std::string searchcondition = oss.str(); std::cout << "test similaritySearch start." << std::endl; status = d.similaritySearch(searchcondition, searchResult); std::cout << "searchResult:" << searchResult << std::endl; if (!status.success) { std::cout << "test similaritySearch failed, errorCode:" << status.errorCode << " errorMsg:" << status.errorMsg << std::endl; } std::cout << "test similaritySearch end." << std::endl; #endif /*删除数据库collection*/ std::cout << "test deleteKnowledgebase start: " << name << std::endl; status = d.deleteKnowledgebase(name); if (!status.success) { std::cout << "test deleteKnowledgebase failed, errorMsg: " << status.errorCode << " errorMsg:" << status.errorMsg << std::endl; } std::cout << "test deleteKnowledgebase end." << std::endl; std::cout << " test end " << std::endl; GMainLoop* loop = g_main_loop_new(nullptr, false); g_timeout_add_seconds(30, quit_loop, loop); g_main_loop_run(loop); return 0; }kylin-ai-document-qa-service-1.2.0.0/test/公司报销制度及流程.docx000077500000000000000000000340141520600016100325270ustar00rootroot00000000000000PK N@ docProps/PKN@U$^^qdocProps/app.xmln0DQ@( cDC9U-,jb[AuH鵷YyC旦`Pr&1\BgXE0ɒJ, `iga圞"dy _K9(09"u8KO HRG.d ea8=|jLIq\C%kvK)-u+fwNS]Hқ ;SPՅh j=.=AM[]e kvUxdu-8so[o['$q'x mQ:p"gy6c|AP?R7OFk{GWKPKN@JrGdocProps/core.xmlQO M -.jH%jg4눅6]W胏swpAS)MF*SuP<7׍ey}³mZ^8&oN@s ⶱP \| pJ H)&de 40M(z0(3V؆;ql)N>85KlS~z+ӿTR 㘰=(iYy7+T$]6dC,!9>xb5츩:P7Rs [B)fg@gW>4r.PKN@ docProps/custom.xmlj0@C>&f%:TtB$Am>]^pew5Y:?]4!H͍BCE7-KHw {vJATh_KTO"֑Ʃ.ѝII0%Ο/Wa%hm3!F&GdKisuB;O|yZ1PO(NEѾ*J24&4IIm 4T qU_PK N@word/PKN@Vs$ oword/styles.xml]rާ*@J~-*oɒ"*wuh Yy}dC03`GϻE$,P=|u:2r"T2sx߼[gs(3<&"ϓ[HdT"cqHp>G"},=OEȃYk`-@ELs}˹O?.W+"ȸʠl$YQѠ V([BTʓY>²d 6+0~Y} rJl̮(pۥY*r'e*ebSMy_bY<t, )9X Y:!ΆCbP./u:p{#=p{Џܞ #3$H<а ɡaRC2$eH ː!%4,CBhXt(NxlRyr߼tEAO2HG>p22P'M*2.9>G#sY N\D3XO}-FTmFF {qtg9|ڹ9BŲ_Z Oa 9Ћ3%` ݣ8t(\S%/X;%rtO#EOhrsēs =Hjb^O蠗ڹmk M20Te:ؘH*!_^V |^ܠ"3V#!D5`)Siy܋lEt6":WW5baUaU5legwDgwDgwDgwDgwDg+Gg|78bۈ.>ݍC 8>t 3#TAxa}+B Z< A@6zsL(my1r_EL>BT8+eN<+nf-_Qej6NA̩/S$<ɝ.0VB|j^W jaKG|jqhG >QlH`:CO3[<̖5ŀ*ؒ 6'|`: Y*l(0Q`d9eSYڭYk,CvVߡD;Px n<Ħ eӆk:CM4oj#m-TwěEo*Woo*Qoo*Qo&o*Mjo*MjxSlP5śH{E#a؃1m.rQě[DśJ[DśJ[DěJBo*MjMm7&5QSDś]xSYlo*;]M墈7xSz7xSz7x7"T.6Ԛo*Mjx7qKO-TwěEo*Woo*Qoo*Qo&o* E\6m5)T"#dfDXRocP^TXޜTT{7 &HX]=:N:N2 Vf$)y +U48Q V(K`^fE+s9/0;yؾ g<?zc XѬ\~ZxZvNPipl~4`OQv#Fuc^r\>^e7ڱ ˏ7T_|;?ٹU<5čKT+<7r!@oR\l:Q]狹eBM6Ϣ'|5 oSY 7z%~#}ZM7[b[q5|YGk#ǵ2KvU2NIh}ߵ<<ǭBKY/ЖQ³P$EY`dw4{u8ỽw% Dh=B/Ѭyy]c04+e!H p0S5VٝYaK/T-lЍĔS<揚0@/.d+%؋ &غԞ5>3[ :OSÈ@65[TmؑCl[ m`W&Υ D`jTYfɊ{?')~1oHa;aGOPfw&m^a*/Ekw/x ]i`χ13sΪ%ՠC~ؠICn][xx}0W='Z[^_+KO^kFzKwOaqE%n'8du~`A8GS"ug+˗D;VBKeV5ϸ~` Fq$ΪtSYԒxpj8Ӥ(m[ Ok#hy;:s/X /_& wb,?{9! #Jvi' 7hv" _XMZhwB<:Jq(n"q!$i`Egnef}2ܽ /PK N@ word/theme/PKN@Ѯ$word/theme/theme1.xmlYMo7X콱d#2">vDJ)-ˈ\݊X@Ѵȡ^z(HhkHS CjEJT>E}3|!WWޏw ,iK%ɐ$ ~˾'$JDY և\A21>GRkkbH\b)NوIõ#ӵR#^bp{c4"C?f;HPC{7L46BLErѦ쨏KߣHHxK_ۺ6s#*Wv]x]A1iRԶ @2S:ŸVq1}Vw;j5@GvQ%Uo5(_Yw-נ _]W*VkP-vn5($/KFk2bt oT+z|j(KM1b\Uk1x H$')!q Q2'a$4h#y64KCjFO 9Ie$E1^߾g~=~/#j%i/y<ڍ&ϟ?Wn l9Wnb3nb; J## }}(rv;D6gE|"^[(쩹0'I螜OL-]sPb3IA=e+͛%8Scb 9l$A>X47%1e"bspaԵ6>+ucjH\QL̀#H|h:BBCL .k$}ĝ:m$d3m6nE(N]I"C"&.wy@t!JjpӤ4/dU)!R$'w6 7Ho8x_TĹgvznQ[sM6rz/ߋ|EM1^a;f .KB4?"dB !iq1]W> ^JaU!+,'|А|)Y?RT9,h&/ %Ɋ d5ZF} ^T:C\RlB sF 8t-F*aDwK9S>mÉ/z.=)؊:r'0#B%x6fIEɝػ-ê42aȷ (UN*tݕfcf KEAb"QIMxwRu%fH<GA\G"dRT+kP|}$.t|<]|[~zK۲k,&JzxMJy'KQg u8A:o~{RABF2^ (%Fm~eͿƬ#<NR'{z:dN[ǝ3>^0,c#4_)G}{3/މdjGT{&Vsyף3%%,C߈tܹUax+H"z^m]]sLէf^MjP´p`=od??S>8֟y6Y2MFsnšڙ29slȞq2A\D7oD&D(z>g.=Dl{P[j Am{w (c/3{4h 6e.d 7\> =[ pR~˜5*!:ʢ'ӎ6WFbr3FZڀBz5b9' t Mt)b^6&WqH!u{x7+]b[uucXxj,ӇP#X{-۪TqpU2^ZcoCaO{mbrT* 85sLv@뿖>Sc/-쳶52"H/#w4'NJbP'iǖpv47m Fpl RW Zf,ēԈ>`Ŵ]Q)F6`4ME"}-OO`#xe q}Q.E!ъJj3,zYWL뜵7ǬJ >f`[ZqA3\~HfErm⌺̥"DiV%~sj*PH3O!Hc4hU_bfCGaǝFi(Ix\ ij 0{+yqg3 )|M![8(UR=EtA}6#!+ b*Oҕ@V"mȊ@iRWsZr-5Ngiv$]2gPN9 VЛ"T2J"@nlbKIe{U@943Q٠,|^TD=~~w#5cD;T:^hWBA9d!8g. ~,N™@P$ )qsfpp2ZQ0ʆ<)vU8@G m ]Py14ArRC7U _z$'/g*'cpJ77Oe5w`s#=5=ΐ,tㆋoZAFZJ&d xr @kcUfbj#*kvc7Stn?8F/Oи4Tt^A>O@Ow=Z)/=iUgwG($f^gqC:x܇?pC1+\_GקDU !AUƠ|*'AYRc՜1PR T ywF7nF:i;%5\*5Ab H.\ >G$l{p³h+]@ꋡrM8G SQE\(;T_|/a؛k·0T+x rv.iq3\8_h PK N@ customXml/PKN@YIcustomXml/item1.xmlA 0 kA=@HILBA\~|_WS0r@شt7p7{P,E ށO,85x %bJ)Kg0nuSHp;×b?K9x9q`PKN@cC{EGcustomXml/itemProps1.xmleQk0r5Fb,N`!^ۀI17t}{9]\ph4!@-L'kXuZՏUgw:3ѡ Byl|imބIM\а!LfC,k =28;7n ⌊ȌٛIqt"ƈYv$'"f{{+j$ReFBSiJu7? uEW}{ PKN@O word/numbering.xmlVmk0>}_nI=2#7zCdNdUHͱ5!Tgʨ}袥)*H u 9H?ZTq"Gd^r"l1ԄARU2ƲA6"*ZZAJ@8;!փ8:=Ꟍq\1q]/Ḯc*:q -ERu(6x\g"̫sQfY+ [uρg! 4yR x>qg]c5OzE0t ebyЁy,F*i}aYn+r  ^-?}i0.mYnqKr1&SEmΉ_w䱃|nk3RX 7#u)V<kݮno}1bޥXu~h 8 S4F{!HACAo(˖KAG5uȲ|F'x-@EZO.z[Ѕow1Yw4׮ =蓰fIX;gNE\p$gt vthcOi PKN@H_4rword/fontTable.xmlXˎ6?Z==F<-[E`PI,h3EǝH6YE-Me d/zIJlSSk Ah\W9^[?:\vmе-lBҳ}^tж-t}}7)K3aTthܵgY68g"q8S)O~PXbF(#c]ii>YtJb<`4SR1#sQd[mdY3D磈4^3!;rd*XMlƝg)hvK/Ore'E:K.(U(e{0%]tۇoL qDW䢈rW͟,sĉܘ^#\X۵ᑸ^e׵#)=jUcQsbGMH΁W}:B;\|毟(N%Xx/~}9Lm{>k)Z$.V]XmEXUcKa8+*po_?{o2xT`iM},ݟl=@boŒA_%JτXQ$ދgCx~Ok T Z !jyk#P74A*M{JM՚t/ʖ&RJQ+X5a 6V+K9S*d N0~MbETaq5cfTvpL2|b\sUU-+ґ#'RijY1 z9&"N(U:`RRy]N A6>[HǦ;ImS+ЪQ^ϦΌo x*Wk F4XEz~.787L Cڔn7HMT̀lQC̝.s ְ**ŸF Y캞NYThܱF]gn, uvAj m(h=@(&}MAS.%ܞ;, g{yc-NPK N@_rels/PKN@"" _rels/.relsJ1!}7*"loDH}! L}{r2g|szstxm U Naq "3zCD62{(.>+㝔Y0W!/6$\ɈzU]ikANl;tr(Θ:b!i> rfu>JG1ے7Pay,]1<h|Tn,PYkZA@ k9rq6ԵPlVT~ɲB9]:ڍj#1e~1s:8i{!leAAֽ !=޹7Gl7fɛ} PKN@x 0[Content_Types].xmlPK N@-_rels/PKN@""  8-_rels/.relsPK N@ #customXml/PK N@^.customXml/_rels/PKN@t?9z( .customXml/_rels/item1.xml.relsPKN@YI $customXml/item1.xmlPKN@cC{EG $customXml/itemProps1.xmlPK N@ docProps/PKN@U$^^q 'docProps/app.xmlPKN@JrG docProps/core.xmlPKN@  )docProps/custom.xmlPK N@Xword/PK N@ /word/_rels/PKN@&J  /word/_rels/document.xml.relsPKN@Srǽ1 word/document.xmlPKN@H_4r (word/fontTable.xmlPKN@O  %word/numbering.xmlPKN@B[  5word/settings.xmlPKN@Vs$ o {word/styles.xmlPK N@ word/theme/PKN@Ѯ$ word/theme/theme1.xmlPKY2