diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca409795..9a20cf2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## [2.0.1]
+
+### Changed
+- **License changed from Apache 2.0 to AGPL-3.0.** GraphRAG is now distributed under the GNU Affero General Public License v3.0; releases through v2.0.0 remain under Apache 2.0.
+- **Knowledge-graph rebuild shows per-stage progress and flags incomplete work.** The rebuild dialog now shows a progress bar for document processing and for community summarization, reports the community-detection level as it climbs, and ends with a warning — instead of a plain success — when some community summaries could not be generated.
+
+### Fixed
+- **Chat no longer errors with models that return structured content.** Replies from models that respond in typed content blocks — such as Gemini 3 and reasoning models — are read correctly instead of raising a validation error, so Classic mode works with these models again.
+- **Knowledge-graph rebuild no longer hangs when the language model is unreachable.** Community summarization fails fast on a provider outage and stops calling the model after repeated connection failures, so a rebuild finishes instead of looping indefinitely. Communities left unsummarized are marked with a placeholder so they can be regenerated once connectivity is restored.
+
## [2.0.0]
### Added
diff --git a/LICENSE b/LICENSE
index 8c75c7bc..be3f7b28 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,178 +1,661 @@
- Copyright (c) 2024-2026 TigerGraph, Inc.
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are 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.
+
+ 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ 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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ 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 AGPL, see
+.
diff --git a/README.md b/README.md
index 02a3607b..70aa1ca5 100644
--- a/README.md
+++ b/README.md
@@ -67,6 +67,7 @@
---
## Releases
+* **7/22/2026**: GraphRAG v2.0.1 released. Fixed a chat error with models that return structured content (such as Gemini 3), and hardened knowledge-graph rebuild so it no longer hangs when the language model is unreachable. Relicensed from Apache 2.0 to AGPL-3.0. See [Release Notes](https://github.com/tigergraph/graphrag/releases/tag/v2.0.1) for details.
* **7/1/2026**: GraphRAG v2.0.0 released. Added an agentic chat engine that plans and runs its own retrieval (Planner and Reactive styles), external MCP tools, and structure-aware document chunking, along with additive prompt customization and many other improvements and bug fixes. See [Release Notes](https://github.com/tigergraph/graphrag/releases/tag/v2.0.0) for details.
* **6/23/2026**: GraphRAG v1.4.2 released. Added a knowledge graph compatibility check and repair tool to pick up shipped query fixes on existing graphs, along with more reliable ingestion for documents with spaces in their filenames and other improvements and bug fixes. See [Release Notes](https://github.com/tigergraph/graphrag/releases/tag/v1.4.2) for details.
* **5/30/2026**: GraphRAG v1.4.1 released. Added token-based login and a pre-flight upload conflict check, along with more resilient chat when vector search is unavailable and other improvements and bug fixes. See [Release Notes](https://github.com/tigergraph/graphrag/releases/tag/v1.4.1) for details.
@@ -509,7 +510,7 @@ Copy the below code into `configs/server_config.json`. You shouldn’t need to c
| `ecc` | string | `"http://graphrag-ecc:8001"` | URL of the knowledge graph build service. No change needed when using the provided Docker Compose file. |
| `chat_history_api` | string | `"http://chat-history:8002"` | URL of the chat history service. No change needed when using the provided Docker Compose file. |
| `chunker` | string | `"semantic"` | Default document chunker. Options: `semantic`, `character`, `regex`, `markdown`, `html`, `recursive`. |
-| `extractor` | string | `"llm"` | Entity extraction method. Options: `llm`, `graphrag`. |
+| `extractor` | string | `"llm"` | Entity extraction method. Use `llm` (schema-aware, recommended). `graphrag` is **deprecated** and will be removed in a future release. |
| `strict_mode` | bool | `false` | Dynamic-schema enforcement during extraction. When `true`, entities and relationships that don't match the domain schema are dropped. When `false` (default), unmatched nodes fall back to generic `Entity` vertices. |
| `retrieval_include_entity` | bool \| null | `null` (auto) | Whether retriever queries include the generic `Entity` vertex alongside domain types. When unset, the server uses `false` if a domain schema exists and `true` otherwise. Set explicitly to override. |
| `schema_max_sample_files` | int | `5` | Maximum number of sample documents accepted by the *Generate from sample documents* path on the *Initialize Knowledge Graph* dialog. |
@@ -1142,3 +1143,7 @@ docker compose up -d --build
For adding a new test suite and the broader developer workflow — extending the service with different LLM providers, embedding services, or tools — see the [Developer Guide](./docs/DeveloperGuide.md).
+
+## License
+
+GraphRAG is licensed under the [GNU Affero General Public License v3.0](./LICENSE) (AGPL-3.0). Prior releases through v2.0.0 were distributed under the Apache License 2.0.
diff --git a/VERSION b/VERSION
index 227cea21..10bf840e 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-2.0.0
+2.0.1
\ No newline at end of file
diff --git a/common/chunkers/auto.py b/common/chunkers/auto.py
index 36bb9373..d1f08026 100644
--- a/common/chunkers/auto.py
+++ b/common/chunkers/auto.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Content-aware chunker dispatcher.
diff --git a/common/chunkers/html_chunker.py b/common/chunkers/html_chunker.py
index 49df7079..b4244455 100644
--- a/common/chunkers/html_chunker.py
+++ b/common/chunkers/html_chunker.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from typing import Optional, List, Tuple
import re
diff --git a/common/chunkers/markdown_chunker.py b/common/chunkers/markdown_chunker.py
index ab8ba521..7c89d75d 100644
--- a/common/chunkers/markdown_chunker.py
+++ b/common/chunkers/markdown_chunker.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from common.chunkers.base_chunker import BaseChunker
from common.chunkers.separators import TEXT_SEPARATORS
diff --git a/common/chunkers/recursive_chunker.py b/common/chunkers/recursive_chunker.py
index b996a87d..5adb3055 100644
--- a/common/chunkers/recursive_chunker.py
+++ b/common/chunkers/recursive_chunker.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from common.chunkers.base_chunker import BaseChunker
from common.chunkers.separators import TEXT_SEPARATORS
diff --git a/common/chunkers/semantic_chunker.py b/common/chunkers/semantic_chunker.py
index 00d34be7..8a428cfc 100644
--- a/common/chunkers/semantic_chunker.py
+++ b/common/chunkers/semantic_chunker.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from common.chunkers.base_chunker import BaseChunker
from common.embeddings.embedding_services import EmbeddingModel
diff --git a/common/chunkers/separators.py b/common/chunkers/separators.py
index bba7749c..eecd1578 100644
--- a/common/chunkers/separators.py
+++ b/common/chunkers/separators.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
TEXT_SEPARATORS = [
"\n\n",
diff --git a/common/chunkers/structured.py b/common/chunkers/structured.py
index 865aa035..aa3ec26e 100644
--- a/common/chunkers/structured.py
+++ b/common/chunkers/structured.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Page- and structure-aware chunker (v2.0 — GML-2121).
diff --git a/common/config.py b/common/config.py
index 9a3dcaa5..d229d694 100644
--- a/common/config.py
+++ b/common/config.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import copy
import json
diff --git a/common/db/connections.py b/common/db/connections.py
index 0ac92ac6..c9dc628a 100644
--- a/common/db/connections.py
+++ b/common/db/connections.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import asyncio
diff --git a/common/db/query_errors.py b/common/db/query_errors.py
index 63693840..a9d166a4 100644
--- a/common/db/query_errors.py
+++ b/common/db/query_errors.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Helpers for interpreting TigerGraph query create/install results and errors.
diff --git a/common/db/query_install.py b/common/db/query_install.py
index d3b6f8ff..2ac52dd8 100644
--- a/common/db/query_install.py
+++ b/common/db/query_install.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Batched, timeout-safe query installation.
diff --git a/common/db/query_sets.py b/common/db/query_sets.py
index 1bcfa279..1852bd52 100644
--- a/common/db/query_sets.py
+++ b/common/db/query_sets.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Canonical lists of shipped GSQL query paths.
diff --git a/common/db/retriever_render.py b/common/db/retriever_render.py
index c7567ab8..ca7980c9 100644
--- a/common/db/retriever_render.py
+++ b/common/db/retriever_render.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Render and install retrieval queries against the live domain schema."""
diff --git a/common/db/schema_extraction.py b/common/db/schema_extraction.py
index 06c58453..6bba615e 100644
--- a/common/db/schema_extraction.py
+++ b/common/db/schema_extraction.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Schema-extraction over sample documents (Phase 1, sample-doc path).
diff --git a/common/db/schema_utils.py b/common/db/schema_utils.py
index e80b1d85..75d317d6 100644
--- a/common/db/schema_utils.py
+++ b/common/db/schema_utils.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""
Schema proposal and persistence for the schema-aware initialize_graph flow.
diff --git a/common/embeddings/tigergraph_embedding_store.py b/common/embeddings/tigergraph_embedding_store.py
index 42856631..bfd1978a 100644
--- a/common/embeddings/tigergraph_embedding_store.py
+++ b/common/embeddings/tigergraph_embedding_store.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import traceback
@@ -59,7 +59,6 @@ def __init__(
restppPort=conn.restppPort,
gsPort=conn.gsPort,
tgCloud=conn.tgCloud,
- useCert=conn.useCert,
certPath=conn.certPath,
sslPort = conn.sslPort,
jwtToken = conn.jwtToken,
@@ -182,7 +181,6 @@ def set_connection(self, conn):
restppPort=conn.restppPort,
gsPort=conn.gsPort,
tgCloud=conn.tgCloud,
- useCert=conn.useCert,
certPath=conn.certPath,
sslPort = conn.sslPort,
jwtToken = conn.jwtToken,
diff --git a/common/extractors/GraphExtractor.py b/common/extractors/GraphExtractor.py
index 9cf44cc3..3bcd35a6 100644
--- a/common/extractors/GraphExtractor.py
+++ b/common/extractors/GraphExtractor.py
@@ -1,6 +1,5 @@
from langchain_community.graphs.graph_document import GraphDocument
from langchain_core.documents import Document
-from langchain_experimental.graph_transformers import LLMGraphTransformer
from common.config import get_llm_service, get_completion_config
from common.extractors.BaseExtractor import BaseExtractor
@@ -8,6 +7,11 @@
class GraphExtractor(BaseExtractor):
def __init__(self):
+ # Imported lazily: langchain-experimental is being sunset upstream, so
+ # only pay the deprecation warning if this extractor is actually used
+ # (the default "llm" path uses LLMEntityRelationshipExtractor instead).
+ from langchain_experimental.graph_transformers import LLMGraphTransformer
+
llm = get_llm_service(get_completion_config()).llm
self.transformer = LLMGraphTransformer(
llm=llm,
diff --git a/common/extractors/LLMEntityRelationshipExtractor.py b/common/extractors/LLMEntityRelationshipExtractor.py
index e2f3a5db..cf1f28a5 100644
--- a/common/extractors/LLMEntityRelationshipExtractor.py
+++ b/common/extractors/LLMEntityRelationshipExtractor.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import re
diff --git a/common/gsql/graphrag/communities_have_desc.gsql b/common/gsql/graphrag/communities_have_desc.gsql
index d44615c0..9b4090f6 100644
--- a/common/gsql/graphrag/communities_have_desc.gsql
+++ b/common/gsql/graphrag/communities_have_desc.gsql
@@ -1,16 +1,18 @@
CREATE OR REPLACE DISTRIBUTED QUERY communities_have_desc(UINT iter, BOOL p=False) SYNTAX V2{
SumAccum @@descrs;
+ SumAccum @@total;
Comms = {Community.*};
Comms = SELECT c FROM Comms:c
WHERE c.iteration == iter
POST-ACCUM
+ @@total += 1,
IF length(c.description) > 0 THEN
@@descrs += 1
END;
-
- PRINT (@@descrs == Comms.size()) as all_have_desc;
- PRINT @@descrs, Comms.size();
+
+ PRINT (@@descrs == @@total) as all_have_desc;
+ PRINT @@descrs AS described, @@total AS total;
IF p THEN
Comms = SELECT c FROM Comms:c
diff --git a/common/gsql/graphrag/graphrag_delete_all_communities.gsql b/common/gsql/graphrag/graphrag_delete_all_communities.gsql
index ceb9f809..05db6e39 100644
--- a/common/gsql/graphrag/graphrag_delete_all_communities.gsql
+++ b/common/gsql/graphrag/graphrag_delete_all_communities.gsql
@@ -1,11 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY graphrag_delete_all_communities() {
diff --git a/common/gsql/graphrag/graphrag_stream_all_ids.gsql b/common/gsql/graphrag/graphrag_stream_all_ids.gsql
index 8f164410..038f0580 100644
--- a/common/gsql/graphrag/graphrag_stream_all_ids.gsql
+++ b/common/gsql/graphrag/graphrag_stream_all_ids.gsql
@@ -1,11 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE QUERY graphrag_stream_all_ids(STRING v_type) {
diff --git a/common/gsql/graphrag/graphrag_stream_entity_community_pairs.gsql b/common/gsql/graphrag/graphrag_stream_entity_community_pairs.gsql
index 8d20117a..adae5d6e 100644
--- a/common/gsql/graphrag/graphrag_stream_entity_community_pairs.gsql
+++ b/common/gsql/graphrag/graphrag_stream_entity_community_pairs.gsql
@@ -1,11 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY graphrag_stream_entity_community_pairs() {
diff --git a/common/gsql/supportai/SupportAI_Schema.gsql b/common/gsql/supportai/SupportAI_Schema.gsql
index 79aa8659..8c80193b 100644
--- a/common/gsql/supportai/SupportAI_Schema.gsql
+++ b/common/gsql/supportai/SupportAI_Schema.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE SCHEMA_CHANGE JOB add_supportai_schema {
diff --git a/common/gsql/supportai/SupportAI_Schema_Images.gsql b/common/gsql/supportai/SupportAI_Schema_Images.gsql
index e6f2e5cf..f135e1e9 100644
--- a/common/gsql/supportai/SupportAI_Schema_Images.gsql
+++ b/common/gsql/supportai/SupportAI_Schema_Images.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE SCHEMA_CHANGE JOB add_image_support_schema {
diff --git a/common/gsql/supportai/SupportAI_Schema_Native_Vector.gsql b/common/gsql/supportai/SupportAI_Schema_Native_Vector.gsql
index 4db81a63..19d286c5 100644
--- a/common/gsql/supportai/SupportAI_Schema_Native_Vector.gsql
+++ b/common/gsql/supportai/SupportAI_Schema_Native_Vector.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE SCHEMA_CHANGE JOB add_graphrag_vector {
diff --git a/common/gsql/supportai/retrievers/Chunk_Sibling_Search.gsql b/common/gsql/supportai/retrievers/Chunk_Sibling_Search.gsql
index d98051ac..a9e41f79 100644
--- a/common/gsql/supportai/retrievers/Chunk_Sibling_Search.gsql
+++ b/common/gsql/supportai/retrievers/Chunk_Sibling_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Chunk_Sibling_Search(STRING json_list_vts="[]", STRING v_type="DocumentChunk", UINT lookback=3, INT lookahead=3, BOOL verbose = False) {
diff --git a/common/gsql/supportai/retrievers/Chunk_Sibling_Vector_Search.gsql b/common/gsql/supportai/retrievers/Chunk_Sibling_Vector_Search.gsql
index a09b0455..5487049a 100644
--- a/common/gsql/supportai/retrievers/Chunk_Sibling_Vector_Search.gsql
+++ b/common/gsql/supportai/retrievers/Chunk_Sibling_Vector_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Chunk_Sibling_Vector_Search(STRING v_type,
diff --git a/common/gsql/supportai/retrievers/Content_Similarity_Search.gsql b/common/gsql/supportai/retrievers/Content_Similarity_Search.gsql
index 2801164d..fef73fff 100644
--- a/common/gsql/supportai/retrievers/Content_Similarity_Search.gsql
+++ b/common/gsql/supportai/retrievers/Content_Similarity_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Content_Similarity_Search(STRING json_list_vts="[]", STRING v_type="DocumentChunk", BOOL verbose = False) {
diff --git a/common/gsql/supportai/retrievers/Content_Similarity_Vector_Search.gsql b/common/gsql/supportai/retrievers/Content_Similarity_Vector_Search.gsql
index 666f7948..93515b50 100644
--- a/common/gsql/supportai/retrievers/Content_Similarity_Vector_Search.gsql
+++ b/common/gsql/supportai/retrievers/Content_Similarity_Vector_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Content_Similarity_Vector_Search(STRING v_type, LIST query_vector, INT top_k=5, BOOL verbose = False) {
diff --git a/common/gsql/supportai/retrievers/Entity_Relationship_Retrieval.gsql b/common/gsql/supportai/retrievers/Entity_Relationship_Retrieval.gsql
index 7e38a528..58531edf 100644
--- a/common/gsql/supportai/retrievers/Entity_Relationship_Retrieval.gsql
+++ b/common/gsql/supportai/retrievers/Entity_Relationship_Retrieval.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Entity_Relationship_Retrieval(SET entities, SET relationships, INT top_k=5) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Community_Search.gsql b/common/gsql/supportai/retrievers/GraphRAG_Community_Search.gsql
index 099a453b..1a10d82f 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Community_Search.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Community_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Community_Search(STRING json_list_vts="[]", INT community_level=2, BOOL with_chunk = true, BOOL with_doc = false, BOOL verbose = false) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Community_Search_Display.gsql b/common/gsql/supportai/retrievers/GraphRAG_Community_Search_Display.gsql
index 939890b3..120eda04 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Community_Search_Display.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Community_Search_Display.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Community_Search_Display(STRING json_list_vts, UINT community_level = 2, BOOL with_chunk = true) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Community_Vector_Search.gsql b/common/gsql/supportai/retrievers/GraphRAG_Community_Vector_Search.gsql
index 0eb648d8..a4edcdcb 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Community_Vector_Search.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Community_Vector_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Community_Vector_Search(LIST query_vector, INT community_level=2, INT top_k = 3, UINT max_results = 0, BOOL with_chunk = true, BOOL with_doc = false, BOOL verbose = false) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search.gsql b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search.gsql
index 8a49e75d..64787b14 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Hybrid_Search(STRING json_list_vts = "[]", UINT num_hops=5, UINT num_seen_min=1, BOOL chunk_only=False, BOOL doc_only = False, BOOL verbose = False) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search_Display.gsql b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search_Display.gsql
index a5dcae58..0e074816 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search_Display.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Search_Display.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Hybrid_Search_Display(STRING json_list_vts, UINT num_hops=5, UINT num_seen_min=1, BOOL chunk_only=False) {
diff --git a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Vector_Search.gsql b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Vector_Search.gsql
index f94cbbec..834c4ef3 100644
--- a/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Vector_Search.gsql
+++ b/common/gsql/supportai/retrievers/GraphRAG_Hybrid_Vector_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY GraphRAG_Hybrid_Vector_Search(Set v_types,
diff --git a/common/gsql/supportai/retrievers/Keyword_Search.gsql b/common/gsql/supportai/retrievers/Keyword_Search.gsql
index fdfdb3f9..c838f705 100644
--- a/common/gsql/supportai/retrievers/Keyword_Search.gsql
+++ b/common/gsql/supportai/retrievers/Keyword_Search.gsql
@@ -1,17 +1,17 @@
/*
* Copyright (c) 2024-2026 TigerGraph, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * This program may be redistributed and/or modified under the terms of the GNU
+ * Affero General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * 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 Affero General Public License for more
+ * details.
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
*/
CREATE OR REPLACE DISTRIBUTED QUERY Keyword_Search(SET keywords, STRING mode = "ANY", INT top_k = 5, BOOL doc_only = False, BOOL verbose = False) {
diff --git a/common/llm_services/aws_bedrock_service.py b/common/llm_services/aws_bedrock_service.py
index 4e6096f6..bb74ce19 100644
--- a/common/llm_services/aws_bedrock_service.py
+++ b/common/llm_services/aws_bedrock_service.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import boto3, botocore
from langchain_aws import ChatBedrock
diff --git a/common/llm_services/base_llm.py b/common/llm_services/base_llm.py
index 8c12159a..141838e2 100644
--- a/common/llm_services/base_llm.py
+++ b/common/llm_services/base_llm.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import os
import re
@@ -23,6 +23,56 @@
logger = logging.getLogger(__name__)
+import asyncio as _asyncio
+
+# HTTP statuses that mean "provider-side / transient" rather than a problem with
+# our request — retrying the same call won't help and, in bulk, signals an
+# outage. 4xx like 400/401/404 are our fault and stay "content".
+_TRANSIENT_HTTP_STATUS = frozenset({408, 409, 425, 429, 500, 502, 503, 504})
+
+
+def classify_llm_error(exc, _depth: int = 0) -> str:
+ """Classify an LLM call failure as ``"connectivity"`` or ``"content"``.
+
+ ``"connectivity"`` = provider unreachable, timed out, or a transient
+ server-side status — do NOT retry (it will just fail again) and count it
+ toward the summarization circuit breaker. ``"content"`` = a response-level
+ problem (bad JSON, an invalid request) that may succeed on a retry and is
+ specific to one call, so it must not trip the breaker.
+
+ Detection is by exception type and HTTP status code (what the SDKs already
+ give us), not by matching free-form error-message text.
+ """
+ # Our own summarization timeout and stdlib timeouts.
+ if isinstance(exc, (_asyncio.TimeoutError, TimeoutError)):
+ return "connectivity"
+
+ # HTTP status, when the provider SDK exposes one (openai, google, anthropic
+ # all surface .status_code, or .response.status_code).
+ status = getattr(exc, "status_code", None)
+ if status is None:
+ status = getattr(getattr(exc, "response", None), "status_code", None)
+ if isinstance(status, int) and status in _TRANSIENT_HTTP_STATUS:
+ return "connectivity"
+
+ # Exception class name — covers ConnectError/ConnectTimeout/ReadTimeout
+ # (httpx), APIConnectionError/APITimeoutError (openai),
+ # ServiceUnavailable/DeadlineExceeded (google) etc. without importing every
+ # provider SDK. The class name is SDK-controlled, unlike the message text.
+ name = type(exc).__name__.lower()
+ if any(t in name for t in ("timeout", "connect", "unavailable", "deadline")):
+ return "connectivity"
+
+ # SDKs often wrap the transport error as __cause__ (e.g. openai wraps httpx);
+ # inspect one level down before giving up.
+ if _depth < 3:
+ for nested in (getattr(exc, "__cause__", None), getattr(exc, "__context__", None)):
+ if nested is not None and nested is not exc:
+ if classify_llm_error(nested, _depth + 1) == "connectivity":
+ return "connectivity"
+
+ return "content"
+
class UserPortionConflictReview(BaseModel):
"""Result of the LLM conflict check between a split prompt's fixed system
@@ -292,6 +342,39 @@ def _repair_json_escapes(s: str) -> str:
flags=re.DOTALL,
)
+ @staticmethod
+ def _message_text(raw) -> str:
+ """Plain text from a model response, normalized across providers.
+
+ LangChain returns ``AIMessage.content`` as a **list of typed content
+ blocks** (not a string) whenever a provider emits reasoning / thinking:
+ Anthropic and Bedrock Claude with extended thinking return
+ ``[{"type": "thinking", "signature": ...}, {"type": "text", "text": ...}]``,
+ and OpenAI reasoning models do the same via the Responses API. (OpenAI on
+ the default Chat Completions path returns a plain string, which is why
+ string-content models never hit this.) Downstream string parsers
+ (``PydanticOutputParser`` -> ``Generation(text=...)``) require a string.
+
+ This mirrors langchain-core's own ``.text`` accessor — keep ``type ==
+ "text"`` blocks and bare strings, drop reasoning / thinking — but is
+ inlined because that accessor's shape differs across our
+ ``langchain-core>=0.3.26`` range (a method in 0.3.x, a property in 1.x),
+ so calling it directly isn't version-portable. Reading ``.content``
+ (stable: str or list) is.
+ """
+ content = raw.content if hasattr(raw, "content") else raw
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts = []
+ for b in content:
+ if isinstance(b, str):
+ parts.append(b)
+ elif isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str):
+ parts.append(b["text"])
+ return "".join(parts)
+ return str(content)
+
def _parse_or_repair(self, parser, text, caller_name):
"""Parse LLM output with a shared fallback: extract the JSON object,
then (if it still fails) repair invalid escapes. Used by every
@@ -420,7 +503,7 @@ def invoke_with_parser(
logger.info(f"{caller_name} usage: {usage_data}")
_record_usage(caller_name, usage_data)
- raw_text = raw_output.content if hasattr(raw_output, "content") else str(raw_output)
+ raw_text = self._message_text(raw_output)
try:
return self._parse_or_repair(parser, raw_text, caller_name)
@@ -490,7 +573,7 @@ def invoke_structured(
)
parser = PydanticOutputParser(pydantic_object=schema)
raw = self.llm.invoke(messages)
- raw_text = raw.content if hasattr(raw, "content") else str(raw)
+ raw_text = self._message_text(raw)
result = self._parse_or_repair(parser, raw_text, caller_name)
usage_data["input_tokens"] = cb.prompt_tokens
usage_data["output_tokens"] = cb.completion_tokens
@@ -528,7 +611,7 @@ async def ainvoke_with_parser(
logger.info(f"{caller_name} usage: {usage_data}")
_record_usage(caller_name, usage_data)
- raw_text = raw_output.content if hasattr(raw_output, "content") else str(raw_output)
+ raw_text = self._message_text(raw_output)
try:
return self._parse_or_repair(parser, raw_text, caller_name)
diff --git a/common/llm_services/capabilities.py b/common/llm_services/capabilities.py
index 70514547..653c3fd9 100644
--- a/common/llm_services/capabilities.py
+++ b/common/llm_services/capabilities.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Per provider/model capability map for the agentic chat engine.
diff --git a/common/llm_services/google_genai_service.py b/common/llm_services/google_genai_service.py
index 54d3a208..af40fad7 100644
--- a/common/llm_services/google_genai_service.py
+++ b/common/llm_services/google_genai_service.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import os
@@ -41,5 +41,5 @@ def __init__(self, config):
)
self.prompt_path = config["prompt_path"]
LogWriter.info(
- f"request_id={req_id_cv.get()} instantiated OpenAI model_name={model_name}"
+ f"request_id={req_id_cv.get()} instantiated GoogleGenAI model_name={model_name}"
)
diff --git a/common/llm_services/groq_llm_service.py b/common/llm_services/groq_llm_service.py
index b1e58eea..cea9fb98 100644
--- a/common/llm_services/groq_llm_service.py
+++ b/common/llm_services/groq_llm_service.py
@@ -20,5 +20,5 @@ def __init__(self, config):
self.llm = ChatGroq(temperature=0, model_name=model_name)
self.prompt_path = config["prompt_path"]
LogWriter.info(
- f"request_id={req_id_cv.get()} instantiated OpenAI model_name={model_name}"
+ f"request_id={req_id_cv.get()} instantiated Groq model_name={model_name}"
)
diff --git a/common/llm_services/openai_service.py b/common/llm_services/openai_service.py
index 9c88deb0..a81cf215 100644
--- a/common/llm_services/openai_service.py
+++ b/common/llm_services/openai_service.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import os
diff --git a/common/mcp_config.py b/common/mcp_config.py
index 8d41e072..15e57a23 100644
--- a/common/mcp_config.py
+++ b/common/mcp_config.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""External MCP-server config.
diff --git a/common/py_schemas/schemas.py b/common/py_schemas/schemas.py
index a4bf2879..a07b9da3 100644
--- a/common/py_schemas/schemas.py
+++ b/common/py_schemas/schemas.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import enum
from typing import Dict, List, Optional, Union
diff --git a/common/py_schemas/tool_io_schemas.py b/common/py_schemas/tool_io_schemas.py
index b680af39..23acfbb8 100644
--- a/common/py_schemas/tool_io_schemas.py
+++ b/common/py_schemas/tool_io_schemas.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from typing import Dict, List, Optional
diff --git a/common/requirements.txt b/common/requirements.txt
index c1a57930..c1249c84 100644
--- a/common/requirements.txt
+++ b/common/requirements.txt
@@ -21,7 +21,7 @@ certifi>=2025.6.15
cffi>=1.17.1
chardet>=5.2.0
charset-normalizer>=3.4.2
-click>=8.4.1
+click>=8.0.0,<8.4.0
contourpy>=1.3.2
cryptography>=45.0.4
cycler>=0.12.1
@@ -77,21 +77,21 @@ jsonpatch>=1.33
jsonpath-python>=1.0.6
jsonpointer>=3.0.0
kiwisolver>=1.4.8
-langchain-core>=0.3.26
-langchain_google_genai>=2.1.8
-langchain-google-vertexai>=2.1.2
-langchain-community>=0.3.26
-langchain-experimental>=0.3.5rc1
-langchain-groq>=0.3.4
-langchain-ibm>=0.3.12
-langchain-openai>=0.3.26
-langchain-ollama>=0.3.7
-langchain-text-splitters>=0.3.8
-langchain-aws>=0.2.31
+langchain-core>=1.0.0
+langchain_google_genai>=4.0.0
+langchain-google-vertexai>=3.0.0
+langchain-community>=0.4.0
+langchain-experimental>=0.4.0
+langchain-groq>=1.0.0
+langchain-ibm>=1.0.0
+langchain-openai>=1.0.0
+langchain-ollama>=1.0.0
+langchain-text-splitters>=1.0.0
+langchain-aws>=1.0.0
langchainhub>=0.1.21
langdetect>=1.0.9
-langgraph>=0.4.10
-langgraph-checkpoint>=2.1.0
+langgraph>=1.0.0
+langgraph-checkpoint>=3.0.0
langsmith>=0.4.2
Levenshtein>=0.27.1
lomond>=0.3.3
@@ -130,6 +130,7 @@ pydantic_core>=2.33.2
pygit2>=1.18.0
pyparsing>=3.2.3
pypdf>=5.6.1
+deepeval==4.0.7
pytest>=8.4.1
python-docx>=1.1.2
pytesseract>=0.3.10
diff --git a/common/utils/prompt_validation.py b/common/utils/prompt_validation.py
index c2062ef5..63ae2e4b 100644
--- a/common/utils/prompt_validation.py
+++ b/common/utils/prompt_validation.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Gatekeepers for user-customized prompt templates.
diff --git a/common/utils/token_calculator.py b/common/utils/token_calculator.py
index dfe4a76b..bc58ceeb 100644
--- a/common/utils/token_calculator.py
+++ b/common/utils/token_calculator.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import tiktoken
diff --git a/ecc/app/eventual_consistency_checker.py b/ecc/app/eventual_consistency_checker.py
index df3ae55d..97d416eb 100644
--- a/ecc/app/eventual_consistency_checker.py
+++ b/ecc/app/eventual_consistency_checker.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
import time
diff --git a/ecc/app/graphrag/community_summarizer.py b/ecc/app/graphrag/community_summarizer.py
index 50c1b64d..55662934 100644
--- a/ecc/app/graphrag/community_summarizer.py
+++ b/ecc/app/graphrag/community_summarizer.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import re
import logging
@@ -19,6 +19,7 @@
from langchain_core.output_parsers import PydanticOutputParser
from common.llm_services import LLM_Model
+from common.llm_services.base_llm import classify_llm_error
from common.py_schemas import CommunitySummary
logger = logging.getLogger(__name__)
@@ -55,5 +56,10 @@ async def summarize(self, name: str, text: list[str]) -> dict:
caller_name="community_summarize",
)
except Exception as e:
- return {"error": True, "summary": "", "message": str(e)}
+ return {
+ "error": True,
+ "summary": "",
+ "message": str(e),
+ "category": classify_llm_error(e),
+ }
return {"error": False, "summary": summary.summary}
\ No newline at end of file
diff --git a/ecc/app/graphrag/graph_rag.py b/ecc/app/graphrag/graph_rag.py
index 6dd5b0e6..97a0e793 100644
--- a/ecc/app/graphrag/graph_rag.py
+++ b/ecc/app/graphrag/graph_rag.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import json
@@ -24,7 +24,7 @@
from graphrag import workers
from graphrag.util import (
COMMUNITY_QUERIES,
- check_vertex_has_desc,
+ community_desc_progress,
http_timeout,
init,
install_queries,
@@ -47,6 +47,82 @@
consistency_checkers = {}
+
+class _DocProgress:
+ """Tracks documents through the merged chunk+extract phase so the UI can
+ show a single 'Processing documents' bar that advances at extraction pace
+ (the slow, LLM-bound part) against a fixed document denominator — no
+ moving-denominator jump, and no misleading jump to 100% when chunking
+ finishes early.
+
+ A document is complete once it has been chunked and all of its chunks have
+ been extracted. When extraction is disabled, a document is complete as soon
+ as it is chunked.
+
+ Every method is defensive: a progress-tracking error must never break the
+ ingestion pipeline.
+ """
+
+ def __init__(self, report, extraction_on: bool):
+ self._report = report
+ self._extraction_on = extraction_on
+ self._total = 0
+ self._completed = 0
+ self._chunk_to_doc: dict = {}
+ self._doc_remaining: dict = {}
+
+ def set_total(self, total: int) -> None:
+ try:
+ self._total = int(total or 0)
+ self._emit()
+ except Exception:
+ pass
+
+ def register(self, doc_key: str, chunk_ids: list) -> None:
+ """Called once per document after chunking, with the ids of its chunks."""
+ try:
+ if not self._extraction_on or not chunk_ids:
+ self._completed += 1
+ self._emit()
+ return
+ self._doc_remaining[doc_key] = len(chunk_ids)
+ for cid in chunk_ids:
+ self._chunk_to_doc[cid] = doc_key
+ except Exception:
+ pass
+
+ def chunk_done(self, chunk_id: str) -> None:
+ """Called after a chunk finishes extraction. Ticks the doc's counter and
+ advances the bar when the document's last chunk clears. Unknown chunk ids
+ (e.g. residual orphans streamed outside the new-doc pipeline) are ignored."""
+ try:
+ doc = self._chunk_to_doc.pop(chunk_id, None)
+ if doc is None:
+ return
+ remaining = self._doc_remaining.get(doc, 0) - 1
+ if remaining <= 0:
+ self._doc_remaining.pop(doc, None)
+ self._completed += 1
+ self._emit()
+ else:
+ self._doc_remaining[doc] = remaining
+ except Exception:
+ pass
+
+ def _emit(self) -> None:
+ if self._report is None or self._total <= 0:
+ return
+ completed = min(self._completed, self._total)
+ pct = min(100, int(100 * completed / self._total))
+ try:
+ self._report(
+ f"Processing documents ({completed}/{self._total} — {pct}%)",
+ current=completed,
+ total=self._total,
+ )
+ except Exception:
+ pass
+
async def stream_docs(
conn: AsyncTigerGraphConnection,
docs_chan: Channel,
@@ -57,10 +133,9 @@ async def stream_docs(
Streams the document contents into the docs_chan, over ``ttl_batches``
partitions (each StreamIds call claims and returns one partition).
- *progress* (optional) is a callable invoked once when document
- streaming completes — runtime hands the rebuild status forward
- from "Chunking documents" to "Extracting entities and
- relationships" at that boundary.
+ *progress* is accepted for API compatibility with callers but is
+ not used here — the UI stage advances after chunk_docs finishes,
+ not when streaming completes.
"""
logger.info(f"streaming docs ({ttl_batches} batches)")
n_docs = 0
@@ -87,11 +162,9 @@ async def stream_docs(
# close the docs chan -- this function is the only sender
logger.info("closing docs chan")
docs_chan.close()
- if progress is not None:
- try:
- progress("Extracting entities and relationships")
- except Exception:
- pass
+ # Do NOT advance the UI stage here. Streaming finishing does not
+ # mean chunking is done; advancing here used to clear the chunking
+ # progress bar before chunk_docs finished (and before the UI polled).
async def stream_chunks(
conn: AsyncTigerGraphConnection,
@@ -163,23 +236,34 @@ async def chunk_docs(
embed_chan: Channel,
upsert_chan: Channel,
extract_chan: Channel,
+ progress=None,
+ total_docs: int = 0,
+ tracker: "_DocProgress | None" = None,
):
"""
Creates and starts one worker for each document
in the docs channel.
+
+ Document-level progress for the merged 'Processing documents' stage is
+ driven by *tracker*, which advances the bar as each document finishes
+ extraction (see :class:`_DocProgress`). This function no longer reports its
+ own chunking percentage — the tracker is the single source of truth.
"""
logger.info("Chunk Processing Start")
- doc_tasks = []
n_docs = 0
+
+ async def _chunk_one(content):
+ nonlocal n_docs
+ await workers.chunk_doc(
+ conn, content, upsert_chan, embed_chan, extract_chan, tracker=tracker
+ )
+ n_docs += 1
+
async with asyncio.TaskGroup() as grp:
while True:
try:
content = await docs_chan.get()
- n_docs += 1
- task = grp.create_task(
- workers.chunk_doc(conn, content, upsert_chan, embed_chan, extract_chan)
- )
- doc_tasks.append(task)
+ grp.create_task(_chunk_one(content))
except ChannelClosed:
break
except Exception:
@@ -383,6 +467,7 @@ async def extract(
extractor: BaseExtractor,
conn: AsyncTigerGraphConnection,
num_senders: int,
+ tracker: "_DocProgress | None" = None,
):
"""
Creates and starts one worker for each extract job
@@ -390,6 +475,17 @@ async def extract(
(chunk , chunk_id) <- q.get()
"""
logger.info("Entity Extration Start")
+
+ async def _extract_one(itm):
+ # itm == (chunk, chunk_id); tick the document tracker once this chunk's
+ # extraction is done (even on error) so the 'Processing documents' bar
+ # advances at extraction pace.
+ try:
+ await workers.extract(upsert_chan, embed_chan, extractor, conn, *itm)
+ finally:
+ if tracker is not None:
+ tracker.chunk_done(itm[1])
+
# consume task queue
n_chunks = 0
async with asyncio.TaskGroup() as grp:
@@ -404,9 +500,7 @@ async def extract(
break
else:
if entity_extraction_switch:
- grp.create_task(
- workers.extract(upsert_chan, embed_chan, extractor, conn, *item)
- )
+ grp.create_task(_extract_one(item))
n_chunks += 1
if n_chunks % 50 == 0:
logger.info(
@@ -425,12 +519,20 @@ async def extract(
embed_chan.close()
-async def communities(conn: AsyncTigerGraphConnection, comm_process_chan: Channel):
+async def communities(conn: AsyncTigerGraphConnection, comm_process_chan: Channel, report=None):
"""
Run louvain
"""
+ def _level(n):
+ if report is not None:
+ try:
+ report(f"Detecting communities — level {n}", clear_progress=True)
+ except Exception:
+ pass
+
# first pass: Group Entities into Communities
logger.info("Initializing Communities (first louvain pass)")
+ _level(1)
async with tg_sem:
try:
@@ -455,7 +557,7 @@ async def communities(conn: AsyncTigerGraphConnection, comm_process_chan: Channe
mod = res[0]["mod"]
logger.info(f"****mod pass 1: {mod}")
- await stream_communities(conn, 1, comm_process_chan)
+ await stream_communities(conn, 1, comm_process_chan, report=report)
# nth pass: Iterate on Communities until modularity stops increasing
prev_mod = -10
@@ -464,6 +566,7 @@ async def communities(conn: AsyncTigerGraphConnection, comm_process_chan: Channe
prev_mod = mod
i += 1
logger.info(f"Running louvain on Communities (iteration: {i})")
+ _level(i + 1)
# louvain pass
async with tg_sem:
res = await conn.runInstalledQuery(
@@ -480,7 +583,7 @@ async def communities(conn: AsyncTigerGraphConnection, comm_process_chan: Channe
mod = res[0]["mod"]
logger.info(f"mod pass {i+1}: {mod} (diff= {abs(prev_mod - mod)})")
# write iter to chan for layer to be processed
- await stream_communities(conn, i + 1, comm_process_chan)
+ await stream_communities(conn, i + 1, comm_process_chan, report=report)
if mod == 0 or mod - prev_mod <= -0.05:
break
@@ -496,6 +599,7 @@ async def stream_communities(
conn: AsyncTigerGraphConnection,
i: int,
comm_process_chan: Channel,
+ report=None,
):
"""
Streams Community IDs from the grpah for a given iteration (from the channel)
@@ -519,10 +623,48 @@ async def stream_communities(
# Wait for all communities for layer i to be processed before doing next layer
# all community descriptions must be populated before the next layer can be processed
if len(comms) > 0:
+ wait_interval = 5
+ # Give up waiting once no new community has been described for longer
+ # than one summarization timeout (+ margin). With the fast-fail timeout
+ # and circuit breaker upstream, failures write a placeholder quickly, so
+ # this only trips if summarization is truly stuck — never an infinite loop.
+ stall_limit_s = workers._SUMMARY_TIMEOUT_S + 60
+ last_described = -1
+ stalled_for = 0
n_waits = 0
- while not await check_vertex_has_desc(conn, i):
- logger.info(f"Waiting for layer{i} to finish processing")
- await asyncio.sleep(5)
+ while True:
+ progress = await community_desc_progress(conn, i)
+ if progress is None:
+ # progress query failed; treat as no forward progress
+ all_have, described, total = False, last_described, None
+ else:
+ all_have, described, total = progress
+ if report is not None and total:
+ try:
+ report(
+ f"Summarizing communities — level {i} ({described}/{total})",
+ current=described,
+ total=total,
+ )
+ except Exception:
+ pass
+ if all_have:
+ break
+ if described > last_described:
+ last_described = described
+ stalled_for = 0
+ else:
+ stalled_for += wait_interval
+ if stalled_for >= stall_limit_s:
+ logger.error(
+ f"Layer {i} summarization stalled at {described}/{total} "
+ f"for {stalled_for}s; abandoning wait and moving on."
+ )
+ break
+ logger.info(
+ f"Waiting for layer{i} to finish processing ({described}/{total})"
+ )
+ await asyncio.sleep(wait_interval)
n_waits += 1
if n_waits > 3:
logger.info("Flushing load_q")
@@ -536,6 +678,7 @@ async def summarize_communities(
comm_process_chan: Channel,
upsert_chan: Channel,
embed_chan: Channel,
+ breaker: "workers.CommunitySummaryBreaker",
):
logger.info("Community summarization started")
n_comm = 0
@@ -543,7 +686,7 @@ async def summarize_communities(
while True:
try:
c = await comm_process_chan.get()
- tg.create_task(workers.process_community(conn, upsert_chan, embed_chan, *c))
+ tg.create_task(workers.process_community(conn, upsert_chan, embed_chan, breaker, *c))
logger.debug(f"Added community to process: {c}")
n_comm += 1
# Per-community summarization can take 30s; emit a
@@ -563,6 +706,12 @@ async def summarize_communities(
logger.info(
f"Community summarization done: {n_comm} communities dispatched"
)
+ if breaker.incomplete:
+ logger.warning(
+ f"{breaker.incomplete} community summaries could not be generated "
+ f"(LLM provider errors) and were left as placeholders; regenerate "
+ f"them once connectivity is restored."
+ )
async def run(graphname: str, conn: AsyncTigerGraphConnection, progress=None):
@@ -582,26 +731,43 @@ async def run(graphname: str, conn: AsyncTigerGraphConnection, progress=None):
where the job is.
"""
- def _report(msg: str) -> None:
+ def _report(msg: str, current=None, total=None, clear_progress=False) -> None:
if progress is None:
return
try:
- progress(msg)
+ progress(
+ msg,
+ current=current,
+ total=total,
+ clear_progress=clear_progress,
+ )
+ except TypeError:
+ try:
+ progress(msg)
+ except Exception:
+ pass
except Exception:
pass
+ # Summary bubbled up to run_with_tracking for the completion status /
+ # partial-success message.
+ run_summary = {"communities_incomplete": 0, "warnings": []}
+
_report("Preparing rebuild")
extractor, embedding_store = await init(conn)
init_start = time.perf_counter()
if doc_process_switch:
- _report("Chunking documents")
+ _report("Processing documents")
logger.info("Doc Processing Start")
docs_chan = Channel(1)
embed_chan = Channel()
upsert_chan = Channel()
extract_chan = Channel()
num_chunk_senders = 2
+ # One bar for the merged chunk+extract phase; it advances as each
+ # document finishes extraction (see _DocProgress).
+ doc_tracker = _DocProgress(_report, entity_extraction_switch)
async with asyncio.TaskGroup() as grp:
# PHASE 1 — residual chunk sweep
@@ -623,12 +789,40 @@ def _report(msg: str) -> None:
# remaining producer racing chunk_docs' load_q writes.
async def new_doc_pipeline():
await sc_task
+ # Count unprocessed Documents before StreamIds claims them,
+ # so chunking can report document-level % progress.
+ total_docs = 0
+ try:
+ count_result = conn.getVertexCount(
+ "Document", where="epoch_processed=0"
+ )
+ if asyncio.iscoroutine(count_result):
+ count_result = await count_result
+ total_docs = int(count_result or 0)
+ except Exception as e:
+ logger.warning(
+ f"Could not count unprocessed Documents for progress: {e}"
+ )
+ if total_docs > 0:
+ doc_tracker.set_total(total_docs)
+ logger.info(
+ f"Processing-documents denominator: {total_docs} unprocessed Document(s)"
+ )
async with asyncio.TaskGroup() as inner:
inner.create_task(
stream_docs(conn, docs_chan, 100, progress=progress)
)
inner.create_task(
- chunk_docs(conn, docs_chan, embed_chan, upsert_chan, extract_chan)
+ chunk_docs(
+ conn,
+ docs_chan,
+ embed_chan,
+ upsert_chan,
+ extract_chan,
+ progress=progress,
+ total_docs=total_docs,
+ tracker=doc_tracker,
+ )
)
grp.create_task(new_doc_pipeline())
@@ -636,7 +830,7 @@ async def new_doc_pipeline():
grp.create_task(load(conn))
grp.create_task(embed(embed_chan, embedding_store, graphname))
grp.create_task(
- extract(extract_chan, upsert_chan, embed_chan, extractor, conn, num_chunk_senders)
+ extract(extract_chan, upsert_chan, embed_chan, extractor, conn, num_chunk_senders, tracker=doc_tracker)
)
logger.info("Join docs_chan")
await docs_chan.join()
@@ -661,7 +855,7 @@ async def new_doc_pipeline():
# schema edits could still leave queries missing.
community_start = time.perf_counter()
if community_detection_switch:
- _report("Detecting communities")
+ _report("Detecting communities", clear_progress=True)
await install_queries(COMMUNITY_QUERIES, conn)
logger.info("Community Processing Start")
@@ -681,13 +875,16 @@ async def new_doc_pipeline():
upsert_chan = Channel()
embed_chan = Channel()
load_q.reopen()
+ # Breaker is created here (not inside summarize_communities) so its
+ # incomplete count can bubble up into the rebuild's completion summary.
+ comm_breaker = workers.CommunitySummaryBreaker()
async with asyncio.TaskGroup() as grp:
# run louvain
# get the communities
- grp.create_task(communities(conn, comm_process_chan))
+ grp.create_task(communities(conn, comm_process_chan, report=_report))
# summarize each community
grp.create_task(
- summarize_communities(conn, comm_process_chan, upsert_chan, embed_chan)
+ summarize_communities(conn, comm_process_chan, upsert_chan, embed_chan, comm_breaker)
)
grp.create_task(upsert(upsert_chan))
grp.create_task(load(conn))
@@ -699,6 +896,18 @@ async def new_doc_pipeline():
logger.info("Join upsert_chan")
await upsert_chan.join()
+ # Record community summaries left incomplete (LLM provider errors) so
+ # the rebuild can end with a partial-success warning instead of a flat
+ # green success.
+ if comm_breaker.incomplete:
+ run_summary["communities_incomplete"] = comm_breaker.incomplete
+ run_summary["warnings"].append(
+ f"{comm_breaker.incomplete} community "
+ f"{'summary' if comm_breaker.incomplete == 1 else 'summaries'} "
+ f"could not be generated (language model unavailable); "
+ f"regenerate them from the graph admin page."
+ )
+
# Mirror Entity → Community memberships onto domain-VT instances
# that share the same id.
try:
@@ -721,7 +930,7 @@ async def new_doc_pipeline():
f"IN_COMMUNITY pair missing on schema"
)
if mirrorable:
- _report("Updating domain types")
+ _report("Updating domain types", clear_progress=True)
await graphrag_mirror_communities(conn, mirrorable)
community_end = time.perf_counter()
logger.info("Community Processing End")
@@ -768,3 +977,5 @@ async def new_doc_pipeline():
)
else:
logger.info("Post-pipeline check: all loading jobs are intact.")
+
+ return run_summary
diff --git a/ecc/app/graphrag/util.py b/ecc/app/graphrag/util.py
index 2fad066f..735ccf5f 100644
--- a/ecc/app/graphrag/util.py
+++ b/ecc/app/graphrag/util.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import base64
@@ -65,6 +65,20 @@
loading_event = asyncio.Event()
loading_event.set() # set the event to true to allow the workers to run
+# Written as a community's description when summarization can't produce a real
+# one. Non-empty so the layer-completion check passes and the rebuild finishes,
+# and stable so it can be found and regenerated later.
+COMMUNITY_SUMMARY_PLACEHOLDER = "[summary unavailable - regenerate]"
+# Placeholder written by pre-2.0.1 builds; kept so re-summarization and progress
+# checks recognize communities left behind by older graphs too.
+LEGACY_SUMMARY_PLACEHOLDER = "Should ignore due to summary error."
+
+def is_placeholder_summary(text: str) -> bool:
+ """True if a community description is a placeholder needing regeneration:
+ the current or legacy sentinel, or empty."""
+ t = (text or "").strip()
+ return t in ("", COMMUNITY_SUMMARY_PLACEHOLDER, LEGACY_SUMMARY_PLACEHOLDER)
+
async def install_queries(
requried_queries: list[str],
conn: AsyncTigerGraphConnection,
@@ -607,7 +621,11 @@ async def get_commuinty_children(conn, i: int, c: str):
return descrs
-async def check_vertex_has_desc(conn, i: int):
+async def community_desc_progress(conn, i: int):
+ """Return (all_have_desc, described_count, total_count) for layer i, or
+ None if the progress query itself failed. `described_count` lets callers
+ detect forward progress and bail if summarization stalls."""
+ resp = None
try:
async with tg_sem:
resp = await conn.runInstalledQuery(
@@ -616,11 +634,18 @@ async def check_vertex_has_desc(conn, i: int):
)
except Exception as e:
logger.error(f"Check Vert Desc err:\n{e}")
+ return None
- res = resp[0]["all_have_desc"]
- logger.info(res)
+ try:
+ all_have = resp[0]["all_have_desc"]
+ described = resp[1]["described"]
+ total = resp[1]["total"]
+ except Exception as e:
+ logger.error(f"Check Vert Desc parse err:\n{e}")
+ return None
- return res
+ logger.info(f"layer {i} progress: {described}/{total} described")
+ return all_have, described, total
async def check_embedding_rebuilt(conn, v_type: str):
try:
diff --git a/ecc/app/graphrag/workers.py b/ecc/app/graphrag/workers.py
index a4746492..1dc7d1b9 100644
--- a/ecc/app/graphrag/workers.py
+++ b/ecc/app/graphrag/workers.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import base64
@@ -35,6 +35,58 @@
logger = logging.getLogger(__name__)
+# Community summarization is a small single-shot call; cap it well below the
+# provider's ~600s default so an unreachable provider fails fast instead of
+# hanging the whole community layer.
+_SUMMARY_TIMEOUT_S = 120
+# After this many consecutive connectivity failures, stop calling the provider
+# for the rest of this run — the remaining communities fall back immediately
+# rather than each burning a full timeout.
+_SUMMARY_CONN_FAILURE_THRESHOLD = 3
+
+
+class CommunitySummaryBreaker:
+ """Per-rebuild circuit breaker for community summarization. Once the LLM
+ provider looks unreachable, `open` flips true so remaining communities skip
+ the call and take the placeholder immediately."""
+
+ def __init__(self, threshold: int = _SUMMARY_CONN_FAILURE_THRESHOLD):
+ self.threshold = threshold
+ self._consecutive = 0
+ self.open = False
+ self.incomplete = 0 # communities left with a placeholder summary
+
+ def record_success(self):
+ self._consecutive = 0
+
+ def record_conn_failure(self):
+ self._consecutive += 1
+ if self._consecutive >= self.threshold and not self.open:
+ self.open = True
+ logger.error(
+ "Community summarization circuit breaker OPEN: LLM provider "
+ "appears unreachable; remaining communities will be left with "
+ "placeholder summaries for later regeneration."
+ )
+
+
+async def _summarize_once(summarizer, comm_id, children) -> dict:
+ """Run one summarization attempt with an explicit timeout so a hung
+ provider fails in _SUMMARY_TIMEOUT_S instead of the ~600s library default."""
+ try:
+ return await asyncio.wait_for(
+ summarizer.summarize(comm_id, children),
+ timeout=_SUMMARY_TIMEOUT_S,
+ )
+ except asyncio.TimeoutError:
+ return {
+ "error": True,
+ "summary": "",
+ "message": f"summarization timed out after {_SUMMARY_TIMEOUT_S}s",
+ "category": "connectivity",
+ }
+
+
async def install_query(
conn: AsyncTigerGraphConnection, query_path: str, install: bool = True
) -> dict[str, httpx.Response | str | None]:
@@ -81,6 +133,7 @@ async def chunk_doc(
upsert_chan: Channel,
embed_chan: Channel,
extract_chan: Channel,
+ tracker=None,
):
"""
Chunks a document.
@@ -98,7 +151,7 @@ async def chunk_doc(
chunker_type = doc["attributes"]["ctype"].lower().strip()
else:
chunker_type = ""
-
+
v_id = doc["v_id"].lower()
# Use get_chunker for all types (including images)
@@ -109,8 +162,13 @@ async def chunk_doc(
# v_id / chunk_id derive from user document content.
logger.debug(f"Chunking {v_id} into {len(chunks)} chunk(s)")
+ chunk_ids = [util.process_id(f"{v_id}_chunk_{i}") for i in range(len(chunks))]
+ # Register the document's chunks before dispatching any, so the extract
+ # worker can't complete a chunk before the tracker knows to expect it.
+ if tracker is not None:
+ tracker.register(v_id, chunk_ids)
for i, chunk in enumerate(chunks):
- chunk_id = util.process_id(f"{v_id}_chunk_{i}")
+ chunk_id = chunk_ids[i]
logger.debug(f"Processing chunk {chunk_id}")
# send chunks to be upserted (func, args)
@@ -760,6 +818,7 @@ async def process_community(
conn: AsyncTigerGraphConnection,
upsert_chan: Channel,
embed_chan: Channel,
+ breaker: CommunitySummaryBreaker,
i: int,
comm_id: str,
):
@@ -787,18 +846,40 @@ async def process_community(
# if the community only has one child, use its description
if len(children) == 1:
summary = children[0]
+ elif breaker.open:
+ # provider already confirmed unreachable this run: skip the call
+ summary = util.COMMUNITY_SUMMARY_PLACEHOLDER
+ breaker.incomplete += 1
else:
from common.config import get_llm_service, get_completion_config
llm = get_llm_service(get_completion_config(conn.graphname))
summarizer = community_summarizer.CommunitySummarizer(llm)
- summary = await summarizer.summarize(comm_id, children)
- if summary["error"]:
- summary = await summarizer.summarize(comm_id, children)
- if summary["error"]:
- logger.error(f"Failed to summarize community {comm_id} with message {summary['message']}")
- summary = "Should ignore due to summary error."
+ result = await _summarize_once(summarizer, comm_id, children)
+ if not result["error"]:
+ breaker.record_success()
+ summary = result["summary"]
+ elif result.get("category") == "connectivity":
+ # connectivity failure: record and DON'T retry — a second call
+ # would just burn another timeout against a down provider
+ breaker.record_conn_failure()
+ logger.error(
+ f"Failed to summarize community {comm_id} (connectivity): "
+ f"{result['message']}"
+ )
+ summary = util.COMMUNITY_SUMMARY_PLACEHOLDER
+ breaker.incomplete += 1
else:
- summary = summary["summary"]
+ # content/transient error: one retry may recover
+ result = await _summarize_once(summarizer, comm_id, children)
+ if not result["error"]:
+ breaker.record_success()
+ summary = result["summary"]
+ else:
+ logger.error(
+ f"Failed to summarize community {comm_id}: {result['message']}"
+ )
+ summary = util.COMMUNITY_SUMMARY_PLACEHOLDER
+ breaker.incomplete += 1
if not err:
logger.debug(f"Community {comm_id}: {children}, {summary}")
@@ -818,4 +899,7 @@ async def process_community(
)
# (v_id, content, index_name)
- await embed_chan.put((comm_id, summary, "Community"))
+ # Don't embed placeholder summaries — they'd pollute the Community
+ # vector index. They get an embedding when regenerated later.
+ if summary != util.COMMUNITY_SUMMARY_PLACEHOLDER:
+ await embed_chan.put((comm_id, summary, "Community"))
diff --git a/ecc/app/main.py b/ecc/app/main.py
index 9889dc02..5bcb8364 100644
--- a/ecc/app/main.py
+++ b/ecc/app/main.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import os
@@ -226,10 +226,15 @@ def rebuild_status(
"is_running": task_info.get("status") == "running",
"status": task_info.get("status"),
"stage": task_info.get("stage"),
+ "progress_current": task_info.get("progress_current"),
+ "progress_total": task_info.get("progress_total"),
+ "progress_pct": task_info.get("progress_pct"),
"started_at": task_info.get("started_at"),
"completed_at": task_info.get("completed_at"),
"failed_at": task_info.get("failed_at"),
- "error": task_info.get("error")
+ "error": task_info.get("error"),
+ "warnings": task_info.get("warnings"),
+ "communities_incomplete": task_info.get("communities_incomplete"),
}
return {
@@ -240,14 +245,33 @@ def rebuild_status(
}
-def _set_stage(task_key: str, msg: str) -> None:
+def _set_stage(
+ task_key: str,
+ msg: str,
+ current=None,
+ total=None,
+ clear_progress: bool = False,
+) -> None:
"""Update the human-readable stage label for an in-flight task.
- Pulled out so individual stage transitions don't have to know
- about the ``running_tasks`` schema.
+
+ Optional *current*/*total* populate a progress bar. Progress fields
+ are left unchanged unless new values are provided or
+ *clear_progress* is True — otherwise a later stage string (e.g.
+ from stream_docs finishing early) would wipe the chunking bar
+ before the UI can poll it.
"""
info = running_tasks.get(task_key)
- if info is not None:
- info["stage"] = msg
+ if info is None:
+ return
+ info["stage"] = msg
+ if current is not None and total is not None and total > 0:
+ info["progress_current"] = int(current)
+ info["progress_total"] = int(total)
+ info["progress_pct"] = min(100, int(100 * current / total))
+ elif clear_progress:
+ info.pop("progress_current", None)
+ info.pop("progress_total", None)
+ info.pop("progress_pct", None)
async def run_with_tracking(task_key: str, run_func, graphname: str, conn):
@@ -304,12 +328,30 @@ async def run_with_tracking(task_key: str, run_func, graphname: str, conn):
# ``run_func`` may ignore the kwarg (the supportai legacy path
# does); the call falls back to the no-progress signature on
# ``TypeError``.
- progress_cb = lambda msg: _set_stage(task_key, msg)
+ def progress_cb(msg, current=None, total=None, clear_progress=False):
+ _set_stage(
+ task_key,
+ msg,
+ current=current,
+ total=total,
+ clear_progress=clear_progress,
+ )
+
try:
- await run_func(graphname, conn, progress=progress_cb)
+ result = await run_func(graphname, conn, progress=progress_cb)
except TypeError:
- await run_func(graphname, conn)
- running_tasks[task_key] = {"status": "completed", "completed_at": time.time()}
+ result = await run_func(graphname, conn)
+ completion = {"status": "completed", "completed_at": time.time()}
+ # Carry any partial-success info (e.g. community summaries left
+ # incomplete) into the completion status so the UI can warn instead of
+ # reporting a flat success.
+ if isinstance(result, dict):
+ warnings = result.get("warnings") or []
+ if warnings:
+ completion["warnings"] = warnings
+ if result.get("communities_incomplete"):
+ completion["communities_incomplete"] = result["communities_incomplete"]
+ running_tasks[task_key] = completion
LogWriter.info(f"Completed ECC task: {task_key}")
except Exception as e:
running_tasks[task_key] = {"status": "failed", "error": str(e), "failed_at": time.time()}
diff --git a/ecc/app/supportai/supportai_init.py b/ecc/app/supportai/supportai_init.py
index 07b8eb07..df2f7491 100644
--- a/ecc/app/supportai/supportai_init.py
+++ b/ecc/app/supportai/supportai_init.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import logging
diff --git a/ecc/app/supportai/workers.py b/ecc/app/supportai/workers.py
index b80cb21e..3c969179 100644
--- a/ecc/app/supportai/workers.py
+++ b/ecc/app/supportai/workers.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import base64
import time
diff --git a/graphrag-ui/src/pages/setup/KGAdmin.tsx b/graphrag-ui/src/pages/setup/KGAdmin.tsx
index a2691a77..cd43337e 100644
--- a/graphrag-ui/src/pages/setup/KGAdmin.tsx
+++ b/graphrag-ui/src/pages/setup/KGAdmin.tsx
@@ -234,6 +234,7 @@ const KGAdmin = () => {
if (!open) {
setRefreshMessage("");
setPollingActive(false);
+ setRebuildProgress(null);
}
};
@@ -471,6 +472,13 @@ const KGAdmin = () => {
const isRebuildRunningRef = useRef(false);
const [isCheckingStatus, setIsCheckingStatus] = useState(false);
const [pollingActive, setPollingActive] = useState(false);
+ // Document-level chunking progress from ECC rebuild_status (optional).
+ const [rebuildProgress, setRebuildProgress] = useState<{
+ pct: number;
+ current: number;
+ total: number;
+ label: string;
+ } | null>(null);
// Load available graphs. First seed from sessionStorage so the
// dropdown shows something immediately, then refresh from
@@ -1124,20 +1132,54 @@ const KGAdmin = () => {
setRefreshMessage(
`⚠️ A rebuild is already in progress for "${graphName}" (started at ${startTime})${stage}. Please wait for it to complete.`
);
+ if (
+ typeof statusData.progress_pct === "number" &&
+ typeof statusData.progress_total === "number" &&
+ statusData.progress_total > 0
+ ) {
+ // Bar label = the stage name without its trailing "(n/total …)".
+ const stageStr =
+ typeof statusData.stage === "string" ? statusData.stage : "";
+ const label = stageStr.split(" (")[0] || "Processing";
+ setRebuildProgress({
+ pct: statusData.progress_pct,
+ current: statusData.progress_current ?? 0,
+ total: statusData.progress_total,
+ label,
+ });
+ } else {
+ // No progress fields → the current stage has no bar (e.g. community
+ // detection). Clear it.
+ setRebuildProgress(null);
+ }
} else if (wasRunning && statusData.status === "completed") {
- setRefreshMessage(`✅ Rebuild completed successfully for "${graphName}".`);
+ const warnings = Array.isArray(statusData.warnings)
+ ? statusData.warnings
+ : [];
+ if (warnings.length > 0) {
+ setRefreshMessage(
+ `⚠️ Rebuild for "${graphName}" completed with warnings: ${warnings.join(" ")}`
+ );
+ } else {
+ setRefreshMessage(`✅ Rebuild completed successfully for "${graphName}".`);
+ }
setPollingActive(false);
+ setRebuildProgress(null);
} else if (statusData.status === "failed") {
setRefreshMessage(`❌ Previous rebuild failed: ${statusData.error || "Unknown error"}`);
setPollingActive(false);
+ setRebuildProgress(null);
} else if (statusData.status === "error") {
setRefreshMessage(`❌ Failed to check rebuild status: ${statusData.error || "Unknown error"}`);
setPollingActive(false);
+ setRebuildProgress(null);
} else if (statusData.status === "unknown") {
setRefreshMessage(`⚠️ ECC service returned unknown status. It may be unavailable.`);
setPollingActive(false);
+ setRebuildProgress(null);
} else {
setRefreshMessage("");
+ setRebuildProgress(null);
}
} else {
setRefreshMessage(`❌ Failed to check rebuild status (HTTP ${statusResponse.status}).`);
@@ -2666,6 +2708,8 @@ const KGAdmin = () => {
+ )}
diff --git a/graphrag/app/agent/agent_generation.py b/graphrag/app/agent/agent_generation.py
index 1bcc6fc3..68074f33 100644
--- a/graphrag/app/agent/agent_generation.py
+++ b/graphrag/app/agent/agent_generation.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import logging
diff --git a/graphrag/app/agent/agent_graph.py b/graphrag/app/agent/agent_graph.py
index 384764dc..93c7350d 100644
--- a/graphrag/app/agent/agent_graph.py
+++ b/graphrag/app/agent/agent_graph.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import boto3
import os
diff --git a/graphrag/app/agent/agent_router.py b/graphrag/app/agent/agent_router.py
index 4bcb2146..52efd772 100644
--- a/graphrag/app/agent/agent_router.py
+++ b/graphrag/app/agent/agent_router.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import PydanticOutputParser
diff --git a/graphrag/app/agent/agentic_agent.py b/graphrag/app/agent/agentic_agent.py
index cf5326f2..77f32d14 100644
--- a/graphrag/app/agent/agentic_agent.py
+++ b/graphrag/app/agent/agentic_agent.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Agentic chat agent (v2.0 deep-thinking mode).
diff --git a/graphrag/app/agent/agentic_executor.py b/graphrag/app/agent/agentic_executor.py
index 7e9f4716..f4f660db 100644
--- a/graphrag/app/agent/agentic_executor.py
+++ b/graphrag/app/agent/agentic_executor.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Executor node for the agentic engine.
diff --git a/graphrag/app/agent/agentic_graph.py b/graphrag/app/agent/agentic_graph.py
index edc87b47..2644e625 100644
--- a/graphrag/app/agent/agentic_graph.py
+++ b/graphrag/app/agent/agentic_graph.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Agentic orchestration: plan -> execute -> (evaluate & maybe extend) ->
synthesize.
diff --git a/graphrag/app/agent/agentic_planner.py b/graphrag/app/agent/agentic_planner.py
index 2bd53e77..69d58d0f 100644
--- a/graphrag/app/agent/agentic_planner.py
+++ b/graphrag/app/agent/agentic_planner.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Planner node for the agentic engine.
diff --git a/graphrag/app/agent/agentic_react.py b/graphrag/app/agent/agentic_react.py
index 59715788..f8387200 100644
--- a/graphrag/app/agent/agentic_react.py
+++ b/graphrag/app/agent/agentic_react.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Agentic react orchestrator — free tool-calling loop.
diff --git a/graphrag/app/agent/agentic_synthesizer.py b/graphrag/app/agent/agentic_synthesizer.py
index 19bea581..7b8e2412 100644
--- a/graphrag/app/agent/agentic_synthesizer.py
+++ b/graphrag/app/agent/agentic_synthesizer.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Synthesizer node for the agentic engine.
diff --git a/graphrag/app/agent/method_selector.py b/graphrag/app/agent/method_selector.py
index d12fbc11..fece7dd9 100644
--- a/graphrag/app/agent/method_selector.py
+++ b/graphrag/app/agent/method_selector.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Auto-selection of GraphRAG retrieval method.
diff --git a/graphrag/app/main.py b/graphrag/app/main.py
index 724f47b3..56772e9e 100644
--- a/graphrag/app/main.py
+++ b/graphrag/app/main.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import logging
@@ -32,46 +32,23 @@
from common.logs.logwriter import LogWriter
from common.metrics.prometheus_metrics import metrics as pmetrics
-if PRODUCTION:
- app = FastAPI(
- title="TigerGraph GraphRAG", docs_url=None, redoc_url=None, openapi_url=None
- )
-else:
- app = FastAPI(title="TigerGraph GraphRAG")
+from contextlib import asynccontextmanager
-app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
-)
-app.include_router(routers.root_router, prefix=PATH_PREFIX)
-app.include_router(routers.inquiryai_router, prefix=PATH_PREFIX)
-app.include_router(routers.supportai_router, prefix=PATH_PREFIX)
-app.include_router(routers.queryai_router, prefix=PATH_PREFIX)
-app.include_router(routers.ui_router, prefix=PATH_PREFIX)
-app.include_router(routers.mcp_servers_router, prefix=PATH_PREFIX)
-
-
-@app.on_event("startup")
-async def _install_mcp_libraries() -> None:
- """Install the source tarballs referenced by configured stdio MCP servers
- (global + per-graph), so their console-script commands are available. Runs
- each boot, which is what makes them persist across container recreation.
- """
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ # --- startup ---
+ # Install source tarballs referenced by configured stdio MCP servers
+ # (global + per-graph) each boot, so their console-script commands persist
+ # across container recreation.
try:
from common.mcp_config import install_configured_libraries
install_configured_libraries()
except Exception as e:
logging.getLogger(__name__).warning(f"mcp library install failed: {e}")
-
-@app.on_event("startup")
-async def _check_agentic_capability() -> None:
- """Warn at boot if the configured chat model can't tool-call, so operators
- know the agentic engine will fall back to the classic engine."""
+ # Warn if the configured chat model can't tool-call, so operators know the
+ # agentic engine will fall back to the classic engine.
try:
from common.config import get_chat_config
from common.llm_services.capabilities import model_capabilities
@@ -87,12 +64,11 @@ async def _check_agentic_capability() -> None:
except Exception as e:
logging.getLogger(__name__).warning(f"agentic capability check skipped: {e}")
+ yield
-@app.on_event("shutdown")
-async def _shutdown_mcp_addons() -> None:
- """Close every cached external-MCP client and stop the dedicated event
- loop on app shutdown so stdio subprocesses don't outlive the worker.
- """
+ # --- shutdown ---
+ # Close every cached external-MCP client and stop the dedicated event loop
+ # so stdio subprocesses don't outlive the worker.
try:
from mcp_addons import shutdown_all, stop_loop, run_async
await run_async(shutdown_all())
@@ -101,6 +77,30 @@ async def _shutdown_mcp_addons() -> None:
logging.getLogger(__name__).warning(f"mcp_addons shutdown failed: {e}")
+if PRODUCTION:
+ app = FastAPI(
+ title="TigerGraph GraphRAG", docs_url=None, redoc_url=None, openapi_url=None,
+ lifespan=lifespan,
+ )
+else:
+ app = FastAPI(title="TigerGraph GraphRAG", lifespan=lifespan)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+app.include_router(routers.root_router, prefix=PATH_PREFIX)
+app.include_router(routers.inquiryai_router, prefix=PATH_PREFIX)
+app.include_router(routers.supportai_router, prefix=PATH_PREFIX)
+app.include_router(routers.queryai_router, prefix=PATH_PREFIX)
+app.include_router(routers.ui_router, prefix=PATH_PREFIX)
+app.include_router(routers.mcp_servers_router, prefix=PATH_PREFIX)
+
+
excluded_metrics_paths = ("/docs", "/openapi.json", "/metrics")
logger = logging.getLogger(__name__)
diff --git a/graphrag/app/mcp_addons/__init__.py b/graphrag/app/mcp_addons/__init__.py
index d14acc31..7578d105 100644
--- a/graphrag/app/mcp_addons/__init__.py
+++ b/graphrag/app/mcp_addons/__init__.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from mcp_addons.client_manager import (
McpClientManager,
diff --git a/graphrag/app/mcp_addons/client_manager.py b/graphrag/app/mcp_addons/client_manager.py
index eddf638f..91ed692d 100644
--- a/graphrag/app/mcp_addons/client_manager.py
+++ b/graphrag/app/mcp_addons/client_manager.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""External MCP-server client manager.
diff --git a/graphrag/app/mcp_addons/registry_adapter.py b/graphrag/app/mcp_addons/registry_adapter.py
index f8124b51..cf140500 100644
--- a/graphrag/app/mcp_addons/registry_adapter.py
+++ b/graphrag/app/mcp_addons/registry_adapter.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Adapt external MCP tools into the agentic tool registry.
diff --git a/graphrag/app/mcp_addons/result_normalize.py b/graphrag/app/mcp_addons/result_normalize.py
index 407d678e..4a34d859 100644
--- a/graphrag/app/mcp_addons/result_normalize.py
+++ b/graphrag/app/mcp_addons/result_normalize.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Translate an MCP ``CallToolResult`` into the agentic tool-result dict.
diff --git a/graphrag/app/mcp_addons/runtime.py b/graphrag/app/mcp_addons/runtime.py
index 7403928e..2d9d455b 100644
--- a/graphrag/app/mcp_addons/runtime.py
+++ b/graphrag/app/mcp_addons/runtime.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Sync ↔ async bridge for the external MCP client manager.
diff --git a/graphrag/app/routers/mcp_servers.py b/graphrag/app/routers/mcp_servers.py
index aa47eb75..4f5c1328 100644
--- a/graphrag/app/routers/mcp_servers.py
+++ b/graphrag/app/routers/mcp_servers.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""External MCP-server CRUD + test endpoints.
diff --git a/graphrag/app/routers/supportai.py b/graphrag/app/routers/supportai.py
index bb278050..196fc2c8 100644
--- a/graphrag/app/routers/supportai.py
+++ b/graphrag/app/routers/supportai.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import logging
diff --git a/graphrag/app/routers/ui.py b/graphrag/app/routers/ui.py
index 1b2682e3..c753fc37 100644
--- a/graphrag/app/routers/ui.py
+++ b/graphrag/app/routers/ui.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import base64
@@ -62,6 +62,10 @@
from common.metrics.prometheus_metrics import metrics as pmetrics
from common.metrics.tg_proxy import TigerGraphConnectionProxy
from common.utils.graph_locks import acquire_graph_lock, release_graph_lock, acquire_rebuild_lock, release_rebuild_lock, get_rebuilding_graph, get_current_operation
+
+# Cache the last successful ECC status response per graph so the UI
+# still sees started_at and stage when ECC is too busy to respond.
+_last_ecc_status_cache: dict = {}
from supportai import supportai
from common.py_schemas.schemas import (
AgentProgess,
@@ -2258,7 +2262,7 @@ async def rebuild_and_monitor():
elapsed = 0
while elapsed < max_wait_time:
- await asyncio.sleep(poll_interval) # Non-blocking sleep
+ await asyncio.sleep(poll_interval)
elapsed += poll_interval
try:
@@ -2272,6 +2276,11 @@ async def rebuild_and_monitor():
status_data = status_response.json()
is_running = status_data.get("is_running", False)
status = status_data.get("status", "unknown")
+
+ # Cache last known good response so the UI endpoint
+ # can fall back to it when ECC is too busy to respond.
+ if is_running and status_data.get("started_at"):
+ _last_ecc_status_cache[graphname] = status_data
# Log every minute to avoid spam
if elapsed % 60 == 0:
@@ -2280,6 +2289,7 @@ async def rebuild_and_monitor():
# Check if ALL stages are complete
if not is_running and status in ["completed", "failed", "idle"]:
LogWriter.info(f"ECC rebuild finished for {graphname} with status: {status} after {elapsed}s")
+ _last_ecc_status_cache.pop(graphname, None)
break
else:
LogWriter.warning(f"ECC status check returned {status_response.status_code} for {graphname}")
@@ -2290,12 +2300,17 @@ async def rebuild_and_monitor():
if elapsed >= max_wait_time:
LogWriter.error(f"ECC rebuild monitoring timed out for {graphname} after {max_wait_time}s")
+ _last_ecc_status_cache.pop(graphname, None)
except Exception as e:
LogWriter.error(f"Error during ECC rebuild monitoring for {graphname}: {e}")
import traceback
LogWriter.error(traceback.format_exc())
finally:
+ # Always drop cached status when monitoring ends (success,
+ # timeout, or unexpected failure) so timeout fallbacks do
+ # not keep reporting a stale rebuild as active.
+ _last_ecc_status_cache.pop(graphname, None)
# Release lock only after ALL stages complete (or timeout/error)
release_rebuild_lock(graphname)
LogWriter.info(f"Released global rebuild lock for {graphname}")
@@ -2342,12 +2357,15 @@ def get_rebuild_status(
"error": f"ECC service returned status {response.status_code}"
}
except httpx.TimeoutException as e:
- # ECC is busy (heavy processing) - assume rebuild is still running
+ # ECC is busy (heavy processing) - assume rebuild is still running.
+ # Return the last cached status so the UI keeps started_at and stage.
LogWriter.warning(f"ECC status check timed out (ECC may be busy): {str(e)}")
+ cached = _last_ecc_status_cache.get(graphname, {})
return {
+ **cached,
"graphname": graphname,
"is_running": True,
- "status": "unknown",
+ "status": cached.get("status", "unknown"),
"error": "ECC is busy processing, status check timed out. Rebuild likely still in progress."
}
except Exception as e:
diff --git a/graphrag/app/tools/find_existing_query.py b/graphrag/app/tools/find_existing_query.py
index d9e8009a..c9c25d6d 100644
--- a/graphrag/app/tools/find_existing_query.py
+++ b/graphrag/app/tools/find_existing_query.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import logging
diff --git a/graphrag/app/tools/generate_cypher.py b/graphrag/app/tools/generate_cypher.py
index 853a8a28..d9199de4 100644
--- a/graphrag/app/tools/generate_cypher.py
+++ b/graphrag/app/tools/generate_cypher.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
from typing import Iterable
diff --git a/graphrag/app/tools/generate_function.py b/graphrag/app/tools/generate_function.py
index 7061aebe..073cfe38 100644
--- a/graphrag/app/tools/generate_function.py
+++ b/graphrag/app/tools/generate_function.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import logging
diff --git a/graphrag/app/tools/generate_gsql.py b/graphrag/app/tools/generate_gsql.py
index bd05f1a3..8be2bbbe 100644
--- a/graphrag/app/tools/generate_gsql.py
+++ b/graphrag/app/tools/generate_gsql.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import logging
from typing import Iterable
diff --git a/graphrag/app/tools/graphrag_tools.py b/graphrag/app/tools/graphrag_tools.py
index 4ac2009a..ca4b9f93 100644
--- a/graphrag/app/tools/graphrag_tools.py
+++ b/graphrag/app/tools/graphrag_tools.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""GraphRAG tools for the agentic engine.
diff --git a/graphrag/app/tools/map_question_to_schema.py b/graphrag/app/tools/map_question_to_schema.py
index d9d8bfae..35d742dd 100644
--- a/graphrag/app/tools/map_question_to_schema.py
+++ b/graphrag/app/tools/map_question_to_schema.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
from langchain_core.tools import BaseTool
from langchain_core.tools import ToolException
diff --git a/graphrag/app/tools/tg_mcp_tools.py b/graphrag/app/tools/tg_mcp_tools.py
index f05ab57a..c9d79792 100644
--- a/graphrag/app/tools/tg_mcp_tools.py
+++ b/graphrag/app/tools/tg_mcp_tools.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""tigergraph-mcp adapter — in-process, per-user.
diff --git a/graphrag/app/tools/tool_guards.py b/graphrag/app/tools/tool_guards.py
index e4e76d7d..46cd57e9 100644
--- a/graphrag/app/tools/tool_guards.py
+++ b/graphrag/app/tools/tool_guards.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Guardrails for agentic tool calls.
diff --git a/graphrag/app/tools/tool_registry.py b/graphrag/app/tools/tool_registry.py
index 63675387..e6d503aa 100644
--- a/graphrag/app/tools/tool_registry.py
+++ b/graphrag/app/tools/tool_registry.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Tool registry for the agentic engine.
diff --git a/graphrag/tests/regression/_container_sync.sh b/graphrag/tests/regression/_container_sync.sh
new file mode 100755
index 00000000..6fa48e5f
--- /dev/null
+++ b/graphrag/tests/regression/_container_sync.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Shared helpers for the regression run_*.sh scripts.
+#
+# The regression code and test_questions datasets are NOT baked into the
+# graphrag image and are no longer bind-mounted. Instead they are copied into
+# the running container on demand, right before a run — so the default
+# `docker compose up` carries no test artifacts, and nothing needs to be
+# installed on the host. Copies are refreshed on every call (idempotent).
+
+# sync_regression_to_container
+# Copies and its sibling ../test_questions into
+# /code/tests/{regression,test_questions} in the container.
+sync_regression_to_container() {
+ local container="$1"
+ local reg_dir="$2"
+ local tq_dir
+ tq_dir="$(cd "${reg_dir}/../test_questions" && pwd)"
+ docker exec "${container}" sh -c \
+ "rm -rf /code/tests && mkdir -p /code/tests/regression /code/tests/test_questions"
+ docker cp "${reg_dir}/." "${container}:/code/tests/regression/"
+ docker cp "${tq_dir}/." "${container}:/code/tests/test_questions/"
+}
+
+# copy_results_from_container
+# Brings the eval results written inside the container back to the host,
+# replacing what the old bind mount did automatically.
+copy_results_from_container() {
+ local container="$1"
+ local reg_dir="$2"
+ mkdir -p "${reg_dir}/results"
+ docker cp "${container}:/code/tests/regression/results/." "${reg_dir}/results/" 2>/dev/null || true
+}
diff --git a/graphrag/tests/regression/evaluator.py b/graphrag/tests/regression/evaluator.py
new file mode 100644
index 00000000..3638fd44
--- /dev/null
+++ b/graphrag/tests/regression/evaluator.py
@@ -0,0 +1,798 @@
+"""GraphRAG Regression Evaluator
+
+Scores a live GraphRAG graph against a labelled dataset using two metrics:
+ 1. Hallucination — TigerGraphAgentHallucinationCheck (confidence 0–1)
+ 2. Answer Correctness — DeepEval GEval (requires answers.csv)
+
+Dataset layout expected:
+ test_questions//
+ ├── data/ documents for ingest
+ ├── questions.csv single column: question
+ ├── answers.csv single column: ground_truth (optional)
+ └── ExportedGraph/ pre-built graph for --load-exported mode
+
+Run via:
+ ./graphrag/tests/regression/run_eval.sh --dataset --graphname
+ ./graphrag/tests/regression/run_eval.sh ... --detailed (shows per-question reasons)
+"""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import json
+import logging
+import os
+import sys
+import time
+import warnings
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import asdict, dataclass, field
+from datetime import datetime
+from typing import List, Optional, Tuple
+
+# Silence DeepEval's progress banner + telemetry. Must be set before deepeval
+# is imported anywhere (it is imported lazily inside answer_correctness).
+os.environ.setdefault("DEEPEVAL_DISABLE_INDICATOR", "YES")
+os.environ.setdefault("DEEPEVAL_TELEMETRY_OPT_OUT", "YES")
+
+# Some libraries (langchain, opentelemetry, pyTigerGraph …) re-arm the warnings
+# filter on import, so PYTHONWARNINGS / simplefilter alone don't hold. Replacing
+# showwarning with a no-op drops every warning no matter what filter is active.
+warnings.filterwarnings("ignore")
+warnings.showwarning = lambda *a, **k: None
+
+import httpx
+
+# Python sets sys.path[0] to the script's directory, not /code, so `import common`
+# and `import agent` fail without this. /code is where the GraphRAG app lives in
+# the container (see Dockerfile: COPY graphrag/app /code && COPY common /code/common).
+if "/code" not in sys.path:
+ sys.path.insert(0, "/code")
+
+logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
+
+# ANSI colours for clean CLI output. NO_COLOR disables; FORCE_COLOR forces on
+# (needed under `docker exec` where stdout is often not a detected TTY).
+if os.environ.get("NO_COLOR"):
+ _USE_COLOR = False
+elif os.environ.get("FORCE_COLOR"):
+ _USE_COLOR = True
+else:
+ _USE_COLOR = sys.stdout.isatty()
+_G = "\033[32m" if _USE_COLOR else "" # green
+_R = "\033[31m" if _USE_COLOR else "" # red
+_Y = "\033[33m" if _USE_COLOR else "" # yellow
+_C = "\033[36m" if _USE_COLOR else "" # cyan
+_B = "\033[1m" if _USE_COLOR else "" # bold
+_X = "\033[0m" if _USE_COLOR else "" # reset
+
+_HALLUCINATION_THRESHOLD = 0.5 # confidence above which an answer is flagged hallucinated
+_MAX_RETRIES = 3 # LLM metric call retries on transient errors
+_RETRY_DELAY = 5.0 # base back-off seconds between retries (doubles each attempt)
+_RETRY_ERRORS = (
+ "APIConnectionError", "ConnectionError", "RateLimitError",
+ "Timeout", "TimeoutError", "ServiceUnavailableError",
+)
+_MAX_CHUNKS = 50 # max context passages passed to the hallucination checker
+_MAX_CHUNK_CHARS = 3000 # each passage is truncated to this many characters
+
+
+# ─── Data types ───────────────────────────────────────────────────────────────
+
+@dataclass
+class EvalQuestion:
+ question: str
+ ground_truth: Optional[str]
+
+
+@dataclass
+class EvalResult:
+ # ── written to CSV ────────────────────────────────────────────────────────
+ index: int
+ question: str
+ ground_truth: Optional[str] = None
+ generated_answer: str = ""
+ agent_mode: Optional[str] = None
+ search_type_used: Optional[str] = None
+ retrieved_context: Optional[str] = None
+ answer_correctness: Optional[float] = None
+ answer_correctness_reason: Optional[str] = None
+ hallucination: Optional[str] = None
+ hallucination_confidence: Optional[float]= None
+ hallucination_reason: Optional[str] = None
+ response_time_seconds: float = 0.0
+ # ── CLI-only (not written to CSV) ─────────────────────────────────────────
+ answered_question: bool = field(default=False, repr=False)
+ error: Optional[str] = field(default=None, repr=False)
+ metric_errors: dict = field(default_factory=dict, repr=False)
+
+
+# ─── Question loader ──────────────────────────────────────────────────────────
+
+def _detect_encoding(path: str) -> str:
+ """Detect CSV encoding. Handles UTF-8 with BOM (Excel default), plain UTF-8,
+ Shift-JIS, and other encodings via chardet fallback."""
+ with open(path, "rb") as f:
+ raw = f.read(4)
+ if raw[:3] == b"\xef\xbb\xbf":
+ return "utf-8-sig" # UTF-8 with BOM — Excel's default UTF-8 export
+ try:
+ import chardet
+ with open(path, "rb") as f:
+ detected = chardet.detect(f.read())
+ enc = detected.get("encoding") or "utf-8"
+ confidence = detected.get("confidence", 0)
+ return enc if confidence >= 0.5 else "utf-8"
+ except ImportError:
+ return "utf-8"
+
+
+def _read_single_column(path: str, column: str) -> List[str]:
+ """Read one column from a single-column CSV.
+
+ These CSVs have exactly one data column (question or ground_truth).
+ csv.DictReader splits unquoted values that contain commas (e.g. Japanese
+ numbers like 2,693) into multiple fields and corrupts the data. We use
+ csv.reader, which correctly handles quoted multi-line fields, then
+ re-join any extra fields that were produced by unquoted commas so the
+ full original value is always returned.
+ """
+ encoding = _detect_encoding(path)
+ with open(path, newline="", encoding=encoding) as f:
+ reader = csv.reader(f)
+ rows = list(reader)
+
+ if not rows:
+ sys.exit(f"ERROR: {os.path.basename(path)} is empty.")
+
+ header = rows[0]
+ try:
+ col_idx = header.index(column)
+ except ValueError:
+ sys.exit(
+ f"ERROR: {os.path.basename(path)} must have a '{column}' column. "
+ f"Found: {header}"
+ )
+
+ results = []
+ for row in rows[1:]:
+ if not row:
+ continue
+ # If the row has more fields than the header, the value contained
+ # unquoted commas and was split — re-join everything from col_idx
+ # onward to restore the original string.
+ value = ",".join(row[col_idx:]).strip()
+ if value:
+ results.append(value)
+ return results
+
+
+def load_questions(dataset_dir: str) -> List[EvalQuestion]:
+ """Load questions.csv and (optionally) answers.csv from dataset_dir.
+
+ questions.csv — required, single column: question
+ answers.csv — optional, single column: ground_truth
+ rows are zipped with questions by index
+ """
+ q_path = os.path.join(dataset_dir, "questions.csv")
+ a_path = os.path.join(dataset_dir, "answers.csv")
+
+ if not os.path.exists(q_path):
+ sys.exit(f"ERROR: questions.csv not found at {q_path}")
+
+ questions = _read_single_column(q_path, "question")
+
+ ground_truths: List[Optional[str]] = [None] * len(questions)
+ if os.path.exists(a_path):
+ answers = _read_single_column(a_path, "ground_truth")
+ if len(answers) != len(questions):
+ sys.exit(
+ f"ERROR: questions.csv has {len(questions)} rows but "
+ f"answers.csv has {len(answers)} rows — they must match."
+ )
+ ground_truths = [a or None for a in answers]
+
+ return [
+ EvalQuestion(question=q, ground_truth=gt)
+ for q, gt in zip(questions, ground_truths)
+ ]
+
+
+# ─── Answer Correctness (DeepEval GEval) ─────────────────────────────────────
+
+_EVALUATION_STEPS = [
+ "Check whether the facts in the actual output contradict any facts in the expected output.",
+ "Lightly penalize omissions of detail — focus on whether the main idea is correct.",
+ "Vague language or differing opinions (without factual contradiction) are acceptable.",
+]
+
+def _build_deepeval_llm():
+ import re as _re
+ from deepeval.models.base_model import DeepEvalBaseLLM
+ from langchain_core.messages import HumanMessage
+ from common.config import get_chat_config, get_llm_service
+
+ cfg = get_chat_config()
+ llm_provider = get_llm_service(cfg)
+ model_name = cfg.get("llm_model", "unknown")
+ lc_model = getattr(llm_provider, "llm", None) or llm_provider
+
+ def _parse(text, schema):
+ try:
+ m = _re.search(r"\{.*\}", text, _re.DOTALL)
+ if m:
+ return schema(**json.loads(m.group()))
+ except Exception:
+ pass
+ return text
+
+ class _Judge(DeepEvalBaseLLM):
+ def __init__(self):
+ super().__init__(model_name)
+
+ def load_model(self):
+ return lc_model
+
+ def generate(self, prompt: str, schema=None):
+ resp = lc_model.invoke([HumanMessage(content=prompt)])
+ text = resp.content if hasattr(resp, "content") else str(resp)
+ return _parse(text, schema) if schema else text
+
+ async def a_generate(self, prompt: str, schema=None):
+ resp = await lc_model.ainvoke([HumanMessage(content=prompt)])
+ text = resp.content if hasattr(resp, "content") else str(resp)
+ return _parse(text, schema) if schema else text
+
+ def get_model_name(self) -> str:
+ return model_name
+
+ return _Judge()
+
+
+def answer_correctness(
+ question: str,
+ generated_answer: str,
+ ground_truth: str,
+) -> Tuple[Optional[float], Optional[str], Optional[str]]:
+ """Returns (score 0–1, reason, error). score/reason are None on failure."""
+ if not ground_truth:
+ return None, None, "no ground truth provided"
+
+ try:
+ import asyncio
+ from deepeval.metrics import GEval
+ from deepeval.test_case import LLMTestCase, LLMTestCaseParams
+ except ImportError as e:
+ return None, None, f"deepeval not installed: {e}"
+
+ try:
+ judge = _build_deepeval_llm()
+ except Exception as e:
+ return None, None, f"judge init failed: {e}"
+
+ metric = GEval(
+ name="Answer Correctness",
+ model=judge,
+ evaluation_steps=_EVALUATION_STEPS,
+ evaluation_params=[
+ LLMTestCaseParams.INPUT,
+ LLMTestCaseParams.ACTUAL_OUTPUT,
+ LLMTestCaseParams.EXPECTED_OUTPUT,
+ ],
+ )
+ test_case = LLMTestCase(
+ input=question,
+ actual_output=generated_answer,
+ expected_output=ground_truth,
+ )
+
+ last_err: Optional[Exception] = None
+ for attempt in range(1, _MAX_RETRIES + 1):
+ try:
+ # _show_indicator=False suppresses DeepEval's "✨ You're running…" line
+ try:
+ asyncio.run(metric.a_measure(test_case, _show_indicator=False))
+ except TypeError:
+ asyncio.run(metric.a_measure(test_case))
+ last_err = None
+ break
+ except Exception as e:
+ last_err = e
+ err_type = type(e).__name__
+ retryable = any(r in err_type or r in str(e) for r in _RETRY_ERRORS)
+ if retryable and attempt < _MAX_RETRIES:
+ time.sleep(_RETRY_DELAY * (2 ** (attempt - 1)))
+ else:
+ break
+
+ if last_err is not None:
+ return None, None, f"{type(last_err).__name__}: {last_err}"
+
+ return (
+ float(metric.score) if metric.score is not None else None,
+ str(metric.reason).strip() if metric.reason else None,
+ None,
+ )
+
+
+# ─── Hallucination check ──────────────────────────────────────────────────────
+
+def hallucination_check(
+ question: str,
+ generation: str,
+ context: str,
+) -> Tuple[Optional[str], Optional[float], Optional[str], Optional[str]]:
+ """Returns (verdict, confidence, reason, error).
+ verdict is 'yes' (hallucinated) or 'no' (grounded).
+ """
+ if not context:
+ return None, None, None, "no retrieved context to check against"
+
+ try:
+ from common.config import get_chat_config, get_llm_service
+ # Regression-only graded grader (0-1 confidence), kept in this folder so
+ # it stays independent of the production binary hallucination check.
+ from hallucination_check import (
+ TigerGraphAgentHallucinationCheck,
+ )
+
+ cfg = get_chat_config()
+ llm = get_llm_service(cfg)
+ result = TigerGraphAgentHallucinationCheck(llm).check_hallucination(
+ generation=generation,
+ context=context,
+ question=question,
+ )
+ confidence = max(0.0, min(1.0, float(result.confidence)))
+ verdict = "yes" if confidence >= _HALLUCINATION_THRESHOLD else "no"
+ return verdict, confidence, str(result.reason).strip() if result.reason else None, None
+ except Exception as e:
+ return None, None, None, f"{type(e).__name__}: {e}"
+
+
+# ─── Context extraction ───────────────────────────────────────────────────────
+
+def _flatten_context(query_sources: dict) -> List[str]:
+ """Extract text chunks from GraphRAG query_sources response."""
+ if not query_sources:
+ return []
+
+ try:
+ final_retrieval = query_sources["result"]["final_retrieval"]
+ if isinstance(final_retrieval, dict):
+ raw: List[str] = []
+ for chunks in final_retrieval.values():
+ if isinstance(chunks, list):
+ raw.extend(str(c) for c in chunks if c)
+ elif isinstance(chunks, str) and chunks.strip():
+ raw.append(chunks)
+ if raw:
+ seen: set = set()
+ out: List[str] = []
+ for c in raw:
+ c = c.strip()
+ if len(c) < 5 or c in seen:
+ continue
+ seen.add(c)
+ out.append(c[:_MAX_CHUNK_CHARS])
+ if len(out) >= _MAX_CHUNKS:
+ break
+ return out
+ except (KeyError, TypeError):
+ pass
+
+ def _walk(node):
+ result: List[str] = []
+ if isinstance(node, str):
+ if node.strip():
+ result.append(node)
+ elif isinstance(node, list):
+ for item in node:
+ result.extend(_walk(item))
+ elif isinstance(node, dict):
+ for key in ("final_retrieval", "context", "contexts", "chunks",
+ "documents", "passages", "text", "result"):
+ if key in node:
+ result.extend(_walk(node[key]))
+ if not result:
+ for v in node.values():
+ result.extend(_walk(v))
+ return result
+
+ chunks = _walk(query_sources)
+ seen2: set = set()
+ out2: List[str] = []
+ for c in chunks:
+ c = c.strip()
+ if len(c) < 5 or c in seen2:
+ continue
+ seen2.add(c)
+ out2.append(c[:_MAX_CHUNK_CHARS])
+ if len(out2) >= _MAX_CHUNKS:
+ break
+ return out2
+
+
+# ─── Core eval loop ───────────────────────────────────────────────────────────
+
+def _query_graphrag(
+ url: str,
+ graphname: str,
+ username: str,
+ password: str,
+ question: str,
+ mode: str,
+ rag_pattern: str,
+) -> dict:
+ resp = httpx.get(
+ f"{url}/ui/{graphname}/query",
+ params={
+ "q": question,
+ "mode": mode,
+ "rag_pattern": rag_pattern,
+ "include_fields": "query_sources",
+ },
+ auth=(username, password),
+ timeout=120.0,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ # The /ui/query endpoint returns model_dump_json() (a string), which FastAPI
+ # JSON-encodes again, so resp.json() gives a str. Parse it a second time.
+ if isinstance(data, str):
+ import json as _json
+ data = _json.loads(data)
+ return data
+
+
+def _eval_one(
+ idx: int,
+ q: EvalQuestion,
+ graphname: str,
+ url: str,
+ username: str,
+ password: str,
+ mode: str,
+ rag_pattern: str,
+) -> EvalResult:
+ r = EvalResult(index=idx, question=q.question, ground_truth=q.ground_truth)
+ t0 = time.monotonic()
+
+ try:
+ data = _query_graphrag(url, graphname, username, password, q.question, mode, rag_pattern)
+ # Release 2.0.0: endpoint returns a Message object; answer is in "content"
+ r.generated_answer = data.get("content") or ""
+ r.answered_question = bool(data.get("answered_question", False))
+ query_sources = data.get("query_sources") or {}
+ # Map the internal chosen_retriever value to the same human-readable label
+ # the UI displays (matches CustomChatMessage.tsx). Falls back to response_type.
+ _RETRIEVER_LABELS = {
+ "similaritysearch": "Similarity Search",
+ "contextualsearch": "Contextual Search",
+ "hybridsearch": "Hybrid Search",
+ "communitysearch": "Community Search",
+ }
+ _chosen = (query_sources.get("chosen_retriever") or "").lower().replace(" ", "")
+ r.search_type_used = _RETRIEVER_LABELS.get(_chosen) or data.get("response_type") or None
+ # Record which agent was used for this run
+ r.agent_mode = f"{mode}/{rag_pattern}"
+ contexts = _flatten_context(query_sources)
+ except httpx.HTTPStatusError as e:
+ r.error = f"HTTP {e.response.status_code}: {e.response.text[:200]}"
+ r.response_time_seconds = time.monotonic() - t0
+ return r
+ except Exception as e:
+ r.error = f"{type(e).__name__}: {e}"
+ r.response_time_seconds = time.monotonic() - t0
+ return r
+ finally:
+ r.response_time_seconds = time.monotonic() - t0
+
+ if not r.answered_question or not r.generated_answer:
+ r.metric_errors["all"] = "GraphRAG did not produce an answer"
+ return r
+
+ ctx_str = "\n\n".join(f"[Passage {i + 1}]\n{c}" for i, c in enumerate(contexts))
+ r.retrieved_context = ctx_str
+
+ tasks = {}
+ if q.ground_truth:
+ _q, _ans, _gt = q.question, r.generated_answer, q.ground_truth
+ tasks["correctness"] = lambda _q=_q, _ans=_ans, _gt=_gt: answer_correctness(_q, _ans, _gt)
+
+ _q, _gen, _ctx = q.question, r.generated_answer, ctx_str
+ tasks["hallucination"] = lambda _q=_q, _gen=_gen, _ctx=_ctx: hallucination_check(_q, _gen, _ctx)
+
+ with ThreadPoolExecutor(max_workers=len(tasks)) as pool:
+ futures = {m: pool.submit(fn) for m, fn in tasks.items()}
+ for metric, future in futures.items():
+ try:
+ val = future.result()
+ if metric == "correctness":
+ r.answer_correctness, r.answer_correctness_reason, err = val
+ if err:
+ r.metric_errors["answer_correctness"] = err
+ elif metric == "hallucination":
+ r.hallucination, r.hallucination_confidence, r.hallucination_reason, err = val
+ if err:
+ r.metric_errors["hallucination"] = err
+ if r.hallucination_confidence is not None:
+ r.hallucination_confidence = round(r.hallucination_confidence, 3)
+ except Exception as e:
+ r.metric_errors[metric] = f"unexpected: {type(e).__name__}: {e}"
+
+ return r
+
+
+def _ac_cell(r: EvalResult) -> str:
+ ac = r.answer_correctness
+ if ac is not None:
+ col = _G if ac >= 0.75 else _Y if ac >= 0.5 else _R
+ return f"{col}{ac * 100:5.1f}%{_X}"
+ if r.metric_errors.get("answer_correctness"):
+ return f"{_Y} n/a{_X}"
+ return " —"
+
+
+def _hal_cell(r: EvalResult) -> str:
+ hal = r.hallucination
+ if hal is not None:
+ col = _R if hal == "yes" else _G
+ verdict = "Halluc." if hal == "yes" else "Ground."
+ conf = f" {r.hallucination_confidence * 100:3.0f}%" if r.hallucination_confidence is not None else ""
+ return f"{col}{verdict}{conf}{_X}"
+ if r.metric_errors.get("hallucination"):
+ return f"{_Y}n/a{_X}"
+ return "—"
+
+
+def _print_compact(r: EvalResult, total: int) -> None:
+ """One clean colourised line per question (default mode)."""
+ n = r.index + 1
+ if r.error:
+ print(f" Q{n:>3}/{total} [{r.response_time_seconds:5.1f}s] "
+ f"{_R}error: {r.error[:100]}{_X}", flush=True)
+ return
+ if not r.answered_question:
+ print(f" Q{n:>3}/{total} [{r.response_time_seconds:5.1f}s] "
+ f"{_Y}no answer from GraphRAG{_X}", flush=True)
+ return
+ extra = ""
+ if r.metric_errors:
+ errs = ", ".join(f"{k}: {v[:60]}" for k, v in r.metric_errors.items())
+ extra = f" {_Y}metric warn: {errs}{_X}"
+ print(f" Q{n:>3}/{total} [{r.response_time_seconds:5.1f}s] "
+ f"AC={_ac_cell(r)} Hal={_hal_cell(r)}{extra}", flush=True)
+
+
+def _print_detailed(r: EvalResult, total: int) -> None:
+ """Question, answer, scores and reasons (--detailed mode)."""
+ n = r.index + 1
+ q_short = (r.question[:70] + "…") if len(r.question) > 71 else r.question
+ print(f" {'─' * 70}", flush=True)
+ print(f" {_B}Q{n}/{total}{_X} [{r.response_time_seconds:.1f}s] {q_short}", flush=True)
+ if r.error:
+ print(f" {_R}error: {r.error}{_X}", flush=True)
+ return
+ if not r.answered_question:
+ print(f" {_Y}GraphRAG did not produce an answer{_X}", flush=True)
+ return
+ print(f" Answer : {(r.generated_answer or '')[:160]}", flush=True)
+
+ ac_line = f" {_C}Answer Correctness{_X} : AC={_ac_cell(r)}"
+ if r.metric_errors.get("answer_correctness"):
+ ac_line += f" {_Y}({r.metric_errors['answer_correctness']}){_X}"
+ print(ac_line, flush=True)
+ if r.answer_correctness_reason:
+ print(f" reason: {r.answer_correctness_reason}", flush=True)
+
+ hal_line = f" {_C}Hallucination{_X} : Hal={_hal_cell(r)}"
+ if r.metric_errors.get("hallucination"):
+ hal_line += f" {_Y}({r.metric_errors['hallucination']}){_X}"
+ print(hal_line, flush=True)
+ if r.hallucination_reason:
+ print(f" reason: {r.hallucination_reason}", flush=True)
+
+
+def run_eval(
+ questions: List[EvalQuestion],
+ graphname: str,
+ url: str,
+ username: str,
+ password: str,
+ mode: str = "agentic",
+ rag_pattern: str = "planned",
+ detailed: bool = False,
+) -> List[EvalResult]:
+ total = len(questions)
+ workers = min(8, total)
+ results: List[Optional[EvalResult]] = [None] * total
+ printer = _print_detailed if detailed else _print_compact
+
+ with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="eval") as pool:
+ futures = {
+ pool.submit(_eval_one, i, q, graphname, url, username, password, mode, rag_pattern): i
+ for i, q in enumerate(questions)
+ }
+ for future in as_completed(futures):
+ r = future.result()
+ results[r.index] = r
+ printer(r, total)
+
+ return [r for r in results if r is not None]
+
+
+# ─── Output ───────────────────────────────────────────────────────────────────
+
+_CSV_FIELDS = [
+ "question", "ground_truth", "generated_answer", "retrieved_context",
+ "agent_mode", "search_type_used",
+ "answer_correctness", "answer_correctness_reason",
+ "hallucination", "hallucination_reason",
+ "response_time_seconds",
+]
+
+
+def write_results(results: List[EvalResult], output_dir: str, detailed: bool = False) -> None:
+ os.makedirs(output_dir, exist_ok=True)
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
+ csv_path = os.path.join(output_dir, f"results_{ts}.csv")
+
+ with open(csv_path, "w", newline="", encoding="utf-8") as f:
+ writer = csv.DictWriter(f, fieldnames=_CSV_FIELDS)
+ writer.writeheader()
+ for r in results:
+ row = asdict(r)
+ writer.writerow({k: row[k] for k in _CSV_FIELDS})
+
+ # ── Summary ───────────────────────────────────────────────────────────────
+ errors = [r for r in results if r.error]
+ unanswered = [r for r in results if not r.error and not r.answered_question]
+ answered = len(results) - len(errors) - len(unanswered)
+ valid_hal = [r for r in results if r.hallucination is not None]
+ hal_rate = sum(1 for r in valid_hal if r.hallucination == "yes") / len(valid_hal) if valid_hal else None
+ corr_vals = [r.answer_correctness for r in results if r.answer_correctness is not None]
+ avg_corr = sum(corr_vals) / len(corr_vals) if corr_vals else None
+
+ agent_label = results[0].agent_mode if results else "unknown"
+ print(f"\n {'═' * 60}")
+ print(f" {_B}Summary{_X} [{_C}{agent_label}{_X}]")
+ print(f" {'═' * 60}")
+ print(f" Answered : {_G}{answered}{_X} / {len(results)}")
+ if unanswered:
+ print(f" No answer : {_Y}{len(unanswered)}{_X}"
+ f" (Q{', Q'.join(str(r.index+1) for r in unanswered)})")
+ if errors:
+ print(f" Errors : {_R}{len(errors)}{_X}"
+ f" (Q{', Q'.join(str(r.index+1) for r in errors)})" )
+ for r in errors:
+ print(f" Q{r.index+1}: {r.error}", flush=True)
+
+ if avg_corr is not None:
+ col = _G if avg_corr >= 0.75 else _Y if avg_corr >= 0.5 else _R
+ print(f" {_C}Avg Answer Correctness{_X} : {col}{avg_corr * 100:.1f}%{_X}")
+ elif not any(r.ground_truth for r in results):
+ print(f" Avg Answer Correctness : — (no ground truth / answers.csv)")
+ else:
+ print(f" Avg Answer Correctness : — (metric errors, check deepeval install)")
+
+ if hal_rate is not None:
+ col = _R if hal_rate > 0.2 else _G
+ print(f" {_C}Hallucination Rate{_X} : {col}{hal_rate * 100:.1f}%{_X}")
+ else:
+ print(f" Hallucination Rate : — (check failed or no context)")
+
+ print(f" {'═' * 60}")
+ print(f"\n CSV : {csv_path}\n")
+
+
+# ─── CLI entry point ──────────────────────────────────────────────────────────
+
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="GraphRAG Regression Evaluator")
+ parser.add_argument("--dataset", required=True,
+ help="Dataset name (folder under graphrag/tests/test_questions/)")
+ parser.add_argument("--graphname", required=True,
+ help="GraphRAG graph name to query")
+ parser.add_argument("--config", default="configs/server_config.json",
+ help="Path to server_config.json")
+ parser.add_argument("--url", default=None,
+ help="GraphRAG base URL (overrides server_config.json graphrag_config.query_url)")
+ parser.add_argument("--agent", default="planned",
+ choices=["planned", "reactive", "classic"],
+ help=(
+ "Agent to use: 'planned' (Planned Agent, default), "
+ "'reactive' (ReAct Agent), or 'classic' (Classic engine). "
+ "Use --search-type to override the Classic retriever."
+ ))
+ parser.add_argument("--search-type", default="auto",
+ help=(
+ "Classic retriever override when --agent classic is set. "
+ "Values: auto, similaritysearch, contextualsearch, "
+ "hybridsearch, communitysearch (default: auto)"
+ ))
+ parser.add_argument("--output", default=None,
+ help="Output directory for result CSV/JSON")
+ parser.add_argument("--detailed", action="store_true",
+ help="Print per-question breakdown in addition to the summary")
+ parser.add_argument("--limit", type=int, default=None,
+ help="Only run the first N questions (useful for quick smoke tests)")
+ args = parser.parse_args()
+
+ # ── Silence the noise: deprecation warnings + the app's INFO logging ───────
+ # The GraphRAG app modules (openai_service, agent_hallucination_check, …)
+ # log at INFO on every call. logging.disable(INFO) hard-suppresses INFO/DEBUG
+ # from every logger regardless of its own level, so the only thing on screen
+ # is our clean per-question output.
+ warnings.simplefilter("ignore")
+ logging.disable(logging.INFO)
+
+ config_path = os.path.abspath(args.config)
+ if not os.path.exists(config_path):
+ sys.exit(f"ERROR: config file not found: {config_path}")
+ os.environ.setdefault("SERVER_CONFIG", config_path)
+
+ with open(config_path) as f:
+ server_cfg = json.load(f)
+
+ db = server_cfg.get("db_config", {})
+ username = db.get("username", "")
+ password = db.get("password", "")
+ if not username or not password:
+ sys.exit(f"ERROR: db_config.username / password not set in {config_path}")
+
+ graphrag_url = (
+ args.url
+ or server_cfg.get("graphrag_config", {}).get("query_url", "http://localhost:8000")
+ ).rstrip("/")
+
+ dataset_dir = os.path.join("/code/tests/test_questions", args.dataset)
+ if not os.path.isdir(dataset_dir):
+ sys.exit(f"ERROR: dataset directory not found: {dataset_dir}")
+
+ output_dir = args.output or os.path.join(os.path.dirname(__file__), "results")
+
+ # Map --agent choice to (mode, rag_pattern) for the /query endpoint
+ _AGENT_MAP = {
+ "planned": ("agentic", "planned"),
+ "reactive": ("agentic", "reactive"),
+ "classic": ("classic", args.search_type.lower()),
+ }
+ mode, rag_pattern = _AGENT_MAP[args.agent]
+
+ questions = load_questions(dataset_dir)
+ if args.limit:
+ questions = questions[:args.limit]
+
+ print(f"\n{_B}GraphRAG Evaluation{_X} dataset={args.dataset} "
+ f"graph={args.graphname} agent={args.agent} "
+ + (f"retriever={args.search_type} " if args.agent == "classic" else "")
+ + f"questions={len(questions)}"
+ + (f" {_Y}(limit={args.limit}){_X}" if args.limit else "")
+ + "\n", flush=True)
+
+ results = run_eval(
+ questions = questions,
+ graphname = args.graphname,
+ url = graphrag_url,
+ username = username,
+ password = password,
+ mode = mode,
+ rag_pattern = rag_pattern,
+ detailed = args.detailed,
+ )
+ write_results(results, output_dir, detailed=args.detailed)
+
+ # os._exit skips the interpreter shutdown phase, which otherwise emits
+ # destructor/asyncio noise ("ImportError: sys.meta_path is None …") from
+ # the GraphRAG embedding-store and LLM clients after our output is done.
+ sys.stdout.flush()
+ sys.stderr.flush()
+ exit_code = 1 if any(
+ r.error or not r.answered_question or r.metric_errors
+ for r in results
+ ) else 0
+ os._exit(exit_code)
diff --git a/graphrag/tests/regression/hallucination_check.py b/graphrag/tests/regression/hallucination_check.py
new file mode 100644
index 00000000..8bb232bc
--- /dev/null
+++ b/graphrag/tests/regression/hallucination_check.py
@@ -0,0 +1,133 @@
+"""Graded hallucination grader for the regression evaluation pipeline (GML-2088).
+
+A 0.0-1.0 confidence variant used ONLY by tests/regression/evaluator.py to score answers.
+The production agent uses the binary check in
+graphrag/app/agent/agent_hallucination_check.py; this copy is kept separate so
+eval-scoring changes never alter runtime code.
+"""
+
+import logging
+from langchain_core.prompts import PromptTemplate
+from langchain_core.output_parsers import PydanticOutputParser
+
+from pydantic import BaseModel, Field
+from common.logs.logwriter import LogWriter
+from common.logs.log import req_id_cv
+
+logger = logging.getLogger(__name__)
+
+
+class HallucinationCheckResponse(BaseModel):
+ confidence: float = Field(
+ description=(
+ "Confidence score between 0.0 and 1.0 that the answer is hallucinated. "
+ "0.0 = fully grounded in the context, 1.0 = completely hallucinated. "
+ "Use the full range — e.g. 0.2 for mostly grounded with minor gaps, "
+ "0.8 for mostly unsupported claims."
+ )
+ )
+ reason: str = Field(
+ description=(
+ "A concise one-to-two sentence explanation of why you assigned this "
+ "confidence score, citing specific claims from the answer and context."
+ )
+ )
+
+
+class TigerGraphAgentHallucinationCheck:
+ def __init__(self, llm_model):
+ self.llm = llm_model
+
+ def check_hallucination(
+ self,
+ generation: str,
+ context: str,
+ question: str = "",
+ ) -> HallucinationCheckResponse:
+ """Score how likely the generated answer is hallucinated.
+
+ Args:
+ generation: The answer produced by the RAG pipeline.
+ context: The retrieved context chunks passed to the LLM.
+ question: The original user question (improves grounding judgement).
+
+ Returns:
+ HallucinationCheckResponse with confidence (0–1) and reason.
+ """
+ LogWriter.info(f"request_id={req_id_cv.get()} ENTRY check_hallucination")
+
+ hallucination_parser = PydanticOutputParser(
+ pydantic_object=HallucinationCheckResponse
+ )
+
+ question_block = (
+ f"\nORIGINAL QUESTION:\n{question}\n" if question.strip() else ""
+ )
+
+ prompt = PromptTemplate(
+ template="""You are an expert grader evaluating whether a GraphRAG \
+pipeline answer is grounded in the retrieved context passages.
+
+GraphRAG answers are SYNTHESIZED — they combine, rephrase, and connect \
+information from multiple passages. Reasonable synthesis and inference are \
+acceptable. However, specific facts (numbers, percentages, names, dates) \
+must be correctly attributed — using a figure from context but applying it \
+to the wrong category or time period IS a hallucination.
+{question_block}
+RETRIEVED CONTEXT PASSAGES:
+-------
+{context}
+-------
+
+ANSWER TO EVALUATE:
+{generation}
+
+SCORING GUIDE — confidence that the answer is hallucinated (0.0 = fully \
+grounded, 1.0 = fully hallucinated):
+
+0.0–0.2 Fully grounded: all key claims are directly stated in or correctly \
+inferred from the context. Paraphrasing and synthesis are expected.
+
+0.2–0.4 Mostly grounded: core ideas are supported; minor details extend \
+beyond the context but are logically consistent and do not contradict anything.
+
+0.4–0.6 Partially grounded: some claims are only loosely supported OR \
+specific facts are misattributed (e.g. a correct number applied to the wrong \
+category, time period, or entity).
+
+0.6–0.8 Mostly hallucinated: several key claims are unsupported or specific \
+facts clearly contradict the context.
+
+0.8–1.0 Fully hallucinated: the answer is largely unrelated to the context \
+or fabricates significant facts.
+
+RULES:
+- Accept synthesis and logical combination across multiple passages.
+- Accept domain knowledge that logically follows from the context topic.
+- Context may be incomplete. Judge consistency, not exhaustiveness.
+- Use semantic alignment, NOT keyword matching.
+- Ignore references to diagrams, figures, or images — context is text only.
+- PENALISE when: (1) a specific number/percentage/date is used but applied \
+to the wrong subject; (2) a claim directly contradicts the context; OR \
+(3) the answer introduces topics entirely unrelated to the context.
+
+Provide your verdict as JSON.
+Format: {format_instructions}""",
+ input_variables=["generation", "context", "question_block"],
+ partial_variables={
+ "format_instructions": hallucination_parser.get_format_instructions()
+ },
+ )
+
+ prediction = self.llm.invoke_with_parser(
+ prompt,
+ hallucination_parser,
+ {
+ "context": context,
+ "generation": generation,
+ "question_block": question_block,
+ },
+ caller_name="check_hallucination",
+ )
+ LogWriter.info(f"request_id={req_id_cv.get()} EXIT check_hallucination")
+ return prediction
diff --git a/graphrag/tests/regression/run_eval.sh b/graphrag/tests/regression/run_eval.sh
new file mode 100644
index 00000000..920a5ca6
--- /dev/null
+++ b/graphrag/tests/regression/run_eval.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# GraphRAG Regression — Evaluation
+#
+# Runs the evaluation INSIDE the graphrag container via docker exec, so it
+# reuses the container's Python environment (deepeval, langchain,
+# common.config, the agent code) — nothing is installed locally.
+#
+# The regression code + test_questions are copied into the container on demand
+# (no bind mount needed); results are copied back to results/ afterward.
+#
+# Usage (from repo root, on the host):
+#
+# Planned Agent (default):
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent planned
+#
+# ReAct Agent:
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent reactive
+#
+# Classic engine (auto retriever):
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent classic
+#
+# Classic with specific retriever:
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent classic --search-type hybridsearch
+#
+# Detailed per-question output:
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent planned --detailed
+#
+# Limit to first N questions (quick smoke test):
+# ./graphrag/tests/regression/run_eval.sh --dataset Toppan --graphname toppan_html --agent planned --limit 5
+#
+# Override the container name with GRAPHRAG_CONTAINER if needed.
+# Results are written to graphrag/tests/regression/results/ on the host
+# (the directory is mounted into the container).
+# All arguments are forwarded to evaluator.py.
+
+set -euo pipefail
+
+# Git Bash / MSYS on Windows rewrites "/code/..." into a Windows path
+# (e.g. C:/Program Files/Git/code/...) before passing it to docker.
+# Disable that POSIX path conversion so the container path is preserved.
+export MSYS_NO_PATHCONV=1
+export MSYS2_ARG_CONV_EXCL="*"
+
+CONTAINER="${GRAPHRAG_CONTAINER:-graphrag}"
+REG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${REG_DIR}/_container_sync.sh"
+
+sync_regression_to_container "${CONTAINER}" "${REG_DIR}"
+
+# FORCE_COLOR=1 keeps the colourised output even though docker exec output is
+# piped (no TTY). Set NO_COLOR=1 in your shell to turn colours off.
+set +e
+docker exec \
+ -e PYTHONUNBUFFERED=1 \
+ -e PYTHONWARNINGS=ignore \
+ -e FORCE_COLOR="${FORCE_COLOR:-1}" \
+ -e NO_COLOR="${NO_COLOR:-}" \
+ "${CONTAINER}" \
+ python /code/tests/regression/evaluator.py "$@"
+rc=$?
+set -e
+
+copy_results_from_container "${CONTAINER}" "${REG_DIR}"
+exit $rc
diff --git a/graphrag/tests/regression/run_load.sh b/graphrag/tests/regression/run_load.sh
new file mode 100644
index 00000000..0602adf0
--- /dev/null
+++ b/graphrag/tests/regression/run_load.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env bash
+# GraphRAG Regression — Load Exported Graph into TigerGraph
+#
+# Place ExportedGraph.zip in:
+# graphrag/tests/test_questions//ExportedGraph/ExportedGraph.zip
+# then run from the repo root:
+#
+# ./graphrag/tests/regression/run_load.sh --dataset Apple_SEQ_10
+# ./graphrag/tests/regression/run_load.sh --dataset Apple_SEQ_10 --graphname my_apple
+#
+# After loading, run evaluation with:
+# ./graphrag/tests/regression/run_eval.sh --dataset Apple_SEQ_10 --graphname
+#
+# --graphname : import under a different name (default: original exported name)
+# --tg-container : TigerGraph container name (default: tigergraph)
+# Override graphrag container: GRAPHRAG_CONTAINER env var
+
+set -euo pipefail
+
+# Prevent Git Bash (MSYS) from converting Unix paths in docker exec args
+export MSYS_NO_PATHCONV=1
+export MSYS2_ARG_CONV_EXCL="*"
+
+CONTAINER="${GRAPHRAG_CONTAINER:-graphrag}"
+TG_CONTAINER="${TG_CONTAINER:-tigergraph}"
+GSQL_BIN="/home/tigergraph/tigergraph/app/4.2.1/cmd/gsql"
+REG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${REG_DIR}/_container_sync.sh"
+
+# ── Parse args ────────────────────────────────────────────────────────────────
+DATASET=""
+GRAPHNAME=""
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --dataset) DATASET="$2"; shift 2 ;;
+ --graphname) GRAPHNAME="$2"; shift 2 ;;
+ --tg-container) TG_CONTAINER="$2"; shift 2 ;;
+ *) echo "Unknown argument: $1" >&2; exit 1 ;;
+ esac
+done
+
+[ -z "${DATASET}" ] && { echo "ERROR: --dataset is required." >&2; exit 1; }
+
+# Copy the regression code + datasets into the container on demand.
+sync_regression_to_container "${CONTAINER}" "${REG_DIR}"
+
+# The dataset folder is copied into the graphrag container at /code/tests/test_questions/
+EXPORT_ZIP="/code/tests/test_questions/${DATASET}/ExportedGraph/ExportedGraph.zip"
+TG_IMPORT_DIR="/tmp/graphrag_regression_${DATASET}"
+GSQL_SCRIPT="/tmp/graphrag_import_${DATASET}.gsql"
+
+# ── Step 1: Detect original graph name from zip ───────────────────────────────
+echo ""
+echo "Step 1/2: Detecting graph name from ExportedGraph.zip ..."
+echo "─────────────────────────────────────────────────────────────────"
+
+ORIG_GRAPHNAME=$(docker exec "${CONTAINER}" python -c "
+import zipfile, sys
+with zipfile.ZipFile('${EXPORT_ZIP}') as z:
+ for name in z.namelist():
+ if name.startswith('DBImportExport_') and name.endswith('.gsql'):
+ print(name.replace('DBImportExport_', '').replace('.gsql', ''))
+ sys.exit(0)
+sys.exit(1)
+")
+
+[ -z "${ORIG_GRAPHNAME}" ] && {
+ echo "ERROR: Cannot read graph name from ${EXPORT_ZIP}" >&2
+ echo " Put ExportedGraph.zip in: graphrag/tests/test_questions/${DATASET}/ExportedGraph/" >&2
+ exit 1
+}
+
+FINAL_GRAPHNAME="${GRAPHNAME:-${ORIG_GRAPHNAME}}"
+echo " Original : ${ORIG_GRAPHNAME}"
+echo " Import as : ${FINAL_GRAPHNAME}"
+
+# ── Step 2: Copy zip into TigerGraph container and import ─────────────────────
+echo ""
+echo "Step 2/2: Importing '${FINAL_GRAPHNAME}' into TigerGraph ..."
+echo "─────────────────────────────────────────────────────────────────"
+
+docker exec "${CONTAINER}" cat "${EXPORT_ZIP}" \
+ | docker exec -i "${TG_CONTAINER}" bash -c "mkdir -p ${TG_IMPORT_DIR} && cat > ${TG_IMPORT_DIR}/ExportedGraph.zip"
+
+echo " Zip copied to ${TG_CONTAINER}:${TG_IMPORT_DIR}/ExportedGraph.zip"
+
+# If rename needed: unzip, sed-replace graph name references, re-zip
+if [ "${FINAL_GRAPHNAME}" != "${ORIG_GRAPHNAME}" ]; then
+ echo " Renaming ${ORIG_GRAPHNAME} → ${FINAL_GRAPHNAME} inside zip ..."
+ docker exec \
+ -e ORIG="${ORIG_GRAPHNAME}" \
+ -e FNEW="${FINAL_GRAPHNAME}" \
+ -e DIR="${TG_IMPORT_DIR}" \
+ "${TG_CONTAINER}" bash -c '
+ cd "${DIR}"
+ unzip -q ExportedGraph.zip -d export_src/
+ find export_src/ -name "*.gsql" | while read f; do
+ sed -i "s/${ORIG}/${FNEW}/g" "$f"
+ newname="$(dirname "$f")/$(basename "$f" | sed "s/${ORIG}/${FNEW}/g")"
+ [ "$f" != "$newname" ] && mv "$f" "$newname"
+ done
+ rm ExportedGraph.zip
+ cd export_src && zip -rq ../ExportedGraph.zip . && cd ..
+ rm -rf export_src/
+ '
+ echo " Rename done."
+fi
+
+# Write GSQL import script to a file inside TigerGraph container, then run it
+docker exec -i "${TG_CONTAINER}" bash -c "cat > ${GSQL_SCRIPT}" << GSQLEOF
+IMPORT GRAPH ${FINAL_GRAPHNAME} FROM "${TG_IMPORT_DIR}"
+GSQLEOF
+
+echo " Running: IMPORT GRAPH ${FINAL_GRAPHNAME} FROM \"${TG_IMPORT_DIR}\" ..."
+docker exec "${TG_CONTAINER}" \
+ "${GSQL_BIN}" -u tigergraph -p tigergraph -f "${GSQL_SCRIPT}"
+
+echo ""
+echo " ✓ Graph '${FINAL_GRAPHNAME}' imported successfully."
+echo ""
+echo " Next — run evaluation:"
+echo " ./graphrag/tests/regression/run_eval.sh --dataset ${DATASET} --graphname ${FINAL_GRAPHNAME}"
+echo "─────────────────────────────────────────────────────────────────"
diff --git a/graphrag/tests/regression/run_setup.sh b/graphrag/tests/regression/run_setup.sh
new file mode 100644
index 00000000..ea37ca9b
--- /dev/null
+++ b/graphrag/tests/regression/run_setup.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# GraphRAG Regression — Graph Setup
+#
+# Runs the setup INSIDE the graphrag container via docker exec, so it reuses
+# the container's Python environment (deepeval, langchain, common.config, etc.)
+# — nothing needs to be installed locally.
+#
+# The regression code + test_questions are copied into the container on demand
+# (no bind mount needed).
+#
+# Usage (from repo root, on the host):
+# ./graphrag/tests/regression/run_setup.sh --dataset Toppan
+# ./graphrag/tests/regression/run_setup.sh --dataset Toppan --skip-rebuild
+#
+# Override the container name with GRAPHRAG_CONTAINER if needed.
+# All arguments are forwarded to setup_graph.py.
+
+set -euo pipefail
+
+# Git Bash / MSYS on Windows rewrites "/code/..." into a Windows path
+# (e.g. C:/Program Files/Git/code/...) before passing it to docker.
+# Disable that POSIX path conversion so the container path is preserved.
+export MSYS_NO_PATHCONV=1
+export MSYS2_ARG_CONV_EXCL="*"
+
+CONTAINER="${GRAPHRAG_CONTAINER:-graphrag}"
+REG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${REG_DIR}/_container_sync.sh"
+
+sync_regression_to_container "${CONTAINER}" "${REG_DIR}"
+
+docker exec -e PYTHONUNBUFFERED=1 "${CONTAINER}" \
+ python /code/tests/regression/setup_graph.py "$@"
diff --git a/graphrag/tests/regression/setup_graph.py b/graphrag/tests/regression/setup_graph.py
new file mode 100644
index 00000000..a1deb5ba
--- /dev/null
+++ b/graphrag/tests/regression/setup_graph.py
@@ -0,0 +1,337 @@
+"""GraphRAG Regression — Graph Setup
+
+Creates and populates a GraphRAG knowledge graph from a dataset folder.
+
+Two modes:
+ 1. Fresh setup (default) — creates graph, initialises schema, uploads &
+ ingests documents, triggers ECC rebuild.
+ 2. Load exported graph (--load-exported) — restore from ExportedGraph/
+ folder (stub — implement load_exported() when confirmed).
+
+The generated graphname is printed last so run_setup.sh can capture it.
+
+Run via:
+ ./graphrag/tests/regression/run_setup.sh --dataset
+ ./graphrag/tests/regression/run_setup.sh --dataset --graphname
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import os
+import re
+import sys
+import time
+import uuid
+from typing import List, Optional
+
+import httpx
+
+logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(name)s: %(message)s")
+
+_REBUILD_POLL_SECS = 30
+
+
+class SetupError(Exception):
+ pass
+
+
+# ─── HTTP helpers ─────────────────────────────────────────────────────────────
+
+class _Client:
+ def __init__(self, base_url: str, username: str, password: str) -> None:
+ self.base_url = base_url.rstrip("/")
+ self.auth = (username, password)
+
+ def post(self, path: str, json_body=None) -> dict:
+ resp = httpx.post(
+ f"{self.base_url}{path}",
+ json=json_body,
+ auth=self.auth,
+ timeout=None,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+ def get(self, path: str) -> dict:
+ resp = httpx.get(
+ f"{self.base_url}{path}",
+ auth=self.auth,
+ timeout=None,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+ def upload_file(self, path: str, filepath: str) -> dict:
+ fname = os.path.basename(filepath)
+ with open(filepath, "rb") as fh:
+ resp = httpx.post(
+ f"{self.base_url}{path}",
+ auth=self.auth,
+ params={"overwrite": "true"},
+ files={"files": (fname, fh)},
+ timeout=None,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+# ─── Setup steps ──────────────────────────────────────────────────────────────
+
+def _create_graph(client: _Client, graphname: str) -> None:
+ result = client.post(f"/ui/{graphname}/create_graph")
+ status = result.get("status", "")
+ if status == "error":
+ msg = result.get("message", "")
+ if "already exists" in msg.lower():
+ print(f" Graph already exists — continuing.", flush=True)
+ else:
+ raise SetupError(f"create_graph: {msg}")
+
+
+def _initialize(client: _Client, graphname: str) -> None:
+ try:
+ result = client.post(f"/ui/{graphname}/initialize_graph")
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code == 409:
+ try:
+ body = e.response.json()
+ detail = body.get("detail", {})
+ if isinstance(detail, dict) and detail.get("reason") == "structural_present":
+ print(f" Schema already installed — skipping init.", flush=True)
+ return
+ except Exception:
+ pass
+ raise SetupError(f"initialize ({e.response.status_code}): {e.response.text[:300]}") from e
+
+ state = str(result.get("status", result.get("state", ""))).lower()
+ if state in ("submitted", "running", "in_progress"):
+ _poll_initialize(client, graphname)
+
+
+def _poll_initialize(client: _Client, graphname: str, poll_secs: int = 5) -> None:
+ print(f" Polling initialization status ...", flush=True)
+ last_msg = None
+ while True:
+ status = client.get(f"/ui/{graphname}/initialize_status")
+ state = str(status.get("state", "")).lower()
+ message = str(status.get("message") or "")
+ error = status.get("error")
+
+ if message and message != last_msg:
+ print(f" [{graphname}] {message}", flush=True)
+ last_msg = message
+
+ if state == "completed":
+ return
+ if state == "failed" or error:
+ raise SetupError(f"Initialization failed: {error or message}")
+ time.sleep(poll_secs)
+
+
+def _ingest_documents(client: _Client, graphname: str, doc_files: List[str]) -> None:
+ # Upload
+ print(f" Uploading {len(doc_files)} file(s) ...", flush=True)
+ for fp in doc_files:
+ result = client.upload_file(f"/ui/{graphname}/uploads", fp)
+ if result.get("status") not in ("success", "conflict"):
+ raise SetupError(f"Upload returned unexpected status: {result}")
+ print(f" + {os.path.basename(fp)}", flush=True)
+
+ # Derive and validate file format from uploaded files
+ extensions = {
+ os.path.splitext(fp)[1].lstrip(".").lower()
+ for fp in doc_files
+ if os.path.splitext(fp)[1]
+ }
+ if len(extensions) != 1:
+ raise SetupError(
+ f"data/ must contain one file type for ingest; found: {sorted(extensions)}"
+ )
+ file_format = extensions.pop()
+
+ # Create ingest job
+ folder_path = f"uploads/{graphname}"
+ ingest_info = client.post(f"/ui/{graphname}/create_ingest", json_body={
+ "data_source": "server",
+ "data_source_config": {"data_path": folder_path},
+ "loader_config": {},
+ "file_format": file_format,
+ })
+ load_job_id = ingest_info.get("load_job_id") or ingest_info.get("jobId")
+ data_source_id = ingest_info.get("data_source_id") or ingest_info.get("dataSourceId")
+ file_path = ingest_info.get("data_path") or folder_path
+
+ if not load_job_id or data_source_id is None:
+ raise SetupError(f"create_ingest did not return expected fields: {ingest_info}")
+
+ # Run ingest
+ client.post(f"/ui/{graphname}/ingest", json_body={
+ "load_job_id": load_job_id,
+ "data_source_id": data_source_id,
+ "file_path": file_path,
+ })
+
+
+def _rebuild(client: _Client, graphname: str) -> None:
+ client.post(f"/ui/{graphname}/rebuild_graph")
+ print(f" Polling rebuild status every {_REBUILD_POLL_SECS}s ...", flush=True)
+ while True:
+ status = client.get(f"/ui/{graphname}/rebuild_status")
+ stage = str(status.get("stage") or status.get("status", "")).lower()
+ if stage in ("complete", "completed", "done", "success"):
+ return
+ if stage in ("failed", "error"):
+ raise SetupError(f"Rebuild failed: {status}")
+ time.sleep(_REBUILD_POLL_SECS)
+
+
+# ─── Main setup pipeline ──────────────────────────────────────────────────────
+
+def fresh_setup(
+ client: _Client,
+ graphname: str,
+ doc_files: List[str],
+ skip_rebuild: bool = False,
+) -> None:
+ errors: List[str] = []
+ init_ok = True
+
+ print(f"\n [1/4] Create Graph", flush=True)
+ t = time.monotonic()
+ try:
+ _create_graph(client, graphname)
+ print(f" Done ({time.monotonic() - t:.1f}s)", flush=True)
+ except SetupError as e:
+ print(f" Failed: {e}", flush=True)
+ errors.append(f"Create Graph: {e}")
+ init_ok = False
+
+ if init_ok:
+ print(f"\n [2/4] Initialize Schema (1-3 min ...)", flush=True)
+ print(f" Waiting 15s for graph to be ready ...", flush=True)
+ time.sleep(15)
+ t = time.monotonic()
+ try:
+ _initialize(client, graphname)
+ print(f" Done ({time.monotonic() - t:.1f}s)", flush=True)
+ except SetupError as e:
+ print(f" Failed: {e}", flush=True)
+ errors.append(f"Initialize: {e}")
+ init_ok = False
+
+ if init_ok and doc_files:
+ print(f"\n [3/4] Upload & Ingest Documents", flush=True)
+ print(f" Waiting 30s for schema to settle ...", flush=True)
+ time.sleep(30)
+ t = time.monotonic()
+ try:
+ _ingest_documents(client, graphname, doc_files)
+ print(f" Done ({time.monotonic() - t:.1f}s)", flush=True)
+ except SetupError as e:
+ print(f" Failed: {e}", flush=True)
+ errors.append(f"Ingest: {e}")
+ elif init_ok:
+ print(f"\n [3/4] Upload & Ingest - skipped (no data/ files found)", flush=True)
+
+ if not skip_rebuild:
+ print(f"\n [4/4] Rebuild Knowledge Graph (ECC)", flush=True)
+ t = time.monotonic()
+ try:
+ _rebuild(client, graphname)
+ print(f" Done ({time.monotonic() - t:.1f}s)", flush=True)
+ except SetupError as e:
+ print(f" Failed: {e}", flush=True)
+ errors.append(f"Rebuild: {e}")
+ else:
+ print(f"\n [4/4] Rebuild - skipped", flush=True)
+
+ if errors:
+ print(f"\n Setup completed with errors:")
+ for err in errors:
+ print(f" - {err}")
+ sys.exit(1)
+
+
+
+
+# ─── CLI entry point ──────────────────────────────────────────────────────────
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="GraphRAG Regression — Graph Setup")
+ parser.add_argument("--dataset", required=True,
+ help="Dataset name (folder under graphrag/tests/test_questions/)")
+ parser.add_argument("--config", default="configs/server_config.json",
+ help="Path to server_config.json")
+ parser.add_argument("--url", default=None,
+ help="GraphRAG base URL (overrides server_config.json)")
+ parser.add_argument("--graphname", default=None,
+ help="Override the auto-generated graphname")
+ parser.add_argument("--skip-rebuild", action="store_true",
+ help="Skip ECC rebuild step (useful when testing setup only)")
+ args = parser.parse_args()
+
+ config_path = os.path.abspath(args.config)
+ if not os.path.exists(config_path):
+ sys.exit(f"ERROR: config not found: {config_path}")
+
+ with open(config_path) as f:
+ server_cfg = json.load(f)
+
+ db = server_cfg.get("db_config", {})
+ username = db.get("username", "")
+ password = db.get("password", "")
+ if not username or not password:
+ sys.exit(f"ERROR: db_config.username / password not set in {config_path}")
+
+ graphrag_url = (
+ args.url
+ or server_cfg.get("graphrag_config", {}).get("query_url", "http://localhost:8000")
+ ).rstrip("/")
+
+ dataset_dir = os.path.join("/code/tests/test_questions", args.dataset)
+ if not os.path.isdir(dataset_dir):
+ sys.exit(f"ERROR: dataset directory not found: {dataset_dir}")
+
+ # Auto-generate graphname: _<8-char uuid>
+ uid = uuid.uuid4().hex[:8]
+ graphname = args.graphname or f"{args.dataset.lower()}_{uid}"
+ graphname = re.sub(r"[^A-Za-z0-9_]", "_", graphname)
+ if graphname[0].isdigit():
+ graphname = f"g_{graphname}"
+
+ print(f"\nGraphRAG Regression - Graph Setup")
+ print("─" * 60)
+ print(f" Dataset : {args.dataset}")
+ print(f" Graph : {graphname}")
+ print(f" URL : {graphrag_url}")
+ print(f" Mode : fresh-setup")
+ print("─" * 60)
+
+ data_dir = os.path.join(dataset_dir, "data")
+ doc_files = []
+ if os.path.isdir(data_dir):
+ doc_files = [
+ os.path.join(data_dir, f)
+ for f in sorted(os.listdir(data_dir))
+ if os.path.isfile(os.path.join(data_dir, f))
+ ]
+ print(f" Documents : {len(doc_files)} file(s)")
+ for fp in doc_files:
+ print(f" - {os.path.basename(fp)}")
+ else:
+ print(f" Warning: no data/ directory found - skipping ingest")
+ print("─" * 60)
+
+ client = _Client(graphrag_url, username, password)
+ fresh_setup(client, graphname, doc_files, skip_rebuild=args.skip_rebuild)
+
+ print(f"\n Setup complete! Graph '{graphname}' is ready.")
+ print(f"\n Next - run evaluation:")
+ print(f" ./graphrag/tests/regression/run_eval.sh --dataset {args.dataset} --graphname {graphname}")
+ print("─" * 60)
+
+ # Print graphname last so run_setup.sh can capture it cleanly
+ print(graphname)
diff --git a/graphrag/tests/test_e2e_prompt_customization.py b/graphrag/tests/test_e2e_prompt_customization.py
index 61246b73..49273304 100644
--- a/graphrag/tests/test_e2e_prompt_customization.py
+++ b/graphrag/tests/test_e2e_prompt_customization.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""End-to-end test for the system/user prompt-split round-trip.
diff --git a/graphrag/tests/test_e2e_schema_aware_ingest.py b/graphrag/tests/test_e2e_schema_aware_ingest.py
index 3589118a..ca8ecdb6 100644
--- a/graphrag/tests/test_e2e_schema_aware_ingest.py
+++ b/graphrag/tests/test_e2e_schema_aware_ingest.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""
End-to-end test for schema-aware initialization (Phase 1).
diff --git a/graphrag/tests/test_invoke_with_parser.py b/graphrag/tests/test_invoke_with_parser.py
index c4fffad4..1d237f81 100644
--- a/graphrag/tests/test_invoke_with_parser.py
+++ b/graphrag/tests/test_invoke_with_parser.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import asyncio
import json
diff --git a/graphrag/tests/test_llm_entity_relationship_extractor.py b/graphrag/tests/test_llm_entity_relationship_extractor.py
index 07a8861b..12f79a18 100644
--- a/graphrag/tests/test_llm_entity_relationship_extractor.py
+++ b/graphrag/tests/test_llm_entity_relationship_extractor.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Unit tests for the schema-aware extension of
``LLMEntityRelationshipExtractor`` — definitions are surfaced in the
diff --git a/graphrag/tests/test_method_selector.py b/graphrag/tests/test_method_selector.py
index bdcd2383..a4dd1021 100644
--- a/graphrag/tests/test_method_selector.py
+++ b/graphrag/tests/test_method_selector.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import importlib.util
import os
diff --git a/graphrag/tests/test_prompt_split.py b/graphrag/tests/test_prompt_split.py
index a07be0e9..8bac4cb4 100644
--- a/graphrag/tests/test_prompt_split.py
+++ b/graphrag/tests/test_prompt_split.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Unit tests for the base_llm system/user prompt-split helpers.
diff --git a/graphrag/tests/test_prompt_validation.py b/graphrag/tests/test_prompt_validation.py
index cec28f44..11446eae 100644
--- a/graphrag/tests/test_prompt_validation.py
+++ b/graphrag/tests/test_prompt_validation.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Tests for ``common.utils.prompt_validation``.
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/ExportedGraph/ExportedGraph.zip b/graphrag/tests/test_questions/Apple_SEQ_10/ExportedGraph/ExportedGraph.zip
new file mode 100644
index 00000000..ba3f9a12
Binary files /dev/null and b/graphrag/tests/test_questions/Apple_SEQ_10/ExportedGraph/ExportedGraph.zip differ
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/answers.csv b/graphrag/tests/test_questions/Apple_SEQ_10/answers.csv
new file mode 100644
index 00000000..d97aaae3
--- /dev/null
+++ b/graphrag/tests/test_questions/Apple_SEQ_10/answers.csv
@@ -0,0 +1,13 @@
+ground_truth
+"Apple's total net sales have changed over time as follows: - For the quarterly period ended June 25, 2022, the total net sales were $82,959 million. (SOURCE: 2022 Q3 AAPL.pdf) - For the quarterly period ended December 31, 2022, the total net sales were $117,154 million. (SOURCE: 2023 Q1 AAPL.pdf) - For the quarterly period ended April 1, 2023, the total net sales were $94,836 million. (SOURCE: 2023 Q2 AAPL.pdf) - For the quarterly period ended July 1, 2023, the total net sales were $81,797 million. (SOURCE: 2023 Q3 AAPL.pdf) From these figures, it can be observed that there was an increase in total net sales from the quarter ended June 25, 2022, to the quarter ended December 31, 2022. However, there was a subsequent decrease in total net sales in the quarters ended April 1, 2023, and July 1, 2023."
+"In the most recent 10-Q for the quarter ended July 1, 2023, the factors contributing to the change in Apple's gross margin compared to previous quarters include: 1. Weakness in foreign currencies relative to the U.S. dollar, which had an unfavorable impact on gross margin. 2. Lower Products volume, which decreased gross margin. 3. Cost savings and a different Products mix, which partially offset the decrease in gross margin. For the third quarter of 2023, the Products gross margin percentage increased compared to the same quarter in 2022 due to cost savings and a different Products mix, despite the negative impact of foreign currency weakness and decreased leverage. However, the year-over-year Products gross margin percentage for the first nine months of 2023 decreased due to the weakness in foreign currencies and decreased leverage, despite cost savings and a different Products mix. The Services gross margin increased due to higher Services net sales but was partially offset by the weakness in foreign currencies and higher Services costs. The Services gross margin percentage decreased due to higher Services costs, partially offset by improved leverage."
+"Yes, there has been a change in Apple's operating expenses over the reported quarters. The key drivers for this change are increases in research and development (""R&D"") expense and selling, general and administrative expense. The growth in R&D expense is primarily driven by increases in headcount-related expenses. For the third quarter of 2022, the total operating expenses were $12,809 million, with R&D expenses of $6,797 million and selling, general and administrative expenses of $6,012 million. For the first quarter of 2023, the total operating expenses increased to $14,316 million, with R&D expenses of $7,709 million and selling, general and administrative expenses of $6,607 million. For the second quarter of 2023, the total operating expenses were $13,658 million, with R&D expenses of $7,457 million and selling, general and administrative expenses of $6,201 million. For the third quarter of 2023, the total operating expenses were $13,415 million, with R&D expenses of $7,442 million and selling, general and administrative expenses of $5,973 million. The consistent increase in R&D expenses indicates the company's continued investment in innovation and product development. The selling, general and administrative expenses have also increased, although they saw a slight decrease in the third quarter of 2023 compared to the second quarter of 2023. "
+"The revenue from iPhone sales for Apple has fluctuated across the quarters as follows: - In the quarter ended June 25, 2022, the revenue from iPhone sales was $40,665 million. (""2022 Q3 AAPL.pdf"") - In the quarter ended December 31, 2022, the revenue from iPhone sales was $65,775 million. (""2023 Q1 AAPL.pdf"") - In the quarter ended April 1, 2023, the revenue from iPhone sales was $51,334 million. (""2023 Q2 AAPL.pdf"") - In the quarter ended July 1, 2023, the revenue from iPhone sales was $39,669 million"
+"- For the quarterly period ended June 25, 2022, weakness in foreign currencies relative to the U.S. dollar had an unfavorable impact on the Company’s total net sales. SOURCE(S): 2023 Q1 AAPL.pdf, Item 2. Management’s Discussion and Analysis of Financial Condition and Results of Operations - For the quarterly period ended December 31, 2022, weakness in foreign currencies relative to the U.S. dollar had an unfavorable impact on the Company’s total net sales, which decreased 5% or $6.8 billion during the first quarter of 2023 compared to the same quarter in 2022. SOURCE(S): 2023 Q2 AAPL.pdf, Item 2. Management’s Discussion and Analysis of Financial Condition and Results of Operations - For the quarterly period ended April 1, 2023, weakness in foreign currencies relative to the U.S. dollar had an unfavorable impact on the Company’s total net sales, which decreased 3% or $2.4 billion during the second quarter of 2023 compared to the same quarter in 2022. SOURCE(S): 2023 Q3 AAPL.pdf, Item 2. Management’s Discussion and Analysis of Financial Condition and Results of Operations - For the quarterly period ended July 1, 2023, weakness in foreign currencies relative to the U.S. dollar had an unfavorable impact on the Company’s total net sales, which decreased 1% or $1.2 billion during the third quarter of 2023 compared to the same quarter in 2022. SOURCE(S): 2023 Q3 AAPL.pdf, Item 2. Management’s Discussion and Analysis of Financial Condition and Results of Operations"
+"The legal proceedings disclosed in the provided 10-Q documents include the following: 1. Epic Games Lawsuit: Epic Games, Inc. filed a lawsuit against Apple Inc. in the U.S. District Court for the Northern District of California, alleging violations of federal and state antitrust laws and California's unfair competition law based on Apple's operation of its App Store. The District Court ruled in favor of Apple on most counts but found that certain provisions of Apple's App Store Review Guidelines violated California's unfair competition law and issued an injunction. The case was appealed to the U.S. Court of Appeals for the Ninth Circuit, which affirmed the District Court's ruling. Further appeals and requests for review are mentioned, including a potential appeal to the U.S. Supreme Court and the Circuit Court's stay of the injunction pending such appeal. 2. European Commission State Aid Decision: The European Commission issued a decision that Ireland granted state aid to Apple by providing tax opinions in 1991 and 2007 concerning the tax allocation of profits of the Irish branches of two Apple subsidiaries. The decision ordered Ireland to recover additional taxes from Apple for the period June 2003 through December 2014. Both Apple and Ireland appealed the decision to the General Court of the Court of Justice of the European Union, which annulled the decision. The European Commission appealed the annulment to the European Court of Justice, and a hearing was held with a decision expected in calendar year 2024. These legal proceedings and contingencies could potentially impact Apple in several ways: - The Epic Games lawsuit could lead to changes in Apple's App Store policies and practices, particularly regarding the prohibition of developers from including external links to purchasing mechanisms other than Apple in-app purchasing. If the injunction takes effect, it could impact Apple's App Store revenue and operating model. - The European Commission State Aid Decision could result in Apple being required to pay additional taxes for the specified period if the appeal by the European Commission is successful. Apple believes it would be eligible to claim a U.S. foreign tax credit for a portion of any incremental Irish corporate income taxes potentially due related to the decision. Both matters could have financial implications for Apple, including potential monetary liabilities and changes to business practices that could affect future revenue and profitability."
+"In the "Quarterly Highlights" section of the 2023 Q1 AAPL.pdf document, it is mentioned that during the first quarter of 2023, Apple announced a new iPad, a new iPad Pro powered by the Apple M2 chip, and a new Apple TV 4K. Additionally, in the "Operating Expenses" section, it is stated that the growth in research and development (R&D) expense during the first quarter of 2023 compared to the same quarter in 2022 was driven primarily by increases in headcount-related expenses. While the document does not explicitly state a direct correlation between R&D expenditure and the introduction of new products or services, the mention of new product announcements in the same period as an increase in R&D expenses suggests that the company's investment in R&D may be related to its product development efforts."
+"Apple's Q2 2023 report indicates that international markets are a significant component of the company's revenue. The report shows that net sales in various regions outside the United States, such as Europe, Greater China, Japan, and the Rest of Asia Pacific, collectively contribute to the company's total net sales. However, the report also highlights that the company's revenue is impacted by currency fluctuations. Specifically, it mentions that the weakness in foreign currencies relative to the U.S. dollar had an unfavorable impact on the company's total net sales, which decreased by 3% during the second quarter of 2023 compared to the same quarter in 2022. The segment on foreign currency risk within the report discusses how Apple uses derivative instruments to partially offset its business exposure to foreign exchange risk. The company may enter into forward contracts, option contracts, or other instruments to protect its gross margins from fluctuations in foreign currency exchange rates. Apple hedges portions of its forecasted foreign currency exposure associated with revenue and inventory purchases, typically for up to 12 months. Additionally, the company may enter into derivative instruments to protect its foreign currency–denominated term debt or marketable securities from fluctuations in foreign currency exchange rates. In summary, Apple's revenue from international markets is subject to foreign currency risk, and the company actively manages this exposure through the use of derivative instruments to mitigate the impact of currency fluctuations on its financial results."
+"The "Liquidity and Capital Resources" section of Apple's most recent 10-Q report indicates that the company believes its balances of cash, cash equivalents, and unrestricted marketable securities, along with cash generated by ongoing operations and continued access to debt markets, will be sufficient to satisfy its cash requirements and capital return program over the next 12 months and beyond. This suggests that the company expects to maintain a strong liquidity position. The "CONDENSED CONSOLIDATED STATEMENTS OF CASH FLOWS" section shows that Apple's cash generated by operating activities was $88.9 billion for the nine months ended July 1, 2023. This indicates that the company's operations are generating a significant amount of cash, which supports the company's assessment in the "Liquidity and Capital Resources" section that the cash generated from operations will contribute to meeting its cash requirements. In summary, the insights from the "Liquidity and Capital Resources" section correlate with the reported changes in Apple's cash flow from operations by confirming that the company's operations continue to generate substantial cash flows, which, along with its other liquid assets, are expected to cover its financial needs."
+"The reported changes in Apple's inventory levels for Q3 2023 show an increase in total inventories from $4,946 million as of September 24, 2022, to $7,351 million as of July 1, 2023. This increase is reflected in both components and finished goods, with components increasing from $1,637 million to $3,788 million and finished goods increasing from $3,309 million to $3,563 million. The discussion in the supply chain and logistics section, specifically regarding manufacturing purchase obligations, indicates that Apple has entered into noncancelable manufacturing purchase obligations primarily with its outsourcing partners who manufacture subassemblies or assemble final products for the company. As of July 1, 2023, Apple had manufacturing purchase obligations of $38.4 billion, with $38.1 billion payable within 12 months. These obligations are for the acquisition of components and building products based on demand information supplied by Apple, which typically covers periods up to 150 days. The increase in inventory levels could be associated with Apple's strategy to ensure the availability of components and finished products to meet anticipated customer demand, considering the lead times and obligations with its manufacturing partners. The noncancelable nature of these obligations suggests that Apple is committed to these inventory levels to maintain its supply chain operations."
+"The discussion on market risk in the financial section of the latest 10-Q states that there have been no material changes to the Company’s market risk during the first nine months of 2023. This aligns with the risk factors mentioned in the company's business overview, where it is stated that there have been no material changes to the Company’s risk factors since the 2022 Form 10-K."
+"Apple's Q1 2023 10-Q report provides information on the company's debt instruments and management's discussion on their debt management strategy. From the financial statements, we can see that Apple has various notes with different maturity dates and interest rates. For instance, the report lists instruments such as 1.375% Notes due 2024, 0.000% Notes due 2025, and 3.600% Notes due 2042, among others, all registered with The Nasdaq Stock Market LLC. In the management discussion section, specifically under "Liquidity and Capital Resources," it is mentioned that Apple believes its balances of cash, cash equivalents, and unrestricted marketable securities, along with cash generated by ongoing operations and continued access to debt markets, will be sufficient to satisfy its cash requirements and capital return program over the next 12 months and beyond. The report also mentions that Apple's contractual cash requirements have not changed materially since the 2022 Form 10-K, except for commercial paper and manufacturing purchase obligations. The report details that Apple issues unsecured short-term promissory notes ("Commercial Paper") under a commercial paper program, which is used for general corporate purposes, including dividends and share repurchases. As of December 31, 2022, Apple had $1.7 billion of Commercial Paper outstanding, all of which was payable within 12 months. Combining this information, we can infer that Apple's debt management strategy involves maintaining a mix of short-term and long-term debt instruments, ensuring sufficient liquidity through a combination of cash reserves, ongoing operations, and access to debt markets, and using instruments like commercial paper for immediate corporate needs, including shareholder returns."
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/data/2022 Q3 AAPL.pdf b/graphrag/tests/test_questions/Apple_SEQ_10/data/2022 Q3 AAPL.pdf
new file mode 100644
index 00000000..f8af3dbe
Binary files /dev/null and b/graphrag/tests/test_questions/Apple_SEQ_10/data/2022 Q3 AAPL.pdf differ
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q1 AAPL.pdf b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q1 AAPL.pdf
new file mode 100644
index 00000000..4620269e
Binary files /dev/null and b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q1 AAPL.pdf differ
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q2 AAPL.pdf b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q2 AAPL.pdf
new file mode 100644
index 00000000..7b8f1a60
Binary files /dev/null and b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q2 AAPL.pdf differ
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q3 AAPL.pdf b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q3 AAPL.pdf
new file mode 100644
index 00000000..4fdfdcbc
Binary files /dev/null and b/graphrag/tests/test_questions/Apple_SEQ_10/data/2023 Q3 AAPL.pdf differ
diff --git a/graphrag/tests/test_questions/Apple_SEQ_10/questions.csv b/graphrag/tests/test_questions/Apple_SEQ_10/questions.csv
new file mode 100644
index 00000000..374c0e6a
--- /dev/null
+++ b/graphrag/tests/test_questions/Apple_SEQ_10/questions.csv
@@ -0,0 +1,13 @@
+question
+"How has Apple's total net sales changed over time?"
+"What are the major factors contributing to the change in Apple's gross margin in the most recent 10-Q compared to the previous quarters?"
+"Has there been any significant change in Apple's operating expenses over the reported quarters? If so, what are the key drivers for this change?"
+"How has Apple's revenue from iPhone sales fluctuated across quarters?"
+"What is the impact of foreign exchange rates on Apple's financial performance? List this out separately for each reported period."
+"What legal proceedings or contingencies are disclosed in these 10-Qs and how might they potentially impact Apple?"
+"In Apple's Q1 2023 10-Q, what is the correlation between Apple's R&D expenditure and the new products or services introduced by the company?"
+"For Apple's Q2 2023 report, analyze the relationship between Apple's revenue from international markets and its segment on foreign currency risk to understand the company's exposure to currency fluctuations."
+"From Apple's most recent 10-Q, how do the insights from the liquidity and capital resources section correlate with the reported changes in Apple's cash flow from operations?"
+"In Apple's Q3 2023 10-Q, analyze how the reported changes in Apple's inventory levels relate to the discussion in their supply chain and logistics section."
+"From the latest 10-Q, how does Apple's discussion on market risk in the financial section align with the risk factors mentioned in the company's business overview?"
+"In Apple's Q1 2023 10-Q, combine the data on Apple's debt instruments from the financial statements with the management discussion to understand their debt management strategy."
\ No newline at end of file
diff --git a/graphrag/tests/test_retriever_render.py b/graphrag/tests/test_retriever_render.py
index 62dceb9b..5673ee27 100644
--- a/graphrag/tests/test_retriever_render.py
+++ b/graphrag/tests/test_retriever_render.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Unit tests for ``common.db.retriever_render``.
diff --git a/graphrag/tests/test_schema_extraction.py b/graphrag/tests/test_schema_extraction.py
index 8ef2b5d4..d5981fac 100644
--- a/graphrag/tests/test_schema_extraction.py
+++ b/graphrag/tests/test_schema_extraction.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Unit tests for ``common.db.schema_extraction`` — the sample-doc
schema-extraction prompt + concatenation helper.
diff --git a/graphrag/tests/test_schema_utils.py b/graphrag/tests/test_schema_utils.py
index 6907ac0e..0dd5b1c8 100644
--- a/graphrag/tests/test_schema_utils.py
+++ b/graphrag/tests/test_schema_utils.py
@@ -1,10 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
"""Unit tests for ``common.db.schema_utils``.
diff --git a/graphrag/tests/test_ui_setup_integration.py b/graphrag/tests/test_ui_setup_integration.py
index 76f2772e..73204831 100644
--- a/graphrag/tests/test_ui_setup_integration.py
+++ b/graphrag/tests/test_ui_setup_integration.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import json
import os
diff --git a/graphrag/tests/test_ui_setup_unit.py b/graphrag/tests/test_ui_setup_unit.py
index 364680c0..14d1c353 100644
--- a/graphrag/tests/test_ui_setup_unit.py
+++ b/graphrag/tests/test_ui_setup_unit.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import sys
import unittest
diff --git a/graphrag/tests/test_v1_4_1_uploads_schema.py b/graphrag/tests/test_v1_4_1_uploads_schema.py
index 74ee10fd..c4927caa 100644
--- a/graphrag/tests/test_v1_4_1_uploads_schema.py
+++ b/graphrag/tests/test_v1_4_1_uploads_schema.py
@@ -1,16 +1,16 @@
# Copyright (c) 2024-2026 TigerGraph, Inc.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
+# This program may be redistributed and/or modified under the terms of the GNU
+# Affero General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# 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 Affero General Public License for more
+# details.
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
import io
import os