pax_global_header00006660000000000000000000000064152057564000014516gustar00rootroot0000000000000052 comment=9bbcbcb8dc0b1214db575ed52c080fb86b45e01e libkysdk-genai-1.1.0.1/000077500000000000000000000000001520575640000145515ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/.clang-format000066400000000000000000000001271520575640000171240ustar00rootroot00000000000000 Language: Cpp BasedOnStyle: Google AccessModifierOffset: -4 IndentWidth: 4 TabWidth: 4libkysdk-genai-1.1.0.1/.gitignore000066400000000000000000000015201520575640000165370ustar00rootroot00000000000000 # This file is used to ignore files which are generated # ---------------------------------------------------------------------------- *~ *.autosave *.a *.core *.moc *.o *.obj *.orig *.rej *.so *.so.* *_pch.h.cpp *_resource.rc *.qm .#* *.*# core !core/ tags .DS_Store .directory *.debug Makefile* *.prl *.app moc_*.cpp ui_*.h qrc_*.cpp Thumbs.db *.res *.rc /.qmake.cache /.qmake.stash # qtcreator generated files *.pro.user* CMakeLists.txt.user* # xemacs temporary files *.flc # Vim temporary files .*.swp # Visual Studio generated files *.ib_pdb_index *.idb *.ilk *.pdb *.sln *.suo *.vcproj *vcproj.*.*.user *.ncb *.sdf *.opensdf *.vcxproj *vcxproj.* # MinGW generated files *.Debug *.Release # Python byte code *.pyc # Binaries # -------- *.dll *.exe build .vscode .cache .reuse # third-party third-party/llama.cpp/common/build-info.cpplibkysdk-genai-1.1.0.1/CMakeLists.txt000066400000000000000000000062411520575640000173140ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kysdk-genai-nlp LANGUAGES CXX C) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) ####################################################################### # Options ####################################################################### option(BUILD_EXAMPLES "Build Examples" OFF) option(ENABLE_TEST "Build Test" OFF) if (CMAKE_BUILD_TYPE AND (CMAKE_BUILD_TYPE STREQUAL "Debug")) add_compile_definitions(RUN_IN_DEBUG) else () add_compile_definitions(RUN_IN_RELEASE) endif () # jsoncpp find_package(jsoncpp REQUIRED) # kylin-ai-proto find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(TEXT_COMMON_PROTO_FILES gennlpservice) kylin_ai_generate_gdbus_proto_code(VISION_COMMON_PROTO_FILES genaivisionservice) # pkg-config find_package(PkgConfig REQUIRED) # glib pkg_check_modules(GIO REQUIRED gio-unix-2.0) include_directories(${GIO_INCLUDE_DIRS}) # kysdk-ai-common pkg_check_modules(AI_COMMON REQUIRED kysdk-ai-common) include_directories(${AI_COMMON_INCLUDE_DIRS}) include_directories(include) include_directories(include/kylin-ai) include_directories(include/kylin-ai/genai/text) include_directories(include/kylin-ai/genai/vision) include_directories(src) include_directories(src/text) include_directories(src/vision) set(TEXT_SERVICE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/_chatmessage.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/_chatmodelconfig.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/_chatresult.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/_genaitextsession.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/genainlpserver.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/text/genainlpserviceproxy.cpp ) set(VISION_SERVICE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/logger.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/vision/imageconfig.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/vision/_imageresult.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/vision/_genaiimagesession.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/vision/genaivisionserviceproxy.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/vision/image.cpp ) add_library(kysdk-genai-nlp SHARED include/kylin-ai/genai/text/error.h ${TEXT_SERVICE_SOURCES} ${TEXT_COMMON_PROTO_FILES} ) add_library(kysdk-genai-vision SHARED ${VISION_SERVICE_SOURCES} ${VISION_COMMON_PROTO_FILES}) if (BUILD_EXAMPLES) add_subdirectory(examples) endif () if (ENABLE_TEST) enable_testing() add_subdirectory(tests) endif () set_target_properties(kysdk-genai-nlp PROPERTIES VERSION 1.0.0 SOVERSION 1) set_target_properties(kysdk-genai-vision PROPERTIES VERSION 1.0.0 SOVERSION 1) target_link_libraries( kysdk-genai-nlp jsoncpp ${GIO_LIBRARIES} ) target_link_libraries( kysdk-genai-vision jsoncpp ${GIO_LIBRARIES} ${OPENSSL_LIBRARIES} ) include(CMakePackageConfigHelpers) include(GNUInstallDirs) install(TARGETS kysdk-genai-nlp DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(TARGETS kysdk-genai-vision DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(DIRECTORY include/kylin-ai DESTINATION include) install(DIRECTORY usr/ DESTINATION /usr) libkysdk-genai-1.1.0.1/COPYING000066400000000000000000001045151520575640000156120ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . libkysdk-genai-1.1.0.1/README.md000066400000000000000000000015171520575640000160340ustar00rootroot00000000000000# libkysdk-genai-nlp Client libraries for generative AI text and vision services, communicating with local AI backends via D-Bus. ## Features ### Text (libkysdk-genai-nlp) - Chat with context and history - Text generation from prompts - Text expansion, polishing, error correction - Translation (Chinese to English) - Summarization, email reply, work summary, tag extraction ### Vision (libkysdk-genai-vision) - Image generation from text prompts - Configurable image style and size - Asynchronous result delivery via callbacks ## Build Dependencies - CMake >= 3.5 - C++17 compiler - jsoncpp - GIO (glib2) - OpenSSL - libkysdk-ai-common - kylin-ai-proto ## Build ```bash mkdir build && cd build cmake .. make ``` ## Install ```bash sudo make install ``` ## License GPL-3.0-or-later. See [COPYING](COPYING) for the full license text. libkysdk-genai-1.1.0.1/examples/000077500000000000000000000000001520575640000163675ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/examples/CMakeLists.txt000066400000000000000000000017621520575640000211350ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kysdk-genai-nlp-examples LANGUAGES CXX C) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # jsoncpp find_package(jsoncpp REQUIRED) # openssl find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) # package config find_package(PkgConfig REQUIRED) pkg_check_modules(GIO REQUIRED gio-unix-2.0) include_directories(${GIO_INCLUDE_DIRS}) pkg_check_modules(KYLIN_AI_CONFIG kyai-config) include_directories(${KYLIN_AI_CONFIG_INCLUDE_DIRS}) # protocol find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(COMMON_PROTO_FILES gennlpservice) # inner include_directories(${CMAKE_SOURCE_DIR}/include) set(LIBRARIES pthread jsoncpp ${OPENSSL_LIBRARIES} ${GIO_LIBRARIES} ${KYLIN_AI_CONFIG_LIBRARIES} ) add_executable(chatbot chatbot.cpp ${TEXT_SERVICE_SOURCES} ${TEXT_COMMON_PROTO_FILES}) target_link_libraries(chatbot ${LIBRARIES}) libkysdk-genai-1.1.0.1/examples/chatbot.cpp000066400000000000000000000124131520575640000205200ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ // std #include #include #include // api #include "kylin-ai/genai/text/chat.h" #include "kylin-ai/genai/text/chatmessage.h" #include "kylin-ai/genai/text/config.h" #include "kylin-ai/genai/text/error.h" #include "kylin-ai/genai/text/result.h" // glib #include namespace { std::vector stringSplit(const std::string &str, const std::string &delim) { std::vector result; size_t begin = 0; for (size_t end; end = str.find(delim, begin), end != std::string::npos; begin = end + delim.size()) { result.emplace_back(str.substr(begin, end - begin)); } result.emplace_back(str.substr(begin)); return result; } } // namespace class Chatbot { public: Chatbot() { stdinChannel_ = g_io_channel_unix_new(STDIN_FILENO); g_io_channel_set_encoding(stdinChannel_, nullptr, nullptr); g_io_channel_set_buffered(stdinChannel_, TRUE); g_io_channel_set_flags(stdinChannel_, G_IO_FLAG_NONBLOCK, nullptr); g_io_add_watch(stdinChannel_, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR), onStdinEnter, this); mainLoop_ = g_main_loop_new(nullptr, false); session_ = genai_text_create_session(); config_ = chat_model_config_create(); #define BAIDU 0 #if BAIDU const char *MODEL_NAME = "百度-ERNIE-Bot-4"; chat_model_config_set_name(config_, MODEL_NAME); chat_model_config_set_top_k(config_, 4); chat_model_config_set_deploy_type(config_, ModelDeployType::PublicCloud); genai_text_set_model_config(session_, config_); #else // default genai_text_set_model_config(session_, nullptr); #endif int errorCode = genai_text_init_session(session_); if (errorCode != AISDK_NO_ERROR) { std::string errorMessage = "Func genai_text_init_session init error, error code is: " + std::to_string(errorCode); throw std::runtime_error(errorMessage.c_str()); } genai_text_result_set_callback(session_, callback, nullptr); } ~Chatbot() { g_main_loop_unref(mainLoop_); g_io_channel_unref(stdinChannel_); } void run() const { g_main_loop_run(mainLoop_); } private: static gboolean onStdinEnter(GIOChannel *channel, GIOCondition condition, gpointer userData) { Chatbot *tool = (Chatbot *)userData; gchar *line{nullptr}; if (condition & G_IO_IN) { GIOStatus status = g_io_channel_read_line(channel, &line, nullptr, nullptr, nullptr); if (status == G_IO_STATUS_NORMAL) { std::string input(line); if (!input.empty() && input[input.size() - 1] == '\n') { input.erase(input.size() - 1); } tool->control(input); g_free(line); } } return TRUE; } void control(const std::string &input) const { if (input.empty()) { std::fprintf(stdout, "Input message is empty.\n"); } else if (input == "quit") { g_main_loop_quit(mainLoop_); } else if (input.substr(0, 5) == "top_k") { std ::vector args = stringSplit(input, " "); int topK = std::stoi(args[1]); chat_model_config_set_top_k(config_, topK); genai_text_set_model_config(session_, config_); } else { std::fprintf(stdout, "----------------------------------------\n"); std::fprintf(stdout, "question:\n"); std::fprintf(stdout, "%s\n", input.c_str()); std::fprintf(stdout, "answer:\n"); genai_text_chat_async(session_, input.c_str()); } } static void callback(ChatResult *result, void *user_data) { std::fprintf(stdout, "%s", chat_result_get_assistant_message(result)); if (chat_result_get_is_end(result)) { std::fprintf(stdout, "\n"); std::fprintf(stdout, "========================================\n"); } } private: GIOChannel *stdinChannel_{nullptr}; GMainLoop *mainLoop_{nullptr}; ChatModelConfig *config_{nullptr}; GenAiTextSession *session_{nullptr}; }; int main() { try { Chatbot chatbot{}; chatbot.run(); } catch (std::exception &exception) { std::fprintf(stderr, "Exception: %s\n", exception.what()); return -1; } return 0; }libkysdk-genai-1.1.0.1/include/000077500000000000000000000000001520575640000161745ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/include/kylin-ai/000077500000000000000000000000001520575640000177115ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/include/kylin-ai/genai/000077500000000000000000000000001520575640000207745ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/000077500000000000000000000000001520575640000217605ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/chat.h000066400000000000000000000056101520575640000230520ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_TEXT_CHAT_H__ #define __KYLIN_AI_GEN_AI_TEXT_CHAT_H__ #include #include "chatmessage.h" #include "config.h" #include "result.h" #ifdef __cplusplus extern "C" { #endif typedef enum { TEXT_EXPANSION = 1, TEXT_POLISHING = 2, TRANSLATE_CHINESE_TO_ENGLISH = 3, TEXT_ERROR_CORRECTION = 8, SUMMARY = 9, EMAIL_REPLY = 10, WORK_SUMMARY = 11, TAG_EXTRACTION = 12, } PromptId; typedef struct _GenAiTextSession GenAiTextSession; typedef void (*ChatResultCallback)(ChatResult *chat_result, void *user_data); AISDK_EXTERN GenAiTextSession *genai_text_create_session(); AISDK_EXTERN void genai_text_destroy_session(GenAiTextSession **session); AISDK_EXTERN int genai_text_init_session(GenAiTextSession *session); AISDK_EXTERN void genai_text_result_set_callback(GenAiTextSession *session, ChatResultCallback callback, void *user_data); AISDK_EXTERN void genai_text_set_model_config(GenAiTextSession *session, ChatModelConfig *config); // 根据提示进行文本生成补全 AISDK_EXTERN void genai_text_generate_content_async(GenAiTextSession *session, const char *prompt); // 进行对话,支持缓存上下文 AISDK_EXTERN void genai_text_chat_async(GenAiTextSession *session, const char *question); // 进行对话,需要传入历史消息 AISDK_EXTERN void genai_text_chat_with_history_messages_async(GenAiTextSession *session, ChatMessage *history_messages); // 设置对话提示词 AISDK_EXTERN void genai_text_set_chat_system_prompt(GenAiTextSession *session, const char *prompt); // 设置对话的提示词,使用SDK内置的提示词 AISDK_EXTERN void genai_text_set_chat_system_prompt_id(GenAiTextSession *session, PromptId prompt_id); // 清除对话上下文 AISDK_EXTERN void genai_text_clear_chat_history_messages(GenAiTextSession *session); AISDK_EXTERN void genai_text_stop_chat(GenAiTextSession *session); #ifdef __cplusplus } #endif #endif // __KYLIN_AI_GEN_AI_TEXT_CHAT_H__ libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/chatmessage.h000066400000000000000000000027511520575640000244220ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_TEXT_CHAT_MESSAGE_H__ #define __KYLIN_AI_GEN_AI_TEXT_CHAT_MESSAGE_H__ #include #ifdef __cplusplus extern "C" { #endif typedef struct _ChatMessage ChatMessage; AISDK_EXTERN ChatMessage *chat_message_create(); AISDK_EXTERN void chat_message_destroy(ChatMessage **chat_message); AISDK_EXTERN void chat_message_add_system_message(ChatMessage *chat_message, const char *message); AISDK_EXTERN void chat_message_add_user_message(ChatMessage *chat_message, const char *message); AISDK_EXTERN void chat_message_add_assistant_message(ChatMessage *chat_message, const char *message); #ifdef __cplusplus } #endif #endif // __KYLIN_AI_GEN_AI_TEXT_CHAT_MESSAGE_H__ libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/config.h000066400000000000000000000026421520575640000234020ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_TEXT_CONFIG_H__ #define __KYLIN_AI_GEN_AI_TEXT_CONFIG_H__ #include #include #ifdef __cplusplus extern "C" { #endif typedef struct _ChatModelConfig ChatModelConfig; AISDK_EXTERN ChatModelConfig *chat_model_config_create(); AISDK_EXTERN void chat_model_config_destroy(ChatModelConfig **config); AISDK_EXTERN void chat_model_config_set_name(ChatModelConfig *config, const char *name); AISDK_EXTERN void chat_model_config_set_top_k(ChatModelConfig *config, int top_k); AISDK_EXTERN void chat_model_config_set_deploy_type(ChatModelConfig *config, ModelDeployType type); #ifdef __cplusplus } #endif #endif // __KYLIN_AI_GEN_AI_TEXT_CONFIG_H__ libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/error.h000066400000000000000000000017551520575640000232720ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_TEXT_ERROR_H__ #define __KYLIN_AI_GEN_AI_TEXT_ERROR_H__ #include #ifdef __cplusplus extern "C" { #endif typedef enum { NLP_INPUT_INVALID = 100, NLP_PARAM_ERROR, } GenAiTextErrorCode; #ifdef __cplusplus } #endif #endif // __KYLIN_AI_GEN_AI_TEXT_ERROR_H__ libkysdk-genai-1.1.0.1/include/kylin-ai/genai/text/result.h000066400000000000000000000033011520575640000234440ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_TEXT_RESULT_H__ #define __KYLIN_AI_GEN_AI_TEXT_RESULT_H__ #include #ifdef __cplusplus extern "C" { #endif typedef struct _ChatResult ChatResult; AISDK_EXTERN const char *chat_result_get_assistant_message(ChatResult *result); AISDK_EXTERN const char *chat_result_get_reasoning_message(ChatResult *result); /** * finish_reason解释说明: * stop : API 返回完整的模型输出 * length : 因为 max_tokens 参数或 token 限制,导致不完整的模型输出 * content_filter: 因为我们的内容过滤的标记,删掉了内容 * null : API 响应还在进行中或未完成 */ AISDK_EXTERN const char *chat_result_get_finish_reason_message(ChatResult *result); AISDK_EXTERN int chat_result_get_error_code(ChatResult *result); AISDK_EXTERN const char *chat_result_get_error_message(ChatResult *result); AISDK_EXTERN bool chat_result_get_is_end(ChatResult *result); #ifdef __cplusplus } #endif #endif // __KYLIN_AI_GEN_AI_TEXT_RESULT_H__ libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/000077500000000000000000000000001520575640000223035ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/error.h000066400000000000000000000025031520575640000236050ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_VISION_ERROR_H__ #define __KYLIN_AI_GEN_AI_VISION_ERROR_H__ #include #ifdef __cplusplus extern "C" { #endif typedef enum { VISION_INPUT_TEXT_LENGTH_INVALID = 100, // 文生图输入文本过长 VISION_IMAGE_STYLE_INVALID, // 不支持的风格 VISION_IMAGE_SIZE_INVALID, // 不支持的大小 VISION_IMAGE_NUMBER_INVALID, // 不支持的图片数量 VISION_IMAGE_GENERATION_BLOCKED, // 图片未过审 VISION_IMAGE_GENERATION_FAILED, // 生成图片失败 } GenAiVisionErrorCode; #ifdef __cplusplus } #endif #endif libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/image.h000066400000000000000000000041131520575640000235350ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_VISION_IMAGE_H__ #define __KYLIN_AI_GEN_AI_VISION_IMAGE_H__ #include #include "imageconfig.h" #include "imageresult.h" #ifdef __cplusplus extern "C" { #endif typedef void (*ImageResultCallback)(VisionImageResult *image_data, void *user_data); typedef struct _GenAiImageSession GenAiImageSession; AISDK_EXTERN GenAiImageSession *genai_image_create_session(); AISDK_EXTERN void genai_image_destroy_session(GenAiImageSession **session); AISDK_EXTERN int genai_image_init_session(GenAiImageSession *session); AISDK_EXTERN void genai_image_set_config(GenAiImageSession *session, ImageConfig *config); AISDK_EXTERN void genai_image_result_set_callback(GenAiImageSession *session, ImageResultCallback callback, void *user_data); AISDK_EXTERN const char **genai_image_get_supported_image_style(GenAiImageSession *session, int *number); AISDK_EXTERN const ImageSize *genai_image_get_supported_image_size( GenAiImageSession *session, int *number); AISDK_EXTERN int genai_image_get_supported_image_number(GenAiImageSession *session); AISDK_EXTERN void genai_image_generate_image_async(GenAiImageSession *session, const char *prompt); #ifdef __cplusplus } #endif #endif libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/imageconfig.h000066400000000000000000000025601520575640000247270ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_VISION_IMAGE_CONFIG_H__ #define __KYLIN_AI_GEN_AI_VISION_IMAGE_CONFIG_H__ #include #ifdef __cplusplus extern "C" { #endif typedef struct _ImageSize { int width; int height; } ImageSize; typedef struct _ImageConfig ImageConfig; AISDK_EXTERN ImageConfig *image_config_create(); AISDK_EXTERN void image_config_destroy(ImageConfig **config); AISDK_EXTERN void image_config_set_generation_number(ImageConfig *config, int number); AISDK_EXTERN void image_config_set_style(ImageConfig *config, const char *style); AISDK_EXTERN void image_config_set_size(ImageConfig *config, ImageSize image_size); #ifdef __cplusplus } #endif #endif libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/imageformat.h000066400000000000000000000017501520575640000247520ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_VISION_IMAGE_FORMAT_H__ #define __KYLIN_AI_GEN_AI_VISION_IMAGE_FORMAT_H__ #ifdef __cplusplus extern "C" { #endif typedef enum { IMAGE_FORMAT_UNKNOWN = -1, IMAGE_FORMAT_JPEG, IMAGE_FORMAT_PNG, IMAGE_FORMAT_WEBP } ImageFormat; #ifdef __cplusplus } #endif #endif libkysdk-genai-1.1.0.1/include/kylin-ai/genai/vision/imageresult.h000066400000000000000000000033731520575640000250030ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef __KYLIN_AI_GEN_AI_VISION_IMAGE_RESULT_H__ #define __KYLIN_AI_GEN_AI_VISION_IMAGE_RESULT_H__ #include #include #include "imageconfig.h" #include "imageformat.h" #ifdef __cplusplus extern "C" { #endif typedef struct _VisionImageResult VisionImageResult; AISDK_EXTERN ImageFormat image_result_get_format(VisionImageResult *image_result); AISDK_EXTERN ImageSize image_result_get_size(VisionImageResult *image_result); AISDK_EXTERN int image_result_get_total(VisionImageResult *image_result); AISDK_EXTERN int image_result_get_index(VisionImageResult *image_result); AISDK_EXTERN const uint8_t *image_result_get_data(VisionImageResult *image_result, int *data_length); AISDK_EXTERN int image_result_get_error_code(VisionImageResult *image_result); AISDK_EXTERN const char *image_result_get_error_message(VisionImageResult *image_result); typedef void (*VisionImageResultCallback)(VisionImageResult *result, void *user_data); #ifdef __cplusplus } #endif #endif libkysdk-genai-1.1.0.1/src/000077500000000000000000000000001520575640000153405ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/src/logger.cpp000066400000000000000000000033501520575640000173240ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "logger.h" #include #include void Logger::printLn() { std::cout << '\n'; } void Logger::printErrorLn() { std::cerr << '\n'; } std::string Logger::location(const char* fileName, int line, const char* funcName) { std::ostringstream oss; oss << '[' << fileName << ':' << line << ':' << funcName << ']'; return oss.str(); } std::string Logger::currentTime() { struct timeval tv{}; struct tm* tm = nullptr; gettimeofday(&tv, nullptr); time_t tt = tv.tv_sec; tm = localtime(&tt); char buffer[32]{}; #ifdef RUN_IN_DEBUG sprintf(buffer, "[%04d-%02d-%02d %02d:%02d:%02d.%03ld]", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec / 1000); #else sprintf(buffer, "[%ld]", tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif return buffer; } Logger& Logger::getInstance() { static Logger instance{}; return instance; } Logger::Logger() { #ifdef RUN_IN_DEBUG level_ = LOG_LEVEL_DEBUG; #endif } libkysdk-genai-1.1.0.1/src/logger.h000066400000000000000000000306351520575640000167770ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef UTILS_LOGGER_H #define UTILS_LOGGER_H #include #include #include #include #include // #define CLR_CLR "\033[0m" // 恢复颜色 // #define CLR_BLACK "\033[30m" // 黑色字 // #define CLR_RED "\033[31m" // 红色字 // #define CLR_GREEN "\033[32m" // 绿色字 // #define CLR_YELLOW "\033[33m" // 黄色字 // #define CLR_BLUE "\033[34m" // 蓝色字 // #define CLR_PURPLE "\033[35m" // 紫色字 // #define CLR_SKYBLUE "\033[36m" // 天蓝字 // #define CLR_WHITE "\033[37m" // 白色字 // // #define CLR_BLK_WHT "\033[40;37m" // 黑底白字 // #define CLR_RED_WHT "\033[41;37m" // 红底白字 // #define CLR_GREEN_WHT "\033[42;37m" // 绿底白字 // #define CLR_YELLOW_WHT "\033[43;37m" // 黄底白字 // #define CLR_BLUE_WHT "\033[44;37m" // 蓝底白字 // #define CLR_PURPLE_WHT "\033[45;37m" // 紫底白字 // #define CLR_SKYBLUE_WHT "\033[46;37m" // 天蓝底白字 // #define CLR_WHT_BLK "\033[47;30m" // 白底黑字 #ifndef __FILENAME__ #define __FILENAME__ (strrchr("/" __FILE__, '/') + 1) #endif class Logger { public: enum Level { LOG_LEVEL_SILENT = 0, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, LOG_LEVEL_WARN, LOG_LEVEL_ERROR }; static void printLn(); template static void printLn(T t, Args... args) { std::cout << t << ' '; printLn(args...); } static void printErrorLn(); template static void printErrorLn(T t, Args... args) { std::cerr << t << ' '; printErrorLn(args...); } template static void printLnLevel(const Logger& logger, Level level, Args... args) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { printLn(currentTime(), "\033[36mdebug\033[0m", args...); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { printLn(currentTime(), "\033[32minfo \033[0m", args...); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { printLn(currentTime(), "\033[33mwarn \033[0m", args...); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { printLn(currentTime(), "\033[31merror\033[0m", args...); } #else // release 暂时往stderr输出 if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { printErrorLn(currentTime(), "\033[36mdebug\033[0m", args...); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { printErrorLn(currentTime(), "\033[32minfo \033[0m", args...); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { printErrorLn(currentTime(), "\033[33mwarn \033[0m", args...); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { printErrorLn(currentTime(), "\033[31merror\033[0m", args...); } #endif } static void printfLnLevel(const Logger& logger, Level level, const char* format) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG FILE* pFile = stdout; #else FILE* pFile = stderr; #endif if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[36mdebug\033[0m ", format); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[32minfo \033[0m", format); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[33mwarn \033[0m", format); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { std::fprintf(pFile, "%s %s %s\n", currentTime().c_str(), "\033[31merror\033[0m", format); } } template static void printfLnLevel(const Logger& logger, Level level, const char* format, Args... args) { std::lock_guard locker(logger.mutex_); #ifdef RUN_IN_DEBUG FILE* pFile = stdout; #else FILE* pFile = stderr; #endif if (logger.level_ == LOG_LEVEL_SILENT) { // do nothing } else if (level == LOG_LEVEL_DEBUG and level >= logger.level_) { std::fprintf(pFile, "%s %s", currentTime().c_str(), "\033[36mdebug\033[0m "); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_INFO and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[32minfo \033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_WARN and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[33mwarn \033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } else if (level == LOG_LEVEL_ERROR and level >= logger.level_) { std::fprintf(pFile, "%s %s ", currentTime().c_str(), "\033[31merror\033[0m"); std::fprintf(pFile, format, args...); std::fprintf(pFile, "\n"); } } static std::string location(const char* fileName, int line, const char* funcName); static std::string currentTime(); static Logger& getInstance(); public: Logger(); private: mutable std::mutex mutex_; std::atomic level_{LOG_LEVEL_INFO}; }; #define g_Logger Logger::getInstance() #ifdef RUN_IN_DEBUG #define LOGD(...) \ do { \ Logger::printLnLevel( \ g_Logger, Logger::LOG_LEVEL_DEBUG, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGDF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, \ "[%s:%d:%s] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, ##__VA_ARGS__); \ } while (0) #define LOGI(...) \ do { \ Logger::printLnLevel( \ g_Logger, Logger::LOG_LEVEL_INFO, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGIF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, \ "[%s:%d:%s] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, ##__VA_ARGS__); \ } while (0) #define LOGW(...) \ do { \ Logger::printLnLevel( \ g_Logger, Logger::LOG_LEVEL_WARN, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGWF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, \ "[%s:%d:%s] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, ##__VA_ARGS__); \ } while (0) #define LOGE(...) \ do { \ Logger::printLnLevel( \ g_Logger, Logger::LOG_LEVEL_ERROR, \ Logger::location(__FILENAME__, __LINE__, __FUNCTION__), \ ##__VA_ARGS__); \ } while (0) #define LOGEF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, \ "[%s:%d:%s] " fmt, __FILENAME__, __LINE__, \ __FUNCTION__, ##__VA_ARGS__); \ } while (0) #else #define LOGD(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, \ ##__VA_ARGS__); \ } while (0) #define LOGDF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_DEBUG, fmt, \ ##__VA_ARGS__); \ } while (0) #define LOGI(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, ##__VA_ARGS__); \ } while (0) #define LOGIF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_INFO, fmt, \ ##__VA_ARGS__); \ } while (0) #define LOGW(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, ##__VA_ARGS__); \ } while (0) #define LOGWF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_WARN, fmt, \ ##__VA_ARGS__); \ } while (0) #define LOGE(...) \ do { \ Logger::printLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, \ ##__VA_ARGS__); \ } while (0) #define LOGEF(fmt, ...) \ do { \ Logger::printfLnLevel(g_Logger, Logger::LOG_LEVEL_ERROR, fmt, \ ##__VA_ARGS__); \ } while (0) #endif #endif // UTILS_LOGGER_H libkysdk-genai-1.1.0.1/src/text/000077500000000000000000000000001520575640000163245ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/src/text/_chatmessage.cpp000066400000000000000000000052431520575640000214570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "chatmessage.h" // #include #include "_chatmessage.h" #include "logger.h" ChatMessage *chat_message_create() { return new _ChatMessage{}; } void chat_message_destroy(ChatMessage **chat_message) { if (chat_message == nullptr) { return; } delete *chat_message; *chat_message = nullptr; } void chat_message_add_system_message(ChatMessage *chat_message, const char *message) { if (chat_message == nullptr) { return; } chat_message->systemMessage_ = message; } void chat_message_add_user_message(ChatMessage *chat_message, const char *message) { if (chat_message == nullptr) { return; } chat_message->messages_.push_back({ChatMessageType::USER, message}); } void chat_message_add_assistant_message(ChatMessage *chat_message, const char *message) { if (chat_message == nullptr) { return; } chat_message->messages_.push_back({ChatMessageType::ASSISTANT, message}); } std::string _ChatMessage::generateJsonString() const { Json::Value messages(Json::arrayValue); if (!systemMessage_.empty()) { Json::Value systemMessage(Json::objectValue); systemMessage["role"] = "system"; systemMessage["content"] = systemMessage_; messages.append(systemMessage); } for (const auto &item : messages_) { Json::Value message(Json::objectValue); if (item.type_ == ChatMessageType::USER) { message["role"] = "user"; message["content"] = item.message_; } else if (item.type_ == ChatMessageType::ASSISTANT) { message["role"] = "assistant"; message["content"] = item.message_; } else { // do nothing } messages.append(message); } Json::Value requestBody(Json::objectValue); requestBody["messages"] = messages; return requestBody.toStyledString(); }libkysdk-genai-1.1.0.1/src/text/_chatmessage.h000066400000000000000000000021361520575640000211220ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef CHAT_MESSAGE_H__ #define CHAT_MESSAGE_H__ #include #include enum class ChatMessageType { SYSTEM, USER, ASSISTANT }; struct ChatMessageItem { ChatMessageType type_{ChatMessageType::USER}; std::string message_; }; struct _ChatMessage { std::string systemMessage_; std::vector messages_; std::string generateJsonString() const; }; #endif // CHAT_MESSAGE_H__libkysdk-genai-1.1.0.1/src/text/_chatmodelconfig.cpp000066400000000000000000000041521520575640000223170ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "config.h" // #include "_chatmodelconfig.h" #include "jsoncpp/json/json.h" ChatModelConfig *chat_model_config_create() { return new _ChatModelConfig(); } void chat_model_config_destroy(ChatModelConfig **config) { if (config == nullptr) { return; } delete *config; *config = nullptr; } void chat_model_config_set_name(ChatModelConfig *config, const char *name) { if (config == nullptr) { return; } config->name_ = name; } void chat_model_config_set_top_k(ChatModelConfig *config, int top_k) { if (config == nullptr) { return; } config->topK_ = top_k; } void chat_model_config_set_deploy_type(ChatModelConfig *config, ModelDeployType type) { if (config == nullptr) { return; } config->type_ = type; } Json::Value modelConfigToJson(const _ChatModelConfig &modelConfig) { Json::Value root; root["model_name"] = modelConfig.name_; root["deploy_type"] = getModelConfigType(modelConfig); root["top_k"] = modelConfig.topK_; return root; } std::string getModelConfigType(const _ChatModelConfig &modelConfig) { switch (modelConfig.type_) { case ModelDeployType::OnDevice: return "Local"; case ModelDeployType::Custom: return "Custom"; case ModelDeployType::PublicCloud: return "PublicCloud"; default: return "Default"; } } libkysdk-genai-1.1.0.1/src/text/_chatmodelconfig.h000066400000000000000000000021311520575640000217570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef MODEL_CONFIG_H #define MODEL_CONFIG_H #include #include #include "kylin-ai/common/enums.h" struct _ChatModelConfig { std::string name_{}; ModelDeployType type_{ModelDeployType(-1)}; int topK_{}; }; Json::Value modelConfigToJson(const _ChatModelConfig &modelConfig); std::string getModelConfigType(const _ChatModelConfig &modelConfig); #endif // MODEL_CONFIG_H libkysdk-genai-1.1.0.1/src/text/_chatresult.cpp000066400000000000000000000033341520575640000213500ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "error.h" #include "result.h" // #include "_chatresult.h" const char *chat_result_get_assistant_message(ChatResult *result) { if (result == nullptr) { return nullptr; } return result->assistantMessage_.c_str(); } const char *chat_result_get_reasoning_message(ChatResult *result) { if (result == nullptr) { return nullptr; } return result->reasoningMessage_.c_str(); } const char *chat_result_get_finish_reason_message(ChatResult *result) { if (result == nullptr) { return nullptr; } return result->finishReasonMessage_.c_str(); } int chat_result_get_error_code(ChatResult *result) { if (result == nullptr) { return NLP_INPUT_INVALID; } return result->errorCode_; } const char *chat_result_get_error_message(ChatResult *result) { if (result == nullptr) { return nullptr; } return result->errorMessage_.c_str(); } bool chat_result_get_is_end(ChatResult *result) { if (result == nullptr) { return true; } return result->isEnd_; }libkysdk-genai-1.1.0.1/src/text/_chatresult.h000066400000000000000000000020361520575640000210130ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef CHAT_RESULT_H #define CHAT_RESULT_H #include #include "error.h" struct _ChatResult { std::string assistantMessage_; std::string reasoningMessage_; std::string finishReasonMessage_; int errorCode_{AISDK_NO_ERROR}; std::string errorMessage_; bool isEnd_{true}; // 默认暂定false默认 }; #endif // CHAT_RESULT_H libkysdk-genai-1.1.0.1/src/text/_genaitextsession.cpp000066400000000000000000000130001520575640000225550ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "_genaitextsession.h" #include #include "_chatmessage.h" #include "_chatmodelconfig.h" #include "chat.h" #include "error.h" #include "logger.h" GenAiTextSession *genai_text_create_session() { return new _GenAiTextSession{}; } void genai_text_destroy_session(GenAiTextSession **session) { if (session == nullptr) { return; } if (*session == nullptr) { return; } (*session)->destroy(); delete *session; *session = nullptr; } int genai_text_init_session(GenAiTextSession *session) { if (session == nullptr) { return AISDK_INVALID_SESSION; } return session->init(); } void genai_text_result_set_callback(GenAiTextSession *session, ChatResultCallback callback, void *user_data) { if (session == nullptr) { return; } session->setResultCallback(callback, user_data); } void genai_text_set_model_config(GenAiTextSession *session, ChatModelConfig *config) { if (session == nullptr) { return; } if (config == nullptr) { session->setChatModelConfig(ChatModelConfig{ std::string{}, ModelDeployType{ModelDeployType(-1)}, int{}}); return; } session->setChatModelConfig(*config); } // 根据提示进行文本生成补全 void genai_text_generate_content_async(GenAiTextSession *session, const char *prompt) { if (session == nullptr) { return; } genai_text_set_chat_system_prompt_id(session, TEXT_EXPANSION); genai_text_chat_async(session, prompt); } // 进行对话,支持缓存上下文 void genai_text_chat_async(GenAiTextSession *session, const char *question) { if (session == nullptr) { return; } session->chat(question); } // 进行对话,需要传入历史消息 void genai_text_chat_with_history_messages_async( GenAiTextSession *session, ChatMessage *history_messages) { if (session == nullptr) { return; } session->chatWithHistoryMessages(*history_messages); } // 设置对话提示词 void genai_text_set_chat_system_prompt(GenAiTextSession *session, const char *prompt) { if (session == nullptr or prompt == nullptr) { return; } session->setChatSystemPrompt(prompt); } // 设置对话的提示词,使用SDK内置的提示词 void genai_text_set_chat_system_prompt_id(GenAiTextSession *session, PromptId prompt_id) { if (session == nullptr) { return; } session->setChatSystemPromptId(prompt_id); } // 清除对话上下文 void genai_text_clear_chat_history_messages(GenAiTextSession *session) { if (session == nullptr) { return; } session->clearChatMessage(); } void genai_text_stop_chat(GenAiTextSession *session) { if (session == nullptr) { return; } session->stopChat(); } // 类:_GenaiTextSession成员函数定义 _GenAiTextSession::_GenAiTextSession() { serviceProxy_.setReconnectedCallback([this]() { initSession(); }); } int _GenAiTextSession::init() { if (!initServer()) { return AiSdkCommonErrorCode::AISDK_RUNTIME_ERROR; } return initSession(); } void _GenAiTextSession::destroy() { serviceProxy_.destroyEngine(sessionId_); } void _GenAiTextSession::setResultCallback(const ChatResultCallback &callback, void *userData) { serviceProxy_.setChatResultCallback(callback, userData); } void _GenAiTextSession::setChatModelConfig( const ChatModelConfig &chatModelConfig) { chatModelConfig_ = chatModelConfig; } void _GenAiTextSession::chat(const std::string &question) { serviceProxy_.chat(sessionId_, chatModelConfig_, question); } void _GenAiTextSession::chatWithHistoryMessages(const ChatMessage &message) { serviceProxy_.chatWithHistoryMessages(sessionId_, chatModelConfig_, message.generateJsonString()); } void _GenAiTextSession::setChatSystemPrompt(const std::string &message) { serviceProxy_.addSystemMessage(sessionId_, message); } void _GenAiTextSession::setChatSystemPromptId(PromptId promptId) { serviceProxy_.setChatSystemPromptId(sessionId_, promptId); } void _GenAiTextSession::stopChat() { serviceProxy_.stopChat(sessionId_); } void _GenAiTextSession::clearChatMessage() { serviceProxy_.clearChatMessage(sessionId_); } bool _GenAiTextSession::initServer() { if (!serviceProxy_.connectToServer()) { return serviceProxy_.reconnectServer(); } return true; } int _GenAiTextSession::initSession() { int errorCode = serviceProxy_.initEngine(chatModelConfig_, &sessionId_); if (errorCode != AISDK_NO_ERROR) { LOGE("Init session error: ", errorCode); } return errorCode; }libkysdk-genai-1.1.0.1/src/text/_genaitextsession.h000066400000000000000000000031101520575640000222230ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef GENAI_TEXT_SESSION_H #define GENAI_TEXT_SESSION_H #include #include "_chatmodelconfig.h" #include "chat.h" #include "config.h" #include "genainlpserviceproxy.h" class _GenAiTextSession { public: _GenAiTextSession(); int init(); void destroy(); void setResultCallback(const ChatResultCallback &callback, void *userData); void setChatModelConfig(const ChatModelConfig &config); void chat(const std::string &question); void chatWithHistoryMessages(const ChatMessage &message); void setChatSystemPrompt(const std::string &message); void setChatSystemPromptId(PromptId promptId); void stopChat(); void clearChatMessage(); private: bool initServer(); int initSession(); private: kyai::genai::nlp::GenAiNlpServiceProxy serviceProxy_; int sessionId_{0}; ChatModelConfig chatModelConfig_{}; }; #endif // GENAI_TEXT_SESSION_H libkysdk-genai-1.1.0.1/src/text/genainlpserver.cpp000066400000000000000000000040011520575640000220470ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "genainlpserver.h" namespace kyai::genai::nlp { const std::string& serverUnixPath = "unix:path=/tmp/.kylin-ai-runtime-unix/" + std::to_string(getuid()) + "/genai-nlp.sock"; GenAiNlpServer& GenAiNlpServer::getInstance() { static GenAiNlpServer instance{}; return instance; } GenAiNlpServer::~GenAiNlpServer() { destroy(); } GenAiNlpServer::GenAiNlpServer() {} void GenAiNlpServer::init() { init(serverUnixPath); } void GenAiNlpServer::init(const std::string& unixPath) { std::lock_guard locker(mutex_); if (connection_ != nullptr && !g_dbus_connection_is_closed(connection_)) { return; } GError* error{nullptr}; connection_ = g_dbus_connection_new_for_address_sync( unixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, // GDBusAuthObserver nullptr, // GCancellable &error); if (connection_ == nullptr) { g_printerr("Error connecting to D-Bus address %s: %s\n", unixPath.c_str(), error->message); g_error_free(error); } } void GenAiNlpServer::destroy() const { std::lock_guard locker(mutex_); if (connection_ != nullptr) { g_object_unref(connection_); } } } // namespace kyai::genai::nlp libkysdk-genai-1.1.0.1/src/text/genainlpserver.h000066400000000000000000000026071520575640000215260ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef GEN_AI_NLP_SERVER_H #define GEN_AI_NLP_SERVER_H #include #include #include "gennlpserviceglue.h" namespace kyai::genai::nlp { class GenAiNlpServer { public: static GenAiNlpServer &getInstance(); ~GenAiNlpServer(); void init(); [[nodiscard]] inline bool available() const { return connection_ != nullptr; } [[nodiscard]] inline GDBusConnection *getConnection() const { return connection_; } private: GenAiNlpServer(); void init(const std::string &unixPath); void destroy() const; private: GDBusConnection *connection_{nullptr}; mutable std::mutex mutex_; }; } // namespace kyai::genai::nlp #endif // GEN_AI_NLP_SERVER_H libkysdk-genai-1.1.0.1/src/text/genainlpserviceproxy.cpp000066400000000000000000000344561520575640000233240ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "genainlpserviceproxy.h" #include #include #include "_chatmodelconfig.h" #include "_chatresult.h" #include "logger.h" namespace kyai::genai::nlp { const char* objectPath = "/com/kylin/AiRuntime/GenAiNlp"; const char* interface = "com.kylin.AiRuntime.GenAiNlp"; const char* nlpResultSignal = "ChatNlpResult"; const int chatResultCallbackTimeoutMs = 60 * 60 * 1000; // 1 hour timeout namespace { ChatResult dissectChatResult(GVariant* parameters) { GVariantIter iter; g_variant_iter_init(&iter, parameters); GVariant* reason = g_variant_iter_next_value(&iter); GVariant* finishReason = g_variant_iter_next_value(&iter); GVariant* errorCode = g_variant_iter_next_value(&iter); GVariant* errorMessage = g_variant_iter_next_value(&iter); GVariant* isEnd = g_variant_iter_next_value(&iter); GVariant* reasoningContent = g_variant_iter_next_value(&iter); if (reason == nullptr or reasoningContent == nullptr or finishReason == nullptr or errorCode == nullptr or errorMessage == nullptr or isEnd == nullptr) { LOGE("chat result error: result is nullptr!"); if (reason) g_variant_unref(reason); if (reasoningContent) g_variant_unref(reasoningContent); if (finishReason) g_variant_unref(finishReason); if (errorCode) g_variant_unref(errorCode); if (errorMessage) g_variant_unref(errorMessage); if (isEnd) g_variant_unref(isEnd); return {}; } const char* resultReason = static_cast(g_variant_get_data(reason)); const char* resultReasoningContent = static_cast(g_variant_get_data(reasoningContent)); const char* resultFinishReason = static_cast(g_variant_get_data(finishReason)); const int* resultErrorCode = static_cast(g_variant_get_data(errorCode)); const char* resultErrorMessage = static_cast(g_variant_get_data(errorMessage)); const bool* resultIsEnd = static_cast(g_variant_get_data(isEnd)); if (resultReason == nullptr or resultReasoningContent == nullptr or resultFinishReason == nullptr or resultErrorCode == nullptr or resultErrorMessage == nullptr or resultIsEnd == nullptr) { LOGE("chat result error: result is nullptr!"); if (reason) g_variant_unref(reason); if (reasoningContent) g_variant_unref(reasoningContent); if (finishReason) g_variant_unref(finishReason); if (errorCode) g_variant_unref(errorCode); if (errorMessage) g_variant_unref(errorMessage); if (isEnd) g_variant_unref(isEnd); return {}; } ChatResult result{resultReason, resultReasoningContent, resultFinishReason, *resultErrorCode, resultErrorMessage, *resultIsEnd}; g_variant_unref(reason); g_variant_unref(reasoningContent); g_variant_unref(finishReason); g_variant_unref(errorCode); g_variant_unref(errorMessage); g_variant_unref(isEnd); return result; } std::string jsonToString(const Json::Value& value) { Json::StreamWriterBuilder builder; builder["emitUTF8"] = true; return Json::writeString(builder, value); } Json::Value stringToJson(const std::string& string) { Json::Value value; if (Json::Reader reader; reader.parse(string, value)) { return value; } else { return Json::objectValue; } } } // namespace GenAiNlpServiceProxy::~GenAiNlpServiceProxy() { if (not GenAiNlpServer::getInstance().available()) { g_printerr( "Error creating core speech server proxy: Server proxy " "connection is unavailable.\n"); return; } auto* connection = GenAiNlpServer::getInstance().getConnection(); if (subscriptionId_ != 0) { // 取消订阅 g_dbus_connection_signal_unsubscribe(connection, subscriptionId_); } removeCallbackTimerIfExists(); } bool GenAiNlpServiceProxy::connectToServer() { GenAiNlpServer::getInstance().init(); if (not GenAiNlpServer::getInstance().available()) { g_printerr( "Error creating core speech server proxy: Server proxy " "connection is unavailable.\n"); return false; } if (proxy_) { g_object_unref(proxy_); proxy_ = nullptr; } GError* error{nullptr}; auto* connection = GenAiNlpServer::getInstance().getConnection(); proxy_ = ai_runtime_gen_ai_nlp_service_proxy_new_sync( connection, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath, nullptr, &error); if (proxy_ == nullptr) { if (error) { g_printerr("Error creating text processor proxy %s: %s\n", objectPath, error->message); g_error_free(error); } return false; } g_dbus_proxy_set_default_timeout(G_DBUS_PROXY(proxy_), 2 * 60 * 60 * 1000); return true; } int GenAiNlpServiceProxy::initEngine(const ChatModelConfig& chatModelConfig, int* sessionId) { Json::Value chatModelConfigJson = modelConfigToJson(chatModelConfig); std::string config = jsonToString(chatModelConfigJson); int errorCode = AISDK_NO_ERROR; GError* error = nullptr; bool success = ai_runtime_gen_ai_nlp_service_call_init_sync( proxy_, config.c_str(), sessionId, &errorCode, nullptr, &error); if (not success) { if (error) { LOGE("Error calling init: {}:{}", error->code, error->message); g_error_free(error); return AISDK_RUNTIME_ERROR; } } if (*sessionId != -1) { connectChatResultSignals(*sessionId); reconnectAttempts_ = 0; } return errorCode; } void GenAiNlpServiceProxy::destroyEngine(int sessionId) { ai_runtime_gen_ai_nlp_service_call_destroy_sync(proxy_, sessionId, nullptr, nullptr); reconnectAttempts_ = 0; } void GenAiNlpServiceProxy::setChatResultCallback( const ChatResultCallback& callback, void* userData) { chatResultCallback_ = callback; userData_ = userData; } void GenAiNlpServiceProxy::setReconnectedCallback( const ReconnectedCallback& callback) { reconnectedCallback_ = std::move(callback); } void GenAiNlpServiceProxy::chat(int sessionId, const ChatModelConfig& chatModelConfig, const std::string& question) { if (question.empty()) { handleMessagesEmptyError(); return; } reconnectAttempts_ = 0; currentSessionId_ = sessionId; // Start the timeout timer startCallbackTimer(); Json::Value request = modelConfigToJson(chatModelConfig); request["question"] = question; std::string temp = jsonToString(request); ai_runtime_gen_ai_nlp_service_call_chat( proxy_, sessionId, temp.c_str(), nullptr, onChatFinishedCallback, this); } void GenAiNlpServiceProxy::handleErrorOccurred(int errorCode) { LOGE("Error occurred with code: {}", errorCode); removeCallbackTimerIfExists(); switch (errorCode) { case G_IO_ERROR_CLOSED: handleServerClosed(); break; case G_IO_ERROR_TIMED_OUT: handleChatTimeout(); break; default: handleGeneralError(); break; } } void GenAiNlpServiceProxy::handleServerClosed() { LOGE("Server closed unexpectedly."); if (chatResultCallback_) { ChatResult result{ "", "", "", AISDK_RUNTIME_ERROR, "Server closed unexpectedly.", true}; chatResultCallback_(&result, userData_); } if (reconnectServer()) { if (reconnectedCallback_) { reconnectedCallback_(); } } } void GenAiNlpServiceProxy::handleChatTimeout() { if (chatResultCallback_) { ChatResult result{ "", "", "", AISDK_MODEL_RUN_TIME_OUT, "Run model time out.", true}; chatResultCallback_(&result, userData_); } } void GenAiNlpServiceProxy::handleGeneralError() { if (chatResultCallback_) { ChatResult result{ "", "", "", AISDK_RUNTIME_ERROR, "General error occurred.", true}; chatResultCallback_(&result, userData_); } } void GenAiNlpServiceProxy::handleMessagesEmptyError() { if (chatResultCallback_) { ChatResult result{ "", "", "", NLP_PARAM_ERROR, "The input message is empty.", true}; chatResultCallback_(&result, userData_); }; } bool GenAiNlpServiceProxy::reconnectServer() { if (reconnectAttempts_ >= maxReconnectAttempts) { LOGE("Max reconnect attempts reached"); return false; } reconnectAttempts_++; LOGD("Reconnect attempt {}.", reconnectAttempts_); if (!connectToServer()) { LOGE("Failed to reconnect to server"); std::this_thread::sleep_for(std::chrono::seconds(1)); return reconnectServer(); } LOGI("Successfully reconnected to server."); return true; } void GenAiNlpServiceProxy::stopChat(int sessionId) { ai_runtime_gen_ai_nlp_service_call_stop_chat_sync(proxy_, sessionId, nullptr, nullptr); } void GenAiNlpServiceProxy::clearChatMessage(int sessionId) { ai_runtime_gen_ai_nlp_service_call_clear_chat_message_sync( proxy_, sessionId, nullptr, nullptr); } void GenAiNlpServiceProxy::setChatSystemPromptId(int sessionId, PromptId promptId) { ai_runtime_gen_ai_nlp_service_call_set_chat_system_prompt_id_sync( proxy_, sessionId, promptId, nullptr, nullptr); } void GenAiNlpServiceProxy::addSystemMessage(int sessionId, const std::string& message) { ai_runtime_gen_ai_nlp_service_call_add_system_message_sync( proxy_, sessionId, message.c_str(), nullptr, nullptr); } void GenAiNlpServiceProxy::chatWithHistoryMessages( int sessionId, const ChatModelConfig& chatModelConfig, const std::string& messages) { if (messages.empty()) { handleMessagesEmptyError(); return; } currentSessionId_ = sessionId; // Start the timeout timer startCallbackTimer(); Json::Value request = stringToJson(messages); request["top_k"] = chatModelConfig.topK_; request["model_name"] = chatModelConfig.name_; request["deploy_type"] = getModelConfigType(chatModelConfig); std::string temp = jsonToString(request); LOGD(temp); ai_runtime_gen_ai_nlp_service_call_chat_with_history_messages( proxy_, sessionId, temp.c_str(), nullptr, onChatFinishedCallback, this); } void GenAiNlpServiceProxy::connectChatResultSignals(int sessionId) { auto* connection = GenAiNlpServer::getInstance().getConnection(); std::string interfaceName = interface + std::to_string(sessionId); subscriptionId_ = g_dbus_connection_signal_subscribe( connection, nullptr, interfaceName.c_str(), nlpResultSignal, objectPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, onChatResultCallback, this, nullptr); } void GenAiNlpServiceProxy::onChatResultCallback( GDBusConnection* connection, const gchar* senderName, const gchar* objectPath, const gchar* interfaceName, const gchar* signalName, GVariant* parameters, gpointer userData) { auto* proxy = static_cast(userData); // Reset the timeout timer since we received a callback proxy->resetCallbackTimer(); if (proxy->chatResultCallback_ != nullptr) { auto result = dissectChatResult(parameters); proxy->chatResultCallback_(&result, proxy->userData_); } else { LOGE("chat result callback is not set!"); } } void GenAiNlpServiceProxy::onChatFinishedCallback(GObject* sourceObject, GAsyncResult* res, gpointer userData) { GError* error{nullptr}; auto* proxy = static_cast(userData); proxy->removeCallbackTimerIfExists(); bool result = ai_runtime_gen_ai_nlp_service_call_chat_finish( (AiRuntimeGenAiNlpService*)sourceObject, res, &error); if (not result) { if (error == nullptr) { g_printerr("Error calling chat: Unknown error\n"); } else { g_printerr("Error calling chat: %s\n", error->message); proxy->handleErrorOccurred(error->code); g_error_free(error); } } } void GenAiNlpServiceProxy::startCallbackTimer() { removeCallbackTimerIfExists(); // Start a new timer timeoutId_ = g_timeout_add( chatResultCallbackTimeoutMs, [](gpointer data) -> gboolean { auto* proxy = static_cast(data); proxy->handleCallbackTimeout(); proxy->timeoutId_ = 0; // Reset the ID since the source is removed return G_SOURCE_REMOVE; // Don't repeat the timeout }, this); } void GenAiNlpServiceProxy::removeCallbackTimerIfExists() { if (timeoutId_ > 0) { g_source_remove(timeoutId_); timeoutId_ = 0; } } void GenAiNlpServiceProxy::resetCallbackTimer() { // Reset the timer by starting a new one startCallbackTimer(); } void GenAiNlpServiceProxy::handleCallbackTimeout() { LOGE("NLP result callback timeout after 2 minutes"); stopChat(currentSessionId_); if (chatResultCallback_) { ChatResult result{"", "", "", AISDK_MODEL_RUN_TIME_OUT, "NLP result callback timeout after 2 minutes", true}; chatResultCallback_(&result, userData_); } } } // namespace kyai::genai::nlp libkysdk-genai-1.1.0.1/src/text/genainlpserviceproxy.h000066400000000000000000000063561520575640000227670ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef GENAI_NLP_SERVICE_PROXY_H #define GENAI_NLP_SERVICE_PROXY_H #include #include #include "_chatmodelconfig.h" #include "chat.h" #include "genainlpserver.h" namespace kyai::genai::nlp { using ReconnectedCallback = std::function; class GenAiNlpServiceProxy { public: ~GenAiNlpServiceProxy(); bool connectToServer(); bool reconnectServer(); int initEngine(const ChatModelConfig &chatModelConfig, int *sessionId); void destroyEngine(int sessionId); void setChatResultCallback(const ChatResultCallback &callback, void *userData); void setReconnectedCallback(const ReconnectedCallback &callback); void chat(int sessionId, const ChatModelConfig &chatModelConfig, const std::string &question); void stopChat(int sessionId); void clearChatMessage(int sessionId); void setChatSystemPromptId(int sessionId, PromptId promptId); void addSystemMessage(int sessionId, const std::string &message); void chatWithHistoryMessages(int sessionId, const ChatModelConfig &chatModelConfig, const std::string &messages); private: void connectChatResultSignals(int sessionId); static void onChatResultCallback(GDBusConnection *connection, const gchar *senderName, const gchar *objectPath, const gchar *interfaceName, const gchar *signalName, GVariant *parameters, gpointer userData); static void onChatFinishedCallback(GObject *sourceObject, GAsyncResult *res, gpointer userData); void handleErrorOccurred(int errorCode); void handleServerClosed(); void handleChatTimeout(); void handleGeneralError(); void handleMessagesEmptyError(); void startCallbackTimer(); void removeCallbackTimerIfExists(); void resetCallbackTimer(); void handleCallbackTimeout(); private: ChatResultCallback chatResultCallback_{nullptr}; ReconnectedCallback reconnectedCallback_{nullptr}; void *userData_{nullptr}; AiRuntimeGenAiNlpService *proxy_{nullptr}; GenAiNlpServer *genNlpServer_{nullptr}; int currentSessionId_{0}; guint subscriptionId_{0}; guint timeoutId_{0}; int reconnectAttempts_{0}; static constexpr int maxReconnectAttempts = 10; }; } // namespace kyai::genai::nlp #endif // GENAI_NLP_SERVICE_PROXY_H libkysdk-genai-1.1.0.1/src/vision/000077500000000000000000000000001520575640000166475ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/src/vision/_genaiimagesession.cpp000066400000000000000000000045711520575640000232130ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "_genaiimagesession.h" namespace kylin { namespace genai { namespace vision { _GenAiImageSession::_GenAiImageSession() { serviceProxy_.setReconnectedCallback([this] { initSession(); if (imageConfig_) { serviceProxy_.setImageConfig(sessionId_, imageConfigToJson(*imageConfig_)); } }); } int _GenAiImageSession::init() { if (!initServer()) { return AiSdkCommonErrorCode::AISDK_RUNTIME_ERROR; } return initSession(); } void _GenAiImageSession::setImageConfig(_ImageConfig *config) { imageConfig_ = config; serviceProxy_.setImageConfig(sessionId_, imageConfigToJson(*config)); } void _GenAiImageSession::setImageResultCallback( VisionImageResultCallback callback, void *userData) { serviceProxy_.setImageResultCallback(callback, userData); } const char **_GenAiImageSession::getSupportedImageStyle(int *number) { return serviceProxy_.getSupportedImageStyle(sessionId_, number); } const ImageSize *_GenAiImageSession::getSupportedImageSize(int *number) { return serviceProxy_.getSupportedImageSize(sessionId_, number); } const int _GenAiImageSession::getSupportedImageNumber() { return serviceProxy_.getSupportedImageNumber(sessionId_); } void _GenAiImageSession::generateImageAsync(const char *prompt) { serviceProxy_.generateImageAsync(sessionId_, prompt); } bool _GenAiImageSession::initServer() { if (!serviceProxy_.connectToServer()) { return serviceProxy_.reconnectServer(); } return true; } int _GenAiImageSession::initSession() { return serviceProxy_.initEngine(&sessionId_); } } // namespace vision } // namespace genai } // namespace kylin libkysdk-genai-1.1.0.1/src/vision/_genaiimagesession.h000066400000000000000000000030761520575640000226570ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _GENAIIMAGE_ #define _GENAIIMAGE_ #include "_imageconfig.h" #include "error.h" #include "genaivisionserviceproxy.h" #include "imageresult.h" namespace kylin { namespace genai { namespace vision { class _GenAiImageSession { public: _GenAiImageSession(); int init(); void setImageConfig(_ImageConfig *config); void setImageResultCallback(VisionImageResultCallback callback, void *userData); const char **getSupportedImageStyle(int *number); const ImageSize *getSupportedImageSize(int *number); const int getSupportedImageNumber(); void generateImageAsync(const char *prompt); private: bool initServer(); int initSession(); private: _ImageConfig *imageConfig_{nullptr}; GenAiVisionServiceProxy serviceProxy_; int sessionId_{0}; }; } // namespace vision } // namespace genai } // namespace kylin #endif libkysdk-genai-1.1.0.1/src/vision/_imageconfig.h000066400000000000000000000017331520575640000214330ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _IMAGECONFIG_H #define _IMAGECONFIG_H #include #include #include struct _ImageConfig { int width = 0; int height = 0; int number = 0; std::string style; }; std::string imageConfigToJson(const _ImageConfig &config); #endif libkysdk-genai-1.1.0.1/src/vision/_imageresult.cpp000066400000000000000000000041241520575640000220340ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "_imageresult.h" #include "imageresult.h" ImageFormat image_result_get_format(VisionImageResult *image_result) { if (image_result == nullptr) { return ImageFormat::IMAGE_FORMAT_UNKNOWN; } return image_result->format; } ImageSize image_result_get_size(VisionImageResult *image_result) { if (image_result == nullptr) { return ImageSize{-1, -1}; } return ImageSize{image_result->width, image_result->height}; } int image_result_get_total(VisionImageResult *image_result) { if (image_result == nullptr) { return -1; } return image_result->total; } int image_result_get_index(VisionImageResult *image_result) { if (image_result == nullptr) { return -1; } return image_result->index; } const uint8_t *image_result_get_data(VisionImageResult *image_result, int *data_length) { if (image_result == nullptr || data_length == nullptr) { return nullptr; } *data_length = image_result->data.size(); return image_result->data.data(); } int image_result_get_error_code(VisionImageResult *image_result) { if (image_result == nullptr) { return -1; } return image_result->errorCode; } const char *image_result_get_error_message(VisionImageResult *image_result) { if (image_result == nullptr) { return nullptr; } return image_result->errorMessage.c_str(); } libkysdk-genai-1.1.0.1/src/vision/_imageresult.h000066400000000000000000000020251520575640000214770ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _IMAGERESULT_H_ #define _IMAGERESULT_H_ #include #include #include #include "imageformat.h" struct _VisionImageResult { ImageFormat format; int width{0}; int height{0}; int total{0}; int index{-1}; std::vector data; int errorCode{0}; std::string errorMessage; }; #endif libkysdk-genai-1.1.0.1/src/vision/genaivisionserviceproxy.cpp000066400000000000000000000437601520575640000243630ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "genaivisionserviceproxy.h" #include #include "_imageresult.h" #include "logger.h" namespace kylin { namespace genai { namespace vision { const std::string serverUnixPath = "unix:path=/tmp/.kylin-ai-runtime-unix/" + std::to_string(getuid()) + "/genai-vision.sock"; const char* objectPath = "/com/kylin/AiRuntime/GenAiVision"; const char* interface = "com.kylin.AiRuntime.GenAiVision"; const char* visionResultSignal = "GenAiVisionResult"; const int resultCallbackTimeoutMs = 3 * 60 * 1000; std::vector base64Decode(const std::string& input) { gsize decodedLength{}; guchar* decodedData = g_base64_decode(input.c_str(), &decodedLength); std::vector result(decodedData, decodedData + decodedLength); g_free(decodedData); return result; } _VisionImageResult dissectImageResult(GVariant* parameters) { GVariantIter iter; g_variant_iter_init(&iter, parameters); GVariant* imageData = g_variant_iter_next_value(&iter); GVariant* format = g_variant_iter_next_value(&iter); GVariant* height = g_variant_iter_next_value(&iter); GVariant* width = g_variant_iter_next_value(&iter); GVariant* total = g_variant_iter_next_value(&iter); GVariant* index = g_variant_iter_next_value(&iter); GVariant* errorCode = g_variant_iter_next_value(&iter); GVariant* errorMsg = g_variant_iter_next_value(&iter); if (!imageData || !format || !height || !width || !total || !index || !errorCode || !errorMsg) { g_variant_unref(imageData); g_variant_unref(format); g_variant_unref(height); g_variant_unref(width); g_variant_unref(total); g_variant_unref(index); g_variant_unref(errorCode); g_variant_unref(errorMsg); LOGE("Generate image result error: image data is nullptr!"); return _VisionImageResult{}; } char* resultImageBase64Data = (char*)g_variant_get_data(imageData); int* resultFormat = (int*)g_variant_get_data(format); int* resultHeight = (int*)g_variant_get_data(height); int* resultWidth = (int*)g_variant_get_data(width); int* resultTotal = (int*)g_variant_get_data(total); int* resultIndex = (int*)g_variant_get_data(index); int* resultErrorCode = (int*)g_variant_get_data(errorCode); char* resultErrorMsg = (char*)g_variant_get_data(errorMsg); if (!resultImageBase64Data || !resultFormat || !resultHeight || !resultWidth || !resultTotal || !resultIndex || !resultErrorCode || !resultErrorMsg) { LOGE("Generate image result error: image data is nullptr!"); g_variant_unref(imageData); g_variant_unref(format); g_variant_unref(height); g_variant_unref(width); g_variant_unref(total); g_variant_unref(index); g_variant_unref(errorCode); g_variant_unref(errorMsg); return _VisionImageResult{}; } LOGD("prompt image result:"); LOGD("format", *resultFormat); LOGD("width", *resultWidth); LOGD("height", *resultHeight); LOGD("total", *resultTotal); LOGD("index", *resultIndex); LOGD("error code", *resultErrorCode); LOGD("error message", resultErrorMsg); std::vector theImageData = base64Decode(resultImageBase64Data); _VisionImageResult visionImageResult{ImageFormat(*resultFormat), *resultWidth, *resultHeight, *resultTotal, *resultIndex, theImageData, *resultErrorCode, resultErrorMsg}; g_variant_unref(imageData); g_variant_unref(format); g_variant_unref(height); g_variant_unref(width); g_variant_unref(total); g_variant_unref(index); g_variant_unref(errorCode); g_variant_unref(errorMsg); return visionImageResult; } GenAiVisionServer& GenAiVisionServer::getInstance() { static GenAiVisionServer instance{}; return instance; } GenAiVisionServer::~GenAiVisionServer() { destroy(); } void GenAiVisionServer::init(const std::string& unixPath) { std::lock_guard locker(mutex_); if (connection_ != nullptr && !g_dbus_connection_is_closed(connection_)) { return; } GError* error = nullptr; connection_ = g_dbus_connection_new_for_address_sync( unixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT, nullptr, /* GDBusAuthObserver */ nullptr, /* GCancellable */ &error); if (connection_ == nullptr) { g_printerr("Error connecting to D-Bus address %s: %s\n", unixPath.c_str(), error->message); g_error_free(error); return; } } void GenAiVisionServer::init() { init(serverUnixPath); } void GenAiVisionServer::destroy() { std::lock_guard locker(mutex_); if (connection_ != nullptr) { g_object_unref(connection_); } } GenAiVisionServiceProxy::~GenAiVisionServiceProxy() { delete[] stylesArray_; stylesArray_ = nullptr; delete[] sizesArray_; sizesArray_ = nullptr; } bool GenAiVisionServiceProxy::connectToServer() { GenAiVisionServer::getInstance().init(); if (!GenAiVisionServer::getInstance().available()) { g_printerr( "Error creating core speech server proxy: Server proxy " "connection is unavailable.\n"); return false; } if (proxy_) { g_object_unref(proxy_); proxy_ = nullptr; } GError* error{nullptr}; auto* connection = GenAiVisionServer::getInstance().getConnection(); proxy_ = ai_runtime_gen_ai_vision_service_proxy_new_sync( connection, G_DBUS_PROXY_FLAGS_NONE, nullptr, objectPath, nullptr, &error); if (proxy_ == nullptr) { if (error) { g_printerr("Error creating text processor proxy %s: %s\n", objectPath, error->message); g_error_free(error); } return false; } g_dbus_proxy_set_default_timeout(G_DBUS_PROXY(proxy_), resultCallbackTimeoutMs); return true; } bool GenAiVisionServiceProxy::reconnectServer() { if (reconnectAttempts_ >= maxReconnectAttempts) { LOGE("Max reconnect attempts reached"); return false; } reconnectAttempts_++; LOGD("Reconnect attempt {}.", reconnectAttempts_); if (!connectToServer()) { LOGE("Failed to reconnect to server"); std::this_thread::sleep_for(std::chrono::seconds(1)); return reconnectServer(); } LOGI("Successfully reconnected to server."); return true; } void GenAiVisionServiceProxy::setImageResultCallback( VisionImageResultCallback callback, void* userData) { visionImageResultCallback_ = callback; visionImageResultUserData_ = userData; } void GenAiVisionServiceProxy::setReconnectedCallback( const ReconnectedCallback& callback) { reconnectedCallback_ = std::move(callback); } int GenAiVisionServiceProxy::initEngine(int* sessionId) { int errorCode = AISDK_NO_ERROR; GError* error{nullptr}; if (!proxy_) { LOGE("Failed to init engine: AiRuntimeGenAiVisionService is null!"); return -1; } bool success = ai_runtime_gen_ai_vision_service_call_init_sync( proxy_, sessionId, &errorCode, nullptr, nullptr); if (!success) { if (error) { LOGE("Error calling init: {}:{}", error->code, error->message); g_error_free(error); return AISDK_RUNTIME_ERROR; } } if (*sessionId != -1) { connectImageResultSignals(*sessionId); } return errorCode; } void GenAiVisionServiceProxy::setImageConfig(int sessionId, const std::string& config) { if (!proxy_) { LOGE( "Failed to set image config: AiRuntimeGenAiVisionService is null!"); return; } bool ret = ai_runtime_gen_ai_vision_service_call_set_image_config_sync( proxy_, sessionId, config.c_str(), nullptr, nullptr); if (!ret) { LOGE("GenAiVisionServiceProxy: error to set image config"); } } const char** GenAiVisionServiceProxy::getSupportedImageStyle(int sessionId, int* number) { if (!number) { LOGE("Failed to get supported image style: number is null!"); return {}; } gchar* imageStyle = nullptr; GError* error = nullptr; if (!proxy_) { LOGE( "Failed to get supported image style: AiRuntimeGenAiVisionService " "is null!"); return {}; } bool ret = ai_runtime_gen_ai_vision_service_call_get_supported_image_style_sync( proxy_, sessionId, &imageStyle, nullptr, &error); if (!imageStyle) { LOGE("Failed to get supported image size: imageStyle is null!"); return {}; } std::vector styleVector = getImageStyleArryFromJsonString(imageStyle); *number = styleVector.size(); if (stylesArray_) { delete[] stylesArray_; stylesArray_ = nullptr; } stylesArray_ = new const char*[*number]; for (int i = 0; i < *number; ++i) { stylesArray_[i] = styleVector[i].c_str(); } return stylesArray_; } const ImageSize* GenAiVisionServiceProxy::getSupportedImageSize(int sessionId, int* number) { if (!number) { LOGE("Failed to get supported image size: number is null!"); return {}; } gchar* imageSize = nullptr; GError* error = nullptr; if (!proxy_) { LOGE( "Failed to get supported image size: AiRuntimeGenAiVisionService " "is null!"); return {}; } bool ret = ai_runtime_gen_ai_vision_service_call_get_supported_image_size_sync( proxy_, sessionId, &imageSize, nullptr, &error); if (!imageSize) { LOGE("Failed to get supported image size: imageSize is null!"); return {}; } std::vector sizeVector = getImageSizeArryFromJsonString(imageSize); *number = sizeVector.size(); if (sizesArray_) { delete[] sizesArray_; sizesArray_ = nullptr; } sizesArray_ = new ImageSize[*number]; for (int i = 0; i < *number; ++i) { sizesArray_[i].width = sizeVector[i].width; sizesArray_[i].height = sizeVector[i].height; } return sizesArray_; } const int GenAiVisionServiceProxy::getSupportedImageNumber(int sessionId) { gint number; GError* error = nullptr; if (!proxy_) { LOGE( "Failed to get supported image number: AiRuntimeGenAiVisionService " "is null!"); return 0; } bool ret = ai_runtime_gen_ai_vision_service_call_get_supported_image_number_sync( proxy_, sessionId, &number, nullptr, &error); if (!ret && error) { LOGE("Failed to get the number of supported images:", error->message); return 0; } return number; } void GenAiVisionServiceProxy::generateImageAsync(int sessionId, const char* prompt) { if (!proxy_) { LOGE("Failed to generate image: AiRuntimeGenAiVisionService is null!"); _VisionImageResult errorResult{ ImageFormat::IMAGE_FORMAT_UNKNOWN, 0, 0, 0, 0, {}, AiSdkCommonErrorCode::AISDK_RUNTIME_ERROR, ""}; if (visionImageResultCallback_) { visionImageResultCallback_(&errorResult, visionImageResultUserData_); } return; } isStopped_ = false; reconnectAttempts_ = 0; currentSessionId_ = sessionId; ai_runtime_gen_ai_vision_service_call_generate_image( proxy_, sessionId, prompt, nullptr, onImageGenerationFinishedCallback, this); } void GenAiVisionServiceProxy::connectImageResultSignals(int sessionId) { auto* connection = GenAiVisionServer::getInstance().getConnection(); std::string interfaceName = interface + std::to_string(sessionId); g_dbus_connection_signal_subscribe( connection, nullptr, interfaceName.c_str(), visionResultSignal, objectPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, onImageResult, this, nullptr); } void GenAiVisionServiceProxy::onImageResult( GDBusConnection* connection, const gchar* senderName, const gchar* objectPath, const gchar* interfaceName, const gchar* signalName, GVariant* parameters, gpointer userData) { auto* proxy = static_cast(userData); if (proxy->isStopped_) { return; } if (!proxy->visionImageResultCallback_) { LOGE("GenAiVisionServiceProxy: vision image callback is not set!"); return; } auto result = dissectImageResult(parameters); proxy->visionImageResultCallback_(&result, proxy->visionImageResultUserData_); } void GenAiVisionServiceProxy::onImageGenerationFinishedCallback( GObject* sourceObject, GAsyncResult* res, gpointer userData) { GError* error{nullptr}; auto* proxy = static_cast(userData); bool result = ai_runtime_gen_ai_vision_service_call_generate_image_finish( (AiRuntimeGenAiVisionService*)sourceObject, res, &error); if (!result) { if (error == nullptr) { g_printerr("Error calling image generation: Unknown error\n"); } else { g_printerr("Error calling image generation: %s\n", error->message); proxy->handleErrorOccurred(error->code); g_error_free(error); } } } void GenAiVisionServiceProxy::stopImageGeneration() { GError* error{nullptr}; if (proxy_) { ai_runtime_gen_ai_vision_service_call_stop_image_generation( proxy_, currentSessionId_, nullptr, nullptr, &error); if (error) { LOGE("Error stopping image generation:", error->message); g_error_free(error); } } else { LOGE( "Failed to stop image generation: AiRuntimeGenAiVisionService is " "null!"); } isStopped_ = true; } void GenAiVisionServiceProxy::handleErrorOccurred(int errorCode) { LOGE("Error occurred with code: {}", errorCode); switch (errorCode) { case G_IO_ERROR_CLOSED: handleServerClosed(); break; case G_IO_ERROR_TIMED_OUT: handleResultTimeout(); break; default: handleGeneralError(); break; } } void GenAiVisionServiceProxy::handleServerClosed() { LOGE("Server closed unexpectedly."); if (visionImageResultCallback_) { _VisionImageResult result{ .errorCode = AISDK_RUNTIME_ERROR, .errorMessage = "Server closed unexpectedly."}; visionImageResultCallback_(&result, visionImageResultUserData_); } if (reconnectServer()) { if (reconnectedCallback_) { reconnectedCallback_(); } } } void GenAiVisionServiceProxy::handleResultTimeout() { if (visionImageResultCallback_) { _VisionImageResult result{.errorCode = AISDK_MODEL_RUN_TIME_OUT, .errorMessage = "Run model time out."}; visionImageResultCallback_(&result, visionImageResultUserData_); } stopImageGeneration(); } void GenAiVisionServiceProxy::handleGeneralError() { if (visionImageResultCallback_) { _VisionImageResult result{.errorCode = AISDK_RUNTIME_ERROR, .errorMessage = "General error occurred."}; visionImageResultCallback_(&result, visionImageResultUserData_); } } bool GenAiVisionServiceProxy::parseJson(const std::string& params, Json::Value& root) const { Json::Reader reader; bool parsingSuccessful = reader.parse(params, root); if (!parsingSuccessful) { LOGE("Failed to parse JSON:", reader.getFormattedErrorMessages()); return false; } return true; } std::vector GenAiVisionServiceProxy::getImageStyleArryFromJsonString( const std::string& params) { Json::Value root; if (!parseJson(params, root)) { return {}; } if (!root.isArray()) { LOGE("Input is not a JSON array"); return {}; } std::vector result; for (const auto& value : root) { result.push_back(value.asString()); } return result; } std::vector GenAiVisionServiceProxy::getImageSizeArryFromJsonString( const std::string& params) const { Json::Value root; if (!parseJson(params, root)) { return {}; } if (!root.isArray()) { LOGE("Input is not a JSON array"); return {}; } std::vector result; for (const auto& value : root) { std::string ratio = value.asString(); size_t pos = ratio.find('x'); if (pos == std::string::npos) { LOGE("Invalid size format:", ratio); continue; } int width = std::stoi(ratio.substr(0, pos)); int height = std::stoi(ratio.substr(pos + 1)); result.push_back(ImageSize{width, height}); } return result; } } // namespace vision } // namespace genai } // namespace kylin libkysdk-genai-1.1.0.1/src/vision/genaivisionserviceproxy.h000066400000000000000000000074061520575640000240250ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _GENAI_VISION_SERVICE_PROXY_H_ #define _GENAI_VISION_SERVICE_PROXY_H_ #include #include #include #include #include #include #include "error.h" #include "genaivisionserviceglue.h" #include "imageresult.h" namespace kylin { namespace genai { namespace vision { using ReconnectedCallback = std::function; class GenAiVisionServer { public: static GenAiVisionServer &getInstance(); ~GenAiVisionServer(); void init(); bool available() const { return connection_ != nullptr; } GDBusConnection *getConnection() const { return connection_; } private: void init(const std::string &unixPath); void destroy(); private: GDBusConnection *connection_{nullptr}; mutable std::mutex mutex_; }; class GenAiVisionServiceProxy { public: ~GenAiVisionServiceProxy(); bool connectToServer(); bool reconnectServer(); void setImageResultCallback(VisionImageResultCallback callback, void *userData); void setReconnectedCallback(const ReconnectedCallback &callback); int initEngine(int *sessionId); void setImageConfig(int sessionId, const std::string &config); const char **getSupportedImageStyle(int sessionId, int *number); const ImageSize *getSupportedImageSize(int sessionId, int *number); const int getSupportedImageNumber(int sessionId); void generateImageAsync(int sessionId, const char *prompt); private: void connectImageResultSignals(int sessionId); static void onImageResult(GDBusConnection *connection, const gchar *senderName, const gchar *objectPath, const gchar *interfaceName, const gchar *signalName, GVariant *parameters, gpointer userData); static void onImageGenerationFinishedCallback(GObject *sourceObject, GAsyncResult *res, gpointer userData); void stopImageGeneration(); void handleErrorOccurred(int errorCode); void handleServerClosed(); void handleResultTimeout(); void handleGeneralError(); bool parseJson(const std::string ¶ms, Json::Value &root) const; std::vector getImageStyleArryFromJsonString( const std::string ¶ms); std::vector getImageSizeArryFromJsonString( const std::string ¶ms) const; private: VisionImageResultCallback visionImageResultCallback_{nullptr}; ReconnectedCallback reconnectedCallback_{nullptr}; void *visionImageResultUserData_{nullptr}; AiRuntimeGenAiVisionService *proxy_{nullptr}; GenAiVisionServer *genaiVisionServer_{nullptr}; const char **stylesArray_{nullptr}; ImageSize *sizesArray_{nullptr}; int currentSessionId_{0}; bool isStopped_{false}; guint timeoutId_{0}; int reconnectAttempts_{0}; static constexpr int maxReconnectAttempts = 10; }; } // namespace vision } // namespace genai } // namespace kylin #endif libkysdk-genai-1.1.0.1/src/vision/image.cpp000066400000000000000000000060061520575640000204370ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "image.h" #include "_genaiimagesession.h" GenAiImageSession *genai_image_create_session() { auto *session = new kylin::genai::vision::_GenAiImageSession(); return (GenAiImageSession *)session; } void genai_image_destroy_session(GenAiImageSession **session) { if (session == nullptr) { return; } if (*session == nullptr) { return; } delete (kylin::genai::vision::_GenAiImageSession *)*session; *session = nullptr; } int genai_image_init_session(GenAiImageSession *session) { if (session == nullptr) { return AISDK_INVALID_SESSION; } return ((kylin::genai::vision::_GenAiImageSession *)session)->init(); } void genai_image_set_config(GenAiImageSession *session, ImageConfig *config) { if (session == nullptr || config == nullptr) { return; } ((kylin::genai::vision::_GenAiImageSession *)session) ->setImageConfig(config); } void genai_image_result_set_callback(GenAiImageSession *session, ImageResultCallback callback, void *user_data) { if (session == nullptr) { return; } ((kylin::genai::vision::_GenAiImageSession *)session) ->setImageResultCallback(callback, user_data); } const char **genai_image_get_supported_image_style(GenAiImageSession *session, int *number) { if (session == nullptr) { return nullptr; } return ((kylin::genai::vision::_GenAiImageSession *)session) ->getSupportedImageStyle(number); } const ImageSize *genai_image_get_supported_image_size( GenAiImageSession *session, int *number) { if (session == nullptr) { return nullptr; } return ((kylin::genai::vision::_GenAiImageSession *)session) ->getSupportedImageSize(number); } int genai_image_get_supported_image_number(GenAiImageSession *session) { if (session == nullptr) { return -1; } return ((kylin::genai::vision::_GenAiImageSession *)session) ->getSupportedImageNumber(); } void genai_image_generate_image_async(GenAiImageSession *session, const char *prompt) { if (session == nullptr) { return; } ((kylin::genai::vision::_GenAiImageSession *)session) ->generateImageAsync(prompt); } libkysdk-genai-1.1.0.1/src/vision/imageconfig.cpp000066400000000000000000000035141520575640000216260ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include "imageconfig.h" #include #include "_imageconfig.h" std::string imageConfigToJson(const _ImageConfig &config) { Json::Value root; root["width"] = config.width; root["height"] = config.height; root["number"] = config.number; root["style"] = config.style; // 序列化 JSON 对象 Json::FastWriter writer; return writer.write(root); } ImageConfig *image_config_create() { ImageConfig *config = new _ImageConfig(); return config; } void image_config_destroy(ImageConfig **config) { if (config == nullptr) { return; } delete *config; *config = nullptr; } void image_config_set_generation_number(ImageConfig *config, int number) { if (config == nullptr) { return; } config->number = number; } void image_config_set_style(ImageConfig *config, const char *style) { if (config == nullptr || style == nullptr) { return; } config->style = style; } void image_config_set_size(ImageConfig *config, ImageSize image_size) { if (config == nullptr) { return; } config->height = image_size.height; config->width = image_size.width; } libkysdk-genai-1.1.0.1/tests/000077500000000000000000000000001520575640000157135ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/tests/CMakeLists.txt000066400000000000000000000017711520575640000204610ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.5) project(kysdk-genai-nlp-test LANGUAGES CXX C) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CMAKE_SKIP_RPATH ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # jsoncpp find_package(jsoncpp REQUIRED) # openssl find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) # package config find_package(PkgConfig REQUIRED) pkg_check_modules(GIO REQUIRED gio-unix-2.0) include_directories(${GIO_INCLUDE_DIRS}) pkg_check_modules(KYLIN_AI_CONFIG kyai-config) include_directories(${KYLIN_AI_CONFIG_INCLUDE_DIRS}) # protocol find_package(KylinAiProto REQUIRED) kylin_ai_generate_gdbus_proto_code(COMMON_PROTO_FILES gennlpservice) # inner include_directories(${CMAKE_SOURCE_DIR}/include) set(LIBRARIES pthread jsoncpp ${OPENSSL_LIBRARIES} ${GIO_LIBRARIES} ${KYLIN_AI_CONFIG_LIBRARIES} ) add_executable(testGenAiNlpApi testGenAiNlp.cpp ${SERVICE_SOURCES} ${COMMON_PROTO_FILES}) target_link_libraries(testGenAiNlpApi ${LIBRARIES}) libkysdk-genai-1.1.0.1/tests/testGenAiNlp.cpp000066400000000000000000000421661520575640000207650ustar00rootroot00000000000000/* * Copyright 2024 KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #include #include #include #include #include #include #include #include #include #include "logger.h" // #include "chat.h" #include "config.h" #include "error.h" #include "result.h" using namespace std::chrono_literals; std::string getMessage(const char *src) { if (src == nullptr) { return "nullptr"; } return src; } void callback(ChatResult *result, void *user_data) { auto getBool = [](bool value) { return value ? "true" : "false"; }; LOGI("reasoning message is ", chat_result_get_reasoning_message(result)); LOGI("assistant message is ", chat_result_get_assistant_message(result)); LOGI("finish reason message is ", chat_result_get_finish_reason_message(result)); if (chat_result_get_error_code(result)) { LOGI("error code is ", chat_result_get_error_code(result)); LOGI("error message is ", chat_result_get_error_message(result)); } LOGI("is_end is ", getBool(chat_result_get_is_end(result))); if (user_data != nullptr) { int *a = static_cast(user_data); LOGI(*a); } } void test01_Chat() { ChatModelConfig *config = chat_model_config_create(); chat_model_config_set_name(config, "百度-ERNIE-Bot-4"); chat_model_config_set_top_k(config, 0.5); chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud); GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, config); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } int a = 100; genai_text_result_set_callback(session, callback, &a); genai_text_chat_async(session, "一加一等于几"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, &config, pMainLoop] { while (std::getchar() != '\n') { } genai_text_chat_async(session, "你说的不对"); while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); chat_model_config_destroy(&config); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test02_ChatHistoryMessages() { ChatModelConfig *config = chat_model_config_create(); chat_model_config_set_name(config, ""); chat_model_config_set_top_k(config, 1.25); chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud); GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, config); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); ChatMessage *chatMessage = chat_message_create(); chat_message_add_system_message(chatMessage, ""); chat_message_add_user_message(chatMessage, "一加一等于几"); chat_message_add_assistant_message(chatMessage, "这是一个非常基础的数学问题," "、涉及到的是加法运算。题目问" "的是1+1等于几。\n\n在数学中," "加法是一种基本的运算方式,表" "示两个数量的和。当我们把两个1" "加在一起时,就是在计算这两个" "数量的总和。\n\n所以,1 + 1 =" " 2。\n\n因此,答案是2。这个问" "题非常直接,没有涉及到复杂的" "数学概念或技巧,只需要理解加" "法的基本定义即可。"); chat_message_add_user_message(chatMessage, "你说的不对"); genai_text_chat_with_history_messages_async(session, chatMessage); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, &config, &chatMessage, pMainLoop] { while (std::getchar() != '\n') { } chat_message_destroy(&chatMessage); genai_text_stop_chat(session); genai_text_destroy_session(&session); chat_model_config_destroy(&config); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test03_ClearChatMessage() { ChatModelConfig *config = chat_model_config_create(); chat_model_config_set_name(config, "百度-ERNIE-Bot-4"); chat_model_config_set_top_k(config, 1.25); chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud); GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, config); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); genai_text_chat_async(session, "一加一等于几"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, &config, pMainLoop] { while (std::getchar() != '\n') { } genai_text_clear_chat_history_messages(session); while (std::getchar() != '\n') { } genai_text_chat_async(session, "你说的不对"); while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); chat_model_config_destroy(&config); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test04_SetModelConfig() { ChatModelConfig *config = chat_model_config_create(); chat_model_config_set_name(config, "百度-ERNIE-Bot-4"); chat_model_config_set_top_k(config, 1.25); chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud); GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, config); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); genai_text_chat_async(session, "一加一等于几"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, &config, pMainLoop] { while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); chat_model_config_destroy(&config); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test05_SetChatSystemPrompt() { GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, nullptr); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); genai_text_set_chat_system_prompt(session, "汉英互译"); genai_text_chat_async(session, "你是谁"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, pMainLoop] { while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test06_GenerateContent() { GenAiTextSession *session = genai_text_create_session(); int errorCode = genai_text_init_session(session); genai_text_set_model_config(session, nullptr); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); genai_text_generate_content_async(session, "今天天气不错"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, pMainLoop] { while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void ChatSystemPromptId(PromptId promptId, const std::string &question) { GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, nullptr); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } genai_text_result_set_callback(session, callback, nullptr); genai_text_set_chat_system_prompt_id(session, promptId); genai_text_chat_async(session, question.c_str()); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, pMainLoop] { while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test07_ChatSystemPromptId_SUMMARY() { ChatSystemPromptId( SUMMARY, "大模型是人工智能领域的热门研究方向。专家认为,人工智能进" "入产业级大模型时代。大模型将是未来一段时间科技领域里面最重要的事情之一" "。大模型将开启人工智能的“大一统时代”。"); } void test08_ChatSystemPromptId_TEXT_EXPANSION() { ChatSystemPromptId(TEXT_EXPANSION, "今天天气不错"); } void test09_ChatSystemPromptId_TRANSLATE_CHINESE_TO_ENGLISH() { ChatSystemPromptId(TRANSLATE_CHINESE_TO_ENGLISH, "今天天气不错"); } void setXunfeiAuthens() { kyai::config::model::ModelConfig mc; std::vector modelsAuthens; modelsAuthens.push_back( {"", { {"", "appId", ""}, {"", "apiKey", ""}, {"", "secretKey", ""}, }}); mc.setModelAuthentications("讯飞-Spark Max", modelsAuthens); } void setBaiduAuthens() { kyai::config::model::ModelConfig mc; std::vector modelsAuthens; modelsAuthens.push_back( {"", { {"", "appId", ""}, {"", "apiKey", ""}, {"", "secretKey", ""}, }}); mc.setModelAuthentications("百度-ERNIE-Bot-4", modelsAuthens); } void setModelConfig(const std::string &modelName) { setBaiduAuthens(); setXunfeiAuthens(); // kyai::config::model::ModelConfig mc; // mc.setCurrentModelName(kyai::config::model::AiCapability::Nlp, // kyai::config::model::DeployType::PublicCloud, // modelName); } void test10_Chat() { ChatModelConfig *config = chat_model_config_create(); chat_model_config_set_name(config, "百度-ERNIE-Bot-4"); chat_model_config_set_top_k(config, 0.5); chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud); GenAiTextSession *session = genai_text_create_session(); genai_text_set_model_config(session, config); int errorCode = genai_text_init_session(session); if (errorCode != AISDK_NO_ERROR) { LOGE("初始化错误:错误码", errorCode); return; } int a = 100; genai_text_result_set_callback(session, callback, &a); genai_text_chat_async(session, "一加一等于几"); GMainLoop *pMainLoop = g_main_loop_new(nullptr, false); std::thread ctrlThread([&session, &config, pMainLoop] { while (std::getchar() != '\n') { } genai_text_chat_async(session, "你说的不对"); while (std::getchar() != '\n') { } genai_text_stop_chat(session); genai_text_destroy_session(&session); chat_model_config_destroy(&config); g_main_loop_quit(pMainLoop); }); ctrlThread.detach(); g_main_loop_run(pMainLoop); g_main_loop_unref(pMainLoop); } void test10_BigTest() { LOGI("一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一"); test10_Chat(); LOGI("二二二二二二二二二二二二二二二二二二二二二二二二二二二二二二"); test10_Chat(); LOGI("三三三三三三三三三三三三三三三三三三三三三三三三三三三三三三"); test10_Chat(); LOGI("四四四四四四四四四四四四四四四四四四四四四四四四四四四四四四"); test10_Chat(); LOGI("五五五五五五五五五五五五五五五五五五五五五五五五五五五五五五"); test10_Chat(); LOGI("六六六六六六六六六六六六六六六六六六六六六六六六六六六六六六"); test10_Chat(); LOGI("七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七"); test10_Chat(); LOGI("八八八八八八八八八八八八八八八八八八八八八八八八八八八八八八"); test10_Chat(); LOGI("九九九九九九九九九九九九九九九九九九九九九九九九九九九九九九"); test10_Chat(); LOGI("十十十十十十十十十十十十十十十十十十十十十十十十十十十十十十"); test10_Chat(); LOGI("十一十一十一十一十一十一十一十一十一十一十一十一十一十一十一"); test10_Chat(); LOGI("十二十二十二十二十二十二十二十二十二十二十二十二十二十二十二"); test10_Chat(); LOGI("十三十三十三十三十三十三十三十三十三十三十三十三十三十三十三"); test10_Chat(); LOGI("十四十四十四十四十四十四十四十四十四十四十四十四十四十四十四"); test10_Chat(); LOGI("十五十五十五十五十五十五十五十五十五十五十五十五十五十五十五"); test10_Chat(); LOGI("十六十六十六十六十六十六十六十六十六十六十六十六十六十六十六"); test10_Chat(); LOGI("十七十七十七十七十七十七十七十七十七十七十七十七十七十七十七"); test10_Chat(); LOGI("十八十八十八十八十八十八十八十八十八十八十八十八十八十八十八"); test10_Chat(); LOGI("十九十九十九十九十九十九十九十九十九十九十九十九十九十九十九"); test10_Chat(); LOGI("二十二十二十二十二十二十二十二十二十二十二十二十二十二十二十"); test10_Chat(); } int main() { setModelConfig("百度-ERNIE-Bot-4"); LOGI("一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一"); test01_Chat(); LOGI("二二二二二二二二二二二二二二二二二二二二二二二二二二二二二二"); test02_ChatHistoryMessages(); LOGI("三三三三三三三三三三三三三三三三三三三三三三三三三三三三三三"); test03_ClearChatMessage(); LOGI("四四四四四四四四四四四四四四四四四四四四四四四四四四四四四四"); test04_SetModelConfig(); LOGI("五五五五五五五五五五五五五五五五五五五五五五五五五五五五五五"); test05_SetChatSystemPrompt(); LOGI("六六六六六六六六六六六六六六六六六六六六六六六六六六六六六六"); test06_GenerateContent(); LOGI("七七七七七七七七七七七七七七七七七七七七七七七七七七七七七七"); test07_ChatSystemPromptId_SUMMARY(); LOGI("八八八八八八八八八八八八八八八八八八八八八八八八八八八八八八"); test08_ChatSystemPromptId_TEXT_EXPANSION(); LOGI("九九九九九九九九九九九九九九九九九九九九九九九九九九九九九九"); test09_ChatSystemPromptId_TRANSLATE_CHINESE_TO_ENGLISH(); LOGI("十十十十十十十十十十十十十十十十十十十十十十十十十十十十十十"); test10_BigTest(); return 0; } libkysdk-genai-1.1.0.1/usr/000077500000000000000000000000001520575640000153625ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/usr/share/000077500000000000000000000000001520575640000164645ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/usr/share/pkgconfig/000077500000000000000000000000001520575640000204335ustar00rootroot00000000000000libkysdk-genai-1.1.0.1/usr/share/pkgconfig/kysdk-genai-nlp.pc000066400000000000000000000002051520575640000237510ustar00rootroot00000000000000Name: libkysdk-genai-nlp Description: Kylin gen ai nlp library Version: 1.0.0 Libs: -lkysdk-genai-nlp Cflags: -I/usr/include/kylin-ailibkysdk-genai-1.1.0.1/usr/share/pkgconfig/kysdk-genai-vision.pc000066400000000000000000000002251520575640000244710ustar00rootroot00000000000000Name: libkysdk-genai-vision Description: Kylin gen ai vision library Version: 1.0.0 Libs: -lkysdk-genai-vision Cflags: -I/usr/include/kylin-ai/genai