Upload 11 files
Browse files- .gitignore +11 -4
- Dockerfile +21 -25
- Dockerfile.slim +18 -0
- LICENSE +235 -0
- app.py +1474 -0
- docker-compose.slim.yml +15 -0
- docker-compose.yml +29 -0
- requirements.txt +4 -5
- test_concurrency.py +95 -0
- test_full_agent_workflow.py +347 -0
- test_tool_emulation.py +375 -0
.gitignore
CHANGED
|
@@ -1,4 +1,11 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*$py.class
|
| 4 |
+
*.so
|
| 5 |
+
.env
|
| 6 |
+
.venv
|
| 7 |
+
env/
|
| 8 |
+
venv/
|
| 9 |
+
ENV/
|
| 10 |
+
.DS_Store
|
| 11 |
+
*.log
|
Dockerfile
CHANGED
|
@@ -1,35 +1,31 @@
|
|
| 1 |
-
FROM python:3.
|
| 2 |
|
| 3 |
-
|
| 4 |
-
ARG BUILD_TAG
|
| 5 |
|
| 6 |
-
ENV BUILD_SHA=${BUILD_SHA}
|
| 7 |
-
ENV BUILD_TAG=${BUILD_TAG}
|
| 8 |
-
ENV TZ=Asia/Shanghai
|
| 9 |
ENV PYTHONUNBUFFERED=1
|
| 10 |
-
ENV HOST=0.0.0.0
|
| 11 |
-
ENV PORT=7860
|
| 12 |
-
ENV CONFIG_PATH=/app/config/quark_config.json
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
COPY .
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
g++ \
|
| 22 |
-
musl-dev \
|
| 23 |
-
libffi-dev \
|
| 24 |
-
openssl-dev \
|
| 25 |
-
cargo \
|
| 26 |
-
rust
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
| 32 |
|
| 33 |
EXPOSE 7860
|
| 34 |
|
| 35 |
-
CMD ["python", "
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
|
| 3 |
+
WORKDIR /app
|
|
|
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
ENV PYTHONUNBUFFERED=1
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
# Install native Debian Chromium + runtime fonts & ca-certificates
|
| 8 |
+
# Clean apt archives immediately to prevent deb bloat in image layers
|
| 9 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 10 |
+
chromium \
|
| 11 |
+
fonts-liberation \
|
| 12 |
+
ca-certificates \
|
| 13 |
+
&& apt-get clean \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/* /tmp/* /root/.cache
|
| 15 |
|
| 16 |
+
COPY requirements.txt .
|
| 17 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
|
| 19 |
+
# Download Playwright browser binaries — required for browser engine
|
| 20 |
+
RUN python -m pip install --upgrade pip && \
|
| 21 |
+
python -m playwright install chromium
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
COPY app.py .
|
| 24 |
+
|
| 25 |
+
ENV HOST=0.0.0.0
|
| 26 |
+
ENV PORT=7860
|
| 27 |
+
ENV ENGINE=browser
|
| 28 |
|
| 29 |
EXPOSE 7860
|
| 30 |
|
| 31 |
+
CMD ["python", "app.py"]
|
Dockerfile.slim
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONUNBUFFERED=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 19 November 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
| 5 |
+
|
| 6 |
+
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
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.
|
| 11 |
+
|
| 12 |
+
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.
|
| 13 |
+
|
| 14 |
+
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.
|
| 15 |
+
|
| 16 |
+
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.
|
| 17 |
+
|
| 18 |
+
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.
|
| 19 |
+
|
| 20 |
+
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.
|
| 21 |
+
|
| 22 |
+
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.
|
| 23 |
+
|
| 24 |
+
The precise terms and conditions for copying, distribution and modification follow.
|
| 25 |
+
|
| 26 |
+
TERMS AND CONDITIONS
|
| 27 |
+
|
| 28 |
+
0. Definitions.
|
| 29 |
+
|
| 30 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
| 31 |
+
|
| 32 |
+
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
| 33 |
+
|
| 34 |
+
"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.
|
| 35 |
+
|
| 36 |
+
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.
|
| 37 |
+
|
| 38 |
+
A "covered work" means either the unmodified Program or a work based on the Program.
|
| 39 |
+
|
| 40 |
+
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.
|
| 41 |
+
|
| 42 |
+
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.
|
| 43 |
+
|
| 44 |
+
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.
|
| 45 |
+
|
| 46 |
+
1. Source Code.
|
| 47 |
+
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.
|
| 48 |
+
|
| 49 |
+
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.
|
| 50 |
+
|
| 51 |
+
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.
|
| 52 |
+
|
| 53 |
+
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
|
| 54 |
+
subprograms and other parts of the work.
|
| 55 |
+
|
| 56 |
+
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
| 57 |
+
|
| 58 |
+
The Corresponding Source for a work in source code form is that same work.
|
| 59 |
+
|
| 60 |
+
2. Basic Permissions.
|
| 61 |
+
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.
|
| 62 |
+
|
| 63 |
+
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.
|
| 64 |
+
|
| 65 |
+
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
| 66 |
+
|
| 67 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 68 |
+
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.
|
| 69 |
+
|
| 70 |
+
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.
|
| 71 |
+
|
| 72 |
+
4. Conveying Verbatim Copies.
|
| 73 |
+
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.
|
| 74 |
+
|
| 75 |
+
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.
|
| 76 |
+
|
| 77 |
+
5. Conveying Modified Source Versions.
|
| 78 |
+
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:
|
| 79 |
+
|
| 80 |
+
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
| 81 |
+
|
| 82 |
+
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".
|
| 83 |
+
|
| 84 |
+
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.
|
| 85 |
+
|
| 86 |
+
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.
|
| 87 |
+
|
| 88 |
+
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.
|
| 89 |
+
|
| 90 |
+
6. Conveying Non-Source Forms.
|
| 91 |
+
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:
|
| 92 |
+
|
| 93 |
+
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.
|
| 94 |
+
|
| 95 |
+
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.
|
| 96 |
+
|
| 97 |
+
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.
|
| 98 |
+
|
| 99 |
+
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.
|
| 100 |
+
|
| 101 |
+
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.
|
| 102 |
+
|
| 103 |
+
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.
|
| 104 |
+
|
| 105 |
+
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.
|
| 106 |
+
|
| 107 |
+
"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.
|
| 108 |
+
|
| 109 |
+
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).
|
| 110 |
+
|
| 111 |
+
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.
|
| 112 |
+
|
| 113 |
+
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.
|
| 114 |
+
|
| 115 |
+
7. Additional Terms.
|
| 116 |
+
"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.
|
| 117 |
+
|
| 118 |
+
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.
|
| 119 |
+
|
| 120 |
+
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:
|
| 121 |
+
|
| 122 |
+
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
| 123 |
+
|
| 124 |
+
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
|
| 125 |
+
|
| 126 |
+
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
|
| 127 |
+
|
| 128 |
+
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
| 129 |
+
|
| 130 |
+
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
| 131 |
+
|
| 132 |
+
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.
|
| 133 |
+
|
| 134 |
+
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.
|
| 135 |
+
|
| 136 |
+
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.
|
| 137 |
+
|
| 138 |
+
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.
|
| 139 |
+
|
| 140 |
+
8. Termination.
|
| 141 |
+
|
| 142 |
+
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).
|
| 143 |
+
|
| 144 |
+
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.
|
| 145 |
+
|
| 146 |
+
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.
|
| 147 |
+
|
| 148 |
+
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.
|
| 149 |
+
|
| 150 |
+
9. Acceptance Not Required for Having Copies.
|
| 151 |
+
|
| 152 |
+
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.
|
| 153 |
+
|
| 154 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 155 |
+
|
| 156 |
+
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.
|
| 157 |
+
|
| 158 |
+
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.
|
| 159 |
+
|
| 160 |
+
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.
|
| 161 |
+
|
| 162 |
+
11. Patents.
|
| 163 |
+
|
| 164 |
+
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".
|
| 165 |
+
|
| 166 |
+
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.
|
| 167 |
+
|
| 168 |
+
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.
|
| 169 |
+
|
| 170 |
+
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.
|
| 171 |
+
|
| 172 |
+
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
|
| 173 |
+
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.
|
| 174 |
+
|
| 175 |
+
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.
|
| 176 |
+
|
| 177 |
+
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.
|
| 178 |
+
|
| 179 |
+
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.
|
| 180 |
+
|
| 181 |
+
12. No Surrender of Others' Freedom.
|
| 182 |
+
|
| 183 |
+
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
|
| 184 |
+
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.
|
| 185 |
+
|
| 186 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
| 187 |
+
|
| 188 |
+
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.
|
| 189 |
+
|
| 190 |
+
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.
|
| 191 |
+
|
| 192 |
+
14. Revised Versions of this License.
|
| 193 |
+
|
| 194 |
+
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.
|
| 195 |
+
|
| 196 |
+
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.
|
| 197 |
+
|
| 198 |
+
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.
|
| 199 |
+
|
| 200 |
+
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.
|
| 201 |
+
|
| 202 |
+
15. Disclaimer of Warranty.
|
| 203 |
+
|
| 204 |
+
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.
|
| 205 |
+
|
| 206 |
+
16. Limitation of Liability.
|
| 207 |
+
|
| 208 |
+
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.
|
| 209 |
+
|
| 210 |
+
17. Interpretation of Sections 15 and 16.
|
| 211 |
+
|
| 212 |
+
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.
|
| 213 |
+
|
| 214 |
+
END OF TERMS AND CONDITIONS
|
| 215 |
+
|
| 216 |
+
How to Apply These Terms to Your New Programs
|
| 217 |
+
|
| 218 |
+
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.
|
| 219 |
+
|
| 220 |
+
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.
|
| 221 |
+
|
| 222 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 223 |
+
Copyright (C) <year> <name of author>
|
| 224 |
+
|
| 225 |
+
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.
|
| 226 |
+
|
| 227 |
+
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.
|
| 228 |
+
|
| 229 |
+
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 230 |
+
|
| 231 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 232 |
+
|
| 233 |
+
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.
|
| 234 |
+
|
| 235 |
+
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 <http://www.gnu.org/licenses/>.
|
app.py
ADDED
|
@@ -0,0 +1,1474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inception Mercury Web-to-API Service (Headless Browser Bridge Edition)
|
| 3 |
+
Exposes an OpenAI-compatible /v1/chat/completions API.
|
| 4 |
+
|
| 5 |
+
Copyright (C) 2026 ZiChuanLan
|
| 6 |
+
|
| 7 |
+
This program is free software: you can redistribute it and/or modify it under
|
| 8 |
+
the terms of the GNU Affero General Public License as published by the Free
|
| 9 |
+
Software Foundation, either version 3 of the License, or (at your option) any
|
| 10 |
+
later version.
|
| 11 |
+
|
| 12 |
+
This program is distributed in the hope that it will be useful, but WITHOUT ANY
|
| 13 |
+
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
|
| 14 |
+
PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
| 15 |
+
|
| 16 |
+
You should have received a copy of the GNU Affero General Public License along
|
| 17 |
+
with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 18 |
+
|
| 19 |
+
Features:
|
| 20 |
+
- Playwright headless Chromium bridge: real browser network stack satisfies Vercel
|
| 21 |
+
Security Checkpoint & Turnstile by native in-page fetch (works from ANY IP,
|
| 22 |
+
including datacenter/VPS IPs)
|
| 23 |
+
- Full 4-level reasoning_effort support: instant, low, medium, high
|
| 24 |
+
- Full OpenAI / DeepSeek R1 reasoning_content stream & non-stream support
|
| 25 |
+
- Live web search citations support
|
| 26 |
+
- Auto-refreshing session token pool (browser engine)
|
| 27 |
+
- Optional curl_cffi zero-browser fallback engine (ENGINE=curl)
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
import asyncio
|
| 31 |
+
import json
|
| 32 |
+
import os
|
| 33 |
+
import re
|
| 34 |
+
import threading
|
| 35 |
+
import time
|
| 36 |
+
import uuid
|
| 37 |
+
from typing import Any
|
| 38 |
+
|
| 39 |
+
import uvicorn
|
| 40 |
+
from fastapi import FastAPI, Header, HTTPException, Request
|
| 41 |
+
from fastapi.responses import StreamingResponse
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
PORT = int(os.getenv("PORT", "7860"))
|
| 45 |
+
except ValueError:
|
| 46 |
+
PORT = 7860
|
| 47 |
+
|
| 48 |
+
HOST = os.getenv("HOST", "0.0.0.0") # noqa: S104 - containerized gateway must bind all interfaces
|
| 49 |
+
PROXY_URL = os.getenv("PROXY_URL", "").strip() or None
|
| 50 |
+
API_KEY = os.getenv("API_KEY", "").strip() or None
|
| 51 |
+
DEFAULT_MODEL = os.getenv("DEFAULT_MODEL", "mercury-3")
|
| 52 |
+
ENGINE = os.getenv("ENGINE", "browser").strip().lower()
|
| 53 |
+
CHROME_PATH = os.getenv("CHROME_PATH", "").strip() or None
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
POOL_SIZE = int(os.getenv("POOL_SIZE", "5"))
|
| 57 |
+
except ValueError:
|
| 58 |
+
POOL_SIZE = 5
|
| 59 |
+
|
| 60 |
+
DEFAULT_REASONING_EFFORT = os.getenv("DEFAULT_REASONING_EFFORT", "medium").strip().lower()
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
MAX_MSG_CHARS = int(os.getenv("MAX_MSG_CHARS", "1400000"))
|
| 64 |
+
except ValueError:
|
| 65 |
+
MAX_MSG_CHARS = 1400000
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
MAX_INPUT_TOKENS = int(os.getenv("MAX_INPUT_TOKENS", "950000"))
|
| 69 |
+
except ValueError:
|
| 70 |
+
MAX_INPUT_TOKENS = 950000
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
UPSTREAM_RETRIES = max(0, int(os.getenv("UPSTREAM_RETRIES", "2")))
|
| 74 |
+
except ValueError:
|
| 75 |
+
UPSTREAM_RETRIES = 2
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
FIRST_TOKEN_TIMEOUT = float(os.getenv("FIRST_TOKEN_TIMEOUT", "180"))
|
| 79 |
+
except ValueError:
|
| 80 |
+
FIRST_TOKEN_TIMEOUT = 180.0
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
STREAM_IDLE_TIMEOUT = float(os.getenv("STREAM_IDLE_TIMEOUT", "120"))
|
| 84 |
+
except ValueError:
|
| 85 |
+
STREAM_IDLE_TIMEOUT = 120.0
|
| 86 |
+
|
| 87 |
+
app = FastAPI(
|
| 88 |
+
title="Inception Mercury Web-to-API",
|
| 89 |
+
description="Headless browser bridge with OpenAI-compatible API for Inception Mercury 3",
|
| 90 |
+
version="2.0.0"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
REASONING_LEVELS = {"instant", "low", "medium", "high"}
|
| 94 |
+
|
| 95 |
+
def normalize_reasoning_effort(val: str | None) -> str:
|
| 96 |
+
if not val:
|
| 97 |
+
return "medium"
|
| 98 |
+
val = str(val).lower().strip()
|
| 99 |
+
if val in ("instant", "none", "off", "0"):
|
| 100 |
+
return "instant"
|
| 101 |
+
if val in ("low", "1"):
|
| 102 |
+
return "low"
|
| 103 |
+
if val in ("medium", "2"):
|
| 104 |
+
return "medium"
|
| 105 |
+
if val in ("high", "max", "3"):
|
| 106 |
+
return "high"
|
| 107 |
+
return "medium"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def current_timestamp() -> int:
|
| 111 |
+
try:
|
| 112 |
+
return int(time.time())
|
| 113 |
+
except (ValueError, TypeError):
|
| 114 |
+
return 0
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ---------------------------------------------------------------------------
|
| 118 |
+
# Upstream Payload Normalization (Vercel AI SDK compatibility)
|
| 119 |
+
# ---------------------------------------------------------------------------
|
| 120 |
+
def estimate_tokens(text: str) -> int:
|
| 121 |
+
"""Rough token estimate: CJK chars ~= 1 token each, other text ~= 4 chars per token."""
|
| 122 |
+
if not text:
|
| 123 |
+
return 0
|
| 124 |
+
cjk = 0
|
| 125 |
+
for ch in text:
|
| 126 |
+
code = ord(ch)
|
| 127 |
+
if 0x3400 <= code <= 0x9FFF or 0xF900 <= code <= 0xFAFF or 0x3040 <= code <= 0x30FF:
|
| 128 |
+
cjk += 1
|
| 129 |
+
other = len(text) - cjk
|
| 130 |
+
return cjk + (other + 3) // 4
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def fit_content(content_str: str) -> str:
|
| 134 |
+
"""Clamp a single message so it fits both the character and token budgets.
|
| 135 |
+
|
| 136 |
+
The upstream web endpoint silently drops everything past ~1M tokens (including
|
| 137 |
+
the trailing user question) and rejects payloads around 1.4M-1.6M chars with
|
| 138 |
+
HTTP 413, so we keep the head and the tail and mark the elided middle.
|
| 139 |
+
"""
|
| 140 |
+
limit_chars = MAX_MSG_CHARS if MAX_MSG_CHARS > 0 else None
|
| 141 |
+
|
| 142 |
+
if MAX_INPUT_TOKENS > 0:
|
| 143 |
+
est = estimate_tokens(content_str)
|
| 144 |
+
if est > MAX_INPUT_TOKENS:
|
| 145 |
+
allowed = int(len(content_str) * MAX_INPUT_TOKENS / est)
|
| 146 |
+
limit_chars = allowed if limit_chars is None else min(limit_chars, allowed)
|
| 147 |
+
|
| 148 |
+
if limit_chars is not None and len(content_str) > limit_chars:
|
| 149 |
+
half = max(1, limit_chars // 2)
|
| 150 |
+
return (content_str[:half]
|
| 151 |
+
+ "\n\n...[content truncated to preserve context window]...\n\n"
|
| 152 |
+
+ content_str[-half:])
|
| 153 |
+
return content_str
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def normalize_upstream_messages(messages: list[dict[str, Any]]) -> list[dict[str, str]]:
|
| 157 |
+
"""
|
| 158 |
+
Normalizes OpenAI messages array strictly for Inception Web API (/api/chat):
|
| 159 |
+
- Upstream only supports 'user' and 'assistant' roles (Vercel AI SDK useChat).
|
| 160 |
+
- 'system' and 'developer' roles are extracted and prepended to the first 'user' message.
|
| 161 |
+
- 'tool' / 'function' roles are flattened to 'user' messages.
|
| 162 |
+
- 'assistant' tool_calls are converted to readable text.
|
| 163 |
+
- Guarantees the last message has role='user'.
|
| 164 |
+
"""
|
| 165 |
+
system_parts = []
|
| 166 |
+
cleaned_messages = []
|
| 167 |
+
|
| 168 |
+
for m in messages:
|
| 169 |
+
if not isinstance(m, dict):
|
| 170 |
+
continue
|
| 171 |
+
role = m.get("role", "user")
|
| 172 |
+
content = m.get("content", "")
|
| 173 |
+
tool_calls = m.get("tool_calls")
|
| 174 |
+
|
| 175 |
+
# Handle system/developer roles
|
| 176 |
+
if role in ("system", "developer"):
|
| 177 |
+
if content:
|
| 178 |
+
system_parts.append(str(content).strip())
|
| 179 |
+
continue
|
| 180 |
+
|
| 181 |
+
# Handle tool/function roles
|
| 182 |
+
elif role in ("tool", "function"):
|
| 183 |
+
tool_id = m.get("tool_call_id") or m.get("name") or "tool"
|
| 184 |
+
cleaned_messages.append({
|
| 185 |
+
"role": "user",
|
| 186 |
+
"content": f"[Tool Execution Result for `{tool_id}`]:\n{content}"
|
| 187 |
+
})
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
# Handle assistant tool_calls: render as strict json markdown block matching our protocol
|
| 191 |
+
elif role == "assistant" and tool_calls:
|
| 192 |
+
calls_blocks = []
|
| 193 |
+
for tc in tool_calls:
|
| 194 |
+
fn = tc.get("function", {}) if isinstance(tc, dict) else {}
|
| 195 |
+
fname = fn.get("name", "unknown")
|
| 196 |
+
fargs = fn.get("arguments", "{}")
|
| 197 |
+
# Format as json code block for consistent in-context learning
|
| 198 |
+
calls_blocks.append(f"```json\n{{\"name\": \"{fname}\", \"arguments\": {fargs}}}\n```")
|
| 199 |
+
summary_str = "\n".join(calls_blocks)
|
| 200 |
+
if content:
|
| 201 |
+
content = f"{content}\n{summary_str}"
|
| 202 |
+
else:
|
| 203 |
+
content = summary_str
|
| 204 |
+
|
| 205 |
+
# Standard assistant or user
|
| 206 |
+
cleaned_messages.append({"role": role if role in ("user", "assistant") else "user", "content": content})
|
| 207 |
+
|
| 208 |
+
# Prepend all collected system instructions to the first user message
|
| 209 |
+
if system_parts:
|
| 210 |
+
merged_system = "\n\n".join(system_parts)
|
| 211 |
+
system_prefix = f"[System Instructions]\n{merged_system}\n\n"
|
| 212 |
+
first_user_idx = next((i for i, msg in enumerate(cleaned_messages) if msg["role"] == "user"), None)
|
| 213 |
+
if first_user_idx is not None:
|
| 214 |
+
cleaned_messages[first_user_idx]["content"] = system_prefix + str(cleaned_messages[first_user_idx]["content"])
|
| 215 |
+
else:
|
| 216 |
+
# If no user message was present, create one with the system prompt
|
| 217 |
+
cleaned_messages.insert(0, {"role": "user", "content": merged_system})
|
| 218 |
+
|
| 219 |
+
# Coalesce consecutive messages of the same role (Vercel AI SDK strictly requires alternating user/assistant)
|
| 220 |
+
coalesced = []
|
| 221 |
+
for msg in cleaned_messages:
|
| 222 |
+
content_str = str(msg.get("content", ""))
|
| 223 |
+
# Clamp oversized messages against both the char and token budgets
|
| 224 |
+
content_str = fit_content(content_str)
|
| 225 |
+
|
| 226 |
+
if coalesced and coalesced[-1]["role"] == msg["role"]:
|
| 227 |
+
coalesced[-1]["content"] = f"{coalesced[-1]['content']}\n\n{content_str}"
|
| 228 |
+
else:
|
| 229 |
+
coalesced.append({"role": msg["role"], "content": content_str})
|
| 230 |
+
|
| 231 |
+
# Ensure there is at least one message and the last message is 'user'
|
| 232 |
+
if not coalesced:
|
| 233 |
+
coalesced.append({"role": "user", "content": "Hello"})
|
| 234 |
+
elif coalesced[-1]["role"] != "user":
|
| 235 |
+
coalesced.append({"role": "user", "content": "Please continue."})
|
| 236 |
+
|
| 237 |
+
return coalesced
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def build_upstream_payload(
|
| 241 |
+
messages: list[dict[str, Any]],
|
| 242 |
+
reasoning_effort: str = "medium",
|
| 243 |
+
web_search: bool = False,
|
| 244 |
+
chat_id: str | None = None
|
| 245 |
+
) -> dict[str, Any]:
|
| 246 |
+
"""Constructs a strict, error-free payload matching Vercel AI SDK useChat protocol."""
|
| 247 |
+
norm_messages = normalize_upstream_messages(messages)
|
| 248 |
+
chat_id = chat_id or ("chat_" + uuid.uuid4().hex[:12])
|
| 249 |
+
|
| 250 |
+
formatted_messages = []
|
| 251 |
+
for i, m in enumerate(norm_messages):
|
| 252 |
+
mid = f"msg_{i}_{uuid.uuid4().hex[:8]}"
|
| 253 |
+
role = m["role"]
|
| 254 |
+
content = m.get("content", "")
|
| 255 |
+
if isinstance(content, list):
|
| 256 |
+
parts = []
|
| 257 |
+
for p in content:
|
| 258 |
+
if isinstance(p, dict) and p.get("type") == "text":
|
| 259 |
+
parts.append({"type": "text", "text": p.get("text", "")})
|
| 260 |
+
else:
|
| 261 |
+
parts = [{"type": "text", "text": str(content)}]
|
| 262 |
+
formatted_messages.append({"id": mid, "role": role, "parts": parts})
|
| 263 |
+
|
| 264 |
+
last_msg_id = formatted_messages[-1]["id"]
|
| 265 |
+
return {
|
| 266 |
+
"id": chat_id,
|
| 267 |
+
"messageId": last_msg_id, # Strictly equals the id of the last message
|
| 268 |
+
"trigger": "submit-message",
|
| 269 |
+
"messages": formatted_messages,
|
| 270 |
+
"reasoningEffort": reasoning_effort,
|
| 271 |
+
"webSearchEnabled": web_search,
|
| 272 |
+
"voiceMode": False,
|
| 273 |
+
"timezone": "Asia/Shanghai",
|
| 274 |
+
"language": "zh-CN",
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# ---------------------------------------------------------------------------
|
| 279 |
+
# Engine 1: Playwright headless browser bridge (default)
|
| 280 |
+
# ---------------------------------------------------------------------------
|
| 281 |
+
class BrowserBridgeEngine:
|
| 282 |
+
"""Runs a persistent headless Chromium in a dedicated background event loop,
|
| 283 |
+
accepts chat requests via run_coroutine_threadsafe, returns SSE yield coroutine."""
|
| 284 |
+
|
| 285 |
+
def __init__(self, proxy: str | None = None, chrome_path: str | None = None, pool_size: int = 5):
|
| 286 |
+
self.proxy = proxy
|
| 287 |
+
self.chrome_path = chrome_path
|
| 288 |
+
self.pool_size = max(1, pool_size)
|
| 289 |
+
self.loop: asyncio.AbstractEventLoop | None = None
|
| 290 |
+
self._thread: threading.Thread | None = None
|
| 291 |
+
self._lock = threading.Lock()
|
| 292 |
+
self._ready = asyncio.Event()
|
| 293 |
+
self._page: Any = None
|
| 294 |
+
self._browser: Any = None
|
| 295 |
+
self._playwright: Any = None
|
| 296 |
+
self.token_pool: list[tuple[str, float]] = []
|
| 297 |
+
self._token_lock = asyncio.Lock()
|
| 298 |
+
self._rr_index = 0
|
| 299 |
+
self.active_queues = {}
|
| 300 |
+
self.failed = False
|
| 301 |
+
|
| 302 |
+
# ---- lifecycle ----------------------------------------------------------
|
| 303 |
+
def start(self):
|
| 304 |
+
with self._lock:
|
| 305 |
+
if self._thread and self._thread.is_alive():
|
| 306 |
+
return
|
| 307 |
+
self._thread = threading.Thread(target=self._run_loop, daemon=True, name="pw-bridge-loop")
|
| 308 |
+
self._thread.start()
|
| 309 |
+
|
| 310 |
+
def _run_loop(self):
|
| 311 |
+
self.loop = asyncio.new_event_loop()
|
| 312 |
+
asyncio.set_event_loop(self.loop)
|
| 313 |
+
try:
|
| 314 |
+
self.loop.run_until_complete(self._bootstrap())
|
| 315 |
+
except Exception as e:
|
| 316 |
+
import traceback
|
| 317 |
+
print(f"[!] Browser engine bootstrap error: {e}")
|
| 318 |
+
traceback.print_exc()
|
| 319 |
+
self.failed = True
|
| 320 |
+
if not self.failed:
|
| 321 |
+
self.loop.run_forever()
|
| 322 |
+
else:
|
| 323 |
+
self.loop.close()
|
| 324 |
+
|
| 325 |
+
async def _bootstrap(self):
|
| 326 |
+
from playwright.async_api import async_playwright
|
| 327 |
+
self._playwright = await async_playwright().start()
|
| 328 |
+
|
| 329 |
+
launch_args = [
|
| 330 |
+
"--disable-blink-features=AutomationControlled",
|
| 331 |
+
"--no-sandbox",
|
| 332 |
+
"--disable-gpu",
|
| 333 |
+
"--window-size=1280,800",
|
| 334 |
+
"--disable-dev-shm-usage",
|
| 335 |
+
]
|
| 336 |
+
launch_kwargs = {"headless": True, "args": launch_args}
|
| 337 |
+
if self.proxy:
|
| 338 |
+
launch_kwargs["proxy"] = {"server": self.proxy}
|
| 339 |
+
if self.chrome_path and os.path.exists(self.chrome_path):
|
| 340 |
+
launch_kwargs["executable_path"] = self.chrome_path
|
| 341 |
+
else:
|
| 342 |
+
# fallback to an installed chrome executable
|
| 343 |
+
for p in (r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
| 344 |
+
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
|
| 345 |
+
"/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"):
|
| 346 |
+
if os.path.exists(p):
|
| 347 |
+
launch_kwargs["executable_path"] = p
|
| 348 |
+
break
|
| 349 |
+
|
| 350 |
+
self._browser = await self._playwright.chromium.launch(**launch_kwargs)
|
| 351 |
+
self._context = await self._browser.new_context(
|
| 352 |
+
user_agent=("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 353 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 354 |
+
"Chrome/131.0.0.0 Safari/537.36"),
|
| 355 |
+
viewport={"width": 1280, "height": 800},
|
| 356 |
+
)
|
| 357 |
+
self._page = await self._context.new_page()
|
| 358 |
+
|
| 359 |
+
async def on_chunk(req_id, text):
|
| 360 |
+
q = self.active_queues.get(req_id)
|
| 361 |
+
if q:
|
| 362 |
+
await q.put(("chunk", text))
|
| 363 |
+
|
| 364 |
+
async def on_done(req_id, status, error_msg):
|
| 365 |
+
q = self.active_queues.get(req_id)
|
| 366 |
+
if q:
|
| 367 |
+
await q.put(("done", status, error_msg))
|
| 368 |
+
|
| 369 |
+
await self._page.expose_function("py_on_chunk", on_chunk)
|
| 370 |
+
await self._page.expose_function("py_on_done", on_done)
|
| 371 |
+
|
| 372 |
+
await self._page.goto("https://chat.inceptionlabs.ai", timeout=30000)
|
| 373 |
+
cleared = False
|
| 374 |
+
for _ in range(20):
|
| 375 |
+
await asyncio.sleep(1)
|
| 376 |
+
try:
|
| 377 |
+
t = await self._page.title()
|
| 378 |
+
except Exception:
|
| 379 |
+
t = ""
|
| 380 |
+
if "Vercel" not in t and ("Chat" in t or "Inception" in t):
|
| 381 |
+
cleared = True
|
| 382 |
+
break
|
| 383 |
+
if not cleared:
|
| 384 |
+
raise RuntimeError("Vercel Security Checkpoint not cleared in browser")
|
| 385 |
+
|
| 386 |
+
await self._page.evaluate("""() => {
|
| 387 |
+
window.inceptionSendChat = function(reqId, payload, token) {
|
| 388 |
+
fetch('/api/chat', {
|
| 389 |
+
method: 'POST',
|
| 390 |
+
headers: {
|
| 391 |
+
'Content-Type': 'application/json',
|
| 392 |
+
'x-session-token': token,
|
| 393 |
+
'Origin': 'https://chat.inceptionlabs.ai',
|
| 394 |
+
'Referer': 'https://chat.inceptionlabs.ai/'
|
| 395 |
+
},
|
| 396 |
+
body: JSON.stringify(payload)
|
| 397 |
+
}).then(async (r) => {
|
| 398 |
+
if (!r.ok) {
|
| 399 |
+
const err = await r.text();
|
| 400 |
+
await window.py_on_done(reqId, r.status, err);
|
| 401 |
+
return;
|
| 402 |
+
}
|
| 403 |
+
const reader = r.body.getReader();
|
| 404 |
+
const decoder = new TextDecoder();
|
| 405 |
+
while (true) {
|
| 406 |
+
const { done, value } = await reader.read();
|
| 407 |
+
if (done) break;
|
| 408 |
+
await window.py_on_chunk(reqId, decoder.decode(value, { stream: true }));
|
| 409 |
+
}
|
| 410 |
+
await window.py_on_done(reqId, 200, '');
|
| 411 |
+
}).catch(async (e) => {
|
| 412 |
+
await window.py_on_done(reqId, 500, e.toString());
|
| 413 |
+
});
|
| 414 |
+
};
|
| 415 |
+
}""")
|
| 416 |
+
self._ready.set()
|
| 417 |
+
print("[Bridge] Browser engine ready: Vercel checkpoint cleared, in-page fetch injected")
|
| 418 |
+
|
| 419 |
+
# ---- public API (called from FastAPI thread) ---------------------------
|
| 420 |
+
def _submit(self, coro):
|
| 421 |
+
if not self.loop or self.failed:
|
| 422 |
+
raise RuntimeError("Browser bridge is not running")
|
| 423 |
+
fut = asyncio.run_coroutine_threadsafe(coro, self.loop)
|
| 424 |
+
return fut
|
| 425 |
+
|
| 426 |
+
async def get_token(self, force_refresh=False):
|
| 427 |
+
fut = self._submit(self._get_token_inner(force_refresh))
|
| 428 |
+
return await asyncio.wrap_future(fut)
|
| 429 |
+
|
| 430 |
+
async def _get_token_inner(self, force_refresh=False):
|
| 431 |
+
async with self._token_lock:
|
| 432 |
+
loop = self.loop
|
| 433 |
+
page = self._page
|
| 434 |
+
if loop is None or page is None:
|
| 435 |
+
raise RuntimeError("Browser bridge is not initialized")
|
| 436 |
+
now = loop.time()
|
| 437 |
+
if force_refresh:
|
| 438 |
+
self.token_pool.clear()
|
| 439 |
+
|
| 440 |
+
valid_pool = [item for item in self.token_pool if item[1] > now + 30]
|
| 441 |
+
self.token_pool = valid_pool
|
| 442 |
+
|
| 443 |
+
needed = self.pool_size - len(self.token_pool)
|
| 444 |
+
if needed > 0:
|
| 445 |
+
fetch_count = min(needed, self.pool_size)
|
| 446 |
+
try:
|
| 447 |
+
results = await self._page.evaluate("""async (count) => {
|
| 448 |
+
const promises = Array.from({length: count}, async () => {
|
| 449 |
+
try {
|
| 450 |
+
const r = await fetch('/api/session');
|
| 451 |
+
return { status: r.status, data: await r.json() };
|
| 452 |
+
} catch (e) {
|
| 453 |
+
return { err: e.toString() };
|
| 454 |
+
}
|
| 455 |
+
});
|
| 456 |
+
return await Promise.all(promises);
|
| 457 |
+
}""", fetch_count)
|
| 458 |
+
if isinstance(results, list):
|
| 459 |
+
for res in results:
|
| 460 |
+
if res.get("status") == 200 and res.get("data", {}).get("ok"):
|
| 461 |
+
tok = res["data"]["token"]
|
| 462 |
+
self.token_pool.append((tok, now + 600))
|
| 463 |
+
print(f"[Bridge] Pooled token added ({len(self.token_pool)}/{self.pool_size}): {tok[:18]}...")
|
| 464 |
+
except Exception as e:
|
| 465 |
+
print(f"[Bridge] Error in parallel token fetch: {e}")
|
| 466 |
+
|
| 467 |
+
if not self.token_pool:
|
| 468 |
+
res = await self._page.evaluate("""async () => {
|
| 469 |
+
const r = await fetch('/api/session');
|
| 470 |
+
return { status: r.status, data: await r.json() };
|
| 471 |
+
}""")
|
| 472 |
+
if res.get("status") == 200 and res.get("data", {}).get("ok"):
|
| 473 |
+
tok = res["data"]["token"]
|
| 474 |
+
self.token_pool.append((tok, now + 600))
|
| 475 |
+
else:
|
| 476 |
+
raise RuntimeError(f"Failed to fetch session token: {res}")
|
| 477 |
+
|
| 478 |
+
self._rr_index = (self._rr_index + 1) % len(self.token_pool)
|
| 479 |
+
token, _ = self.token_pool[self._rr_index]
|
| 480 |
+
return token
|
| 481 |
+
|
| 482 |
+
async def close(self):
|
| 483 |
+
print("[Bridge] Closing headless browser bridge...")
|
| 484 |
+
if self.loop and self._page:
|
| 485 |
+
try:
|
| 486 |
+
fut = self._submit(self._page.close())
|
| 487 |
+
await asyncio.wrap_future(fut)
|
| 488 |
+
except Exception as e:
|
| 489 |
+
print(f"[Bridge] Error closing page: {e}")
|
| 490 |
+
if self.loop and self._browser:
|
| 491 |
+
try:
|
| 492 |
+
fut = self._submit(self._browser.close())
|
| 493 |
+
await asyncio.wrap_future(fut)
|
| 494 |
+
except Exception as e:
|
| 495 |
+
print(f"[Bridge] Error closing browser: {e}")
|
| 496 |
+
if self.loop and self._playwright:
|
| 497 |
+
try:
|
| 498 |
+
fut = self._submit(self._playwright.stop())
|
| 499 |
+
await asyncio.wrap_future(fut)
|
| 500 |
+
except Exception as e:
|
| 501 |
+
print(f"[Bridge] Error stopping playwright: {e}")
|
| 502 |
+
if self.loop:
|
| 503 |
+
self.loop.call_soon_threadsafe(self.loop.stop)
|
| 504 |
+
|
| 505 |
+
async def chat_events(self, messages, reasoning_effort="medium", web_search=False):
|
| 506 |
+
"""Async generator yielding (kind, value). Runs the fetch in the browser loop."""
|
| 507 |
+
if not self.loop or self.failed:
|
| 508 |
+
raise RuntimeError("Browser bridge not running")
|
| 509 |
+
|
| 510 |
+
req_id = "req_" + uuid.uuid4().hex[:12]
|
| 511 |
+
queue = asyncio.Queue()
|
| 512 |
+
self.active_queues[req_id] = queue
|
| 513 |
+
|
| 514 |
+
payload = build_upstream_payload(
|
| 515 |
+
messages,
|
| 516 |
+
reasoning_effort=reasoning_effort,
|
| 517 |
+
web_search=web_search,
|
| 518 |
+
chat_id="chat_" + req_id,
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
token = await self.get_token()
|
| 522 |
+
|
| 523 |
+
try:
|
| 524 |
+
await asyncio.wrap_future(
|
| 525 |
+
self._submit(
|
| 526 |
+
self._page.evaluate("""([reqId, payload, token]) => {
|
| 527 |
+
window.inceptionSendChat(reqId, payload, token);
|
| 528 |
+
}""", [req_id, payload, token])
|
| 529 |
+
)
|
| 530 |
+
)
|
| 531 |
+
except Exception as e:
|
| 532 |
+
self.active_queues.pop(req_id, None)
|
| 533 |
+
raise RuntimeError(f"Failed to dispatch chat in browser: {e}") from e
|
| 534 |
+
|
| 535 |
+
try:
|
| 536 |
+
buffer = ""
|
| 537 |
+
got_first = False
|
| 538 |
+
while True:
|
| 539 |
+
# read from local queue; the browser loop writes into it
|
| 540 |
+
timeout = STREAM_IDLE_TIMEOUT if got_first else FIRST_TOKEN_TIMEOUT
|
| 541 |
+
try:
|
| 542 |
+
item = await asyncio.wait_for(queue.get(), timeout=timeout)
|
| 543 |
+
except asyncio.TimeoutError:
|
| 544 |
+
stage = "idle" if got_first else "first token"
|
| 545 |
+
raise RuntimeError(
|
| 546 |
+
f"Upstream stream timeout ({stage} > {timeout:.0f}s); browser bridge stopped responding"
|
| 547 |
+
) from None
|
| 548 |
+
kind = item[0]
|
| 549 |
+
if kind == "chunk":
|
| 550 |
+
got_first = True
|
| 551 |
+
buffer += item[1]
|
| 552 |
+
while "\n\n" in buffer:
|
| 553 |
+
event_block, buffer = buffer.split("\n\n", 1)
|
| 554 |
+
for line in event_block.split("\n"):
|
| 555 |
+
line = line.strip()
|
| 556 |
+
if line.startswith("data:"):
|
| 557 |
+
raw_data = line[5:].strip()
|
| 558 |
+
if raw_data == "[DONE]":
|
| 559 |
+
return
|
| 560 |
+
try:
|
| 561 |
+
ev = json.loads(raw_data)
|
| 562 |
+
ev_type = ev.get("type")
|
| 563 |
+
if ev_type == "text-delta":
|
| 564 |
+
yield ("text", ev.get("delta", ""))
|
| 565 |
+
elif ev_type == "reasoning-delta":
|
| 566 |
+
yield ("reasoning", ev.get("delta", ""))
|
| 567 |
+
elif ev_type == "source-url":
|
| 568 |
+
url = ev.get("url", "")
|
| 569 |
+
title = ev.get("title", "")
|
| 570 |
+
if url and url != "__searching__":
|
| 571 |
+
yield ("citation", {"url": url, "title": title})
|
| 572 |
+
except (json.JSONDecodeError, AttributeError, TypeError, KeyError):
|
| 573 |
+
# Malformed SSE frame from upstream - skip it, keep stream alive
|
| 574 |
+
continue
|
| 575 |
+
elif kind == "done":
|
| 576 |
+
status = item[1]
|
| 577 |
+
err = item[2]
|
| 578 |
+
if status != 200:
|
| 579 |
+
raise RuntimeError(f"Inception Chat returned HTTP {status}: {err}")
|
| 580 |
+
if buffer.strip():
|
| 581 |
+
for line in buffer.split("\n"):
|
| 582 |
+
line = line.strip()
|
| 583 |
+
if line.startswith("data:"):
|
| 584 |
+
raw_data = line[5:].strip()
|
| 585 |
+
if raw_data != "[DONE]":
|
| 586 |
+
try:
|
| 587 |
+
ev = json.loads(raw_data)
|
| 588 |
+
ev_type = ev.get("type")
|
| 589 |
+
if ev_type == "text-delta":
|
| 590 |
+
yield ("text", ev.get("delta", ""))
|
| 591 |
+
elif ev_type == "reasoning-delta":
|
| 592 |
+
yield ("reasoning", ev.get("delta", ""))
|
| 593 |
+
elif ev_type == "source-url":
|
| 594 |
+
url = ev.get("url", "")
|
| 595 |
+
title = ev.get("title", "")
|
| 596 |
+
if url and url != "__searching__":
|
| 597 |
+
yield ("citation", {"url": url, "title": title})
|
| 598 |
+
except (json.JSONDecodeError, AttributeError, TypeError, KeyError):
|
| 599 |
+
# Malformed trailing SSE frame - skip it
|
| 600 |
+
continue
|
| 601 |
+
break
|
| 602 |
+
finally:
|
| 603 |
+
self.active_queues.pop(req_id, None)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
# ---------------------------------------------------------------------------
|
| 607 |
+
# Engine 2: curl_cffi zero-browser fallback (Async non-blocking)
|
| 608 |
+
# ---------------------------------------------------------------------------
|
| 609 |
+
class CurlEngine:
|
| 610 |
+
def __init__(self, proxy: str | None = None, pool_size: int = 5):
|
| 611 |
+
from curl_cffi import requests as cr
|
| 612 |
+
self.requests = cr
|
| 613 |
+
self.proxy = proxy
|
| 614 |
+
self.proxies: Any = {"http": proxy, "https": proxy} if proxy else None
|
| 615 |
+
self.pool_size = max(1, pool_size)
|
| 616 |
+
self.session = cr.AsyncSession(impersonate="chrome120", proxies=self.proxies)
|
| 617 |
+
self.token_pool: list[tuple[str, float]] = []
|
| 618 |
+
self._token_lock = asyncio.Lock()
|
| 619 |
+
self._rr_index = 0
|
| 620 |
+
|
| 621 |
+
async def get_token(self, force_refresh: bool = False) -> str:
|
| 622 |
+
async with self._token_lock:
|
| 623 |
+
now = time.time()
|
| 624 |
+
if force_refresh:
|
| 625 |
+
self.token_pool.clear()
|
| 626 |
+
|
| 627 |
+
valid_pool = [item for item in self.token_pool if item[1] > now + 30]
|
| 628 |
+
self.token_pool = valid_pool
|
| 629 |
+
|
| 630 |
+
needed = self.pool_size - len(self.token_pool)
|
| 631 |
+
if needed > 0:
|
| 632 |
+
fetch_count = min(needed, self.pool_size)
|
| 633 |
+
results = await asyncio.gather(
|
| 634 |
+
*(self._fetch_single_token() for _ in range(fetch_count)),
|
| 635 |
+
return_exceptions=True
|
| 636 |
+
)
|
| 637 |
+
for res in results:
|
| 638 |
+
if isinstance(res, tuple) and len(res) == 2:
|
| 639 |
+
self.token_pool.append(res)
|
| 640 |
+
else:
|
| 641 |
+
print(f"[Curl] Failed to fetch pooled token: {res}")
|
| 642 |
+
|
| 643 |
+
if not self.token_pool:
|
| 644 |
+
res = await self._fetch_single_token()
|
| 645 |
+
self.token_pool.append(res)
|
| 646 |
+
|
| 647 |
+
self._rr_index = (self._rr_index + 1) % len(self.token_pool)
|
| 648 |
+
token, _ = self.token_pool[self._rr_index]
|
| 649 |
+
return token
|
| 650 |
+
|
| 651 |
+
async def close(self):
|
| 652 |
+
print("[Curl] Closing AsyncSession connections...")
|
| 653 |
+
if self.session:
|
| 654 |
+
try:
|
| 655 |
+
await self.session.close()
|
| 656 |
+
except Exception as e:
|
| 657 |
+
print(f"[Curl] Error closing session: {e}")
|
| 658 |
+
|
| 659 |
+
async def _fetch_single_token(self) -> tuple[str, float]:
|
| 660 |
+
r = await self.session.get(
|
| 661 |
+
"https://chat.inceptionlabs.ai/api/session",
|
| 662 |
+
timeout=15,
|
| 663 |
+
headers={
|
| 664 |
+
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 665 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 666 |
+
"Chrome/120.0.0.0 Safari/537.36"),
|
| 667 |
+
"Accept": "*/*",
|
| 668 |
+
"Referer": "https://chat.inceptionlabs.ai/",
|
| 669 |
+
},
|
| 670 |
+
)
|
| 671 |
+
if r.status_code != 200:
|
| 672 |
+
raise RuntimeError(f"Failed to fetch session: HTTP {r.status_code} - {r.text}")
|
| 673 |
+
data = r.json()
|
| 674 |
+
token = data["token"]
|
| 675 |
+
return token, time.time() + 600
|
| 676 |
+
|
| 677 |
+
async def chat_events(self, messages, reasoning_effort="medium", web_search=False):
|
| 678 |
+
token = await self.get_token()
|
| 679 |
+
chat_id = "chat_" + uuid.uuid4().hex[:12]
|
| 680 |
+
|
| 681 |
+
payload = build_upstream_payload(
|
| 682 |
+
messages,
|
| 683 |
+
reasoning_effort=reasoning_effort,
|
| 684 |
+
web_search=web_search,
|
| 685 |
+
chat_id=chat_id,
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
headers = {
|
| 689 |
+
"Content-Type": "application/json",
|
| 690 |
+
"x-session-token": token,
|
| 691 |
+
"Origin": "https://chat.inceptionlabs.ai",
|
| 692 |
+
"Referer": "https://chat.inceptionlabs.ai/",
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
r = await self.session.post(
|
| 696 |
+
"https://chat.inceptionlabs.ai/api/chat",
|
| 697 |
+
headers=headers,
|
| 698 |
+
json=payload,
|
| 699 |
+
stream=True,
|
| 700 |
+
timeout=120,
|
| 701 |
+
)
|
| 702 |
+
if r.status_code != 200:
|
| 703 |
+
raise RuntimeError(f"Inception Chat returned HTTP {r.status_code}: {r.text}")
|
| 704 |
+
|
| 705 |
+
async for line in r.aiter_lines():
|
| 706 |
+
if line:
|
| 707 |
+
decoded = line.decode("utf-8", errors="ignore") if isinstance(line, bytes) else str(line)
|
| 708 |
+
if decoded.startswith("data: "):
|
| 709 |
+
raw_data = decoded[6:].strip()
|
| 710 |
+
if raw_data == "[DONE]":
|
| 711 |
+
break
|
| 712 |
+
try:
|
| 713 |
+
ev = json.loads(raw_data)
|
| 714 |
+
ev_type = ev.get("type")
|
| 715 |
+
if ev_type == "text-delta":
|
| 716 |
+
yield ("text", ev.get("delta", ""))
|
| 717 |
+
elif ev_type == "reasoning-delta":
|
| 718 |
+
yield ("reasoning", ev.get("delta", ""))
|
| 719 |
+
elif ev_type == "source-url":
|
| 720 |
+
url = ev.get("url", "")
|
| 721 |
+
title = ev.get("title", "")
|
| 722 |
+
if url and url != "__searching__":
|
| 723 |
+
yield ("citation", {"url": url, "title": title})
|
| 724 |
+
except (json.JSONDecodeError, AttributeError, TypeError, KeyError):
|
| 725 |
+
# Malformed SSE frame from upstream - skip it, keep stream alive
|
| 726 |
+
continue
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
# ---------------------------------------------------------------------------
|
| 730 |
+
# Engine selection
|
| 731 |
+
# ---------------------------------------------------------------------------
|
| 732 |
+
engine: Any
|
| 733 |
+
if ENGINE == "browser":
|
| 734 |
+
print(f"[*] Engine: Playwright headless browser bridge (Pool size: {POOL_SIZE})")
|
| 735 |
+
engine = BrowserBridgeEngine(proxy=PROXY_URL, chrome_path=CHROME_PATH, pool_size=POOL_SIZE)
|
| 736 |
+
engine.start()
|
| 737 |
+
elif ENGINE == "curl":
|
| 738 |
+
print(f"[*] Engine: curl_cffi zero-browser (Pool size: {POOL_SIZE})")
|
| 739 |
+
engine = CurlEngine(proxy=PROXY_URL, pool_size=POOL_SIZE)
|
| 740 |
+
else:
|
| 741 |
+
raise SystemExit(f"Unknown ENGINE={ENGINE}; use browser or curl")
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
# ---------------------------------------------------------------------------
|
| 745 |
+
# Upstream call with bounded retry (safe only before the first token is emitted)
|
| 746 |
+
# ---------------------------------------------------------------------------
|
| 747 |
+
# 413 / 400 are deterministic: retrying the same payload cannot help.
|
| 748 |
+
NON_RETRYABLE_MARKERS = ("413", "Request Entity Too Large", "FUNCTION_PAYLOAD_TOO_LARGE", "400")
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def _is_retryable(err: Exception) -> bool:
|
| 752 |
+
text = str(err)
|
| 753 |
+
return not any(marker in text for marker in NON_RETRYABLE_MARKERS)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
async def chat_events_with_retry(messages, reasoning_effort: str = "medium", web_search: bool = False):
|
| 757 |
+
"""Wrap engine.chat_events with bounded retries while nothing has been emitted yet.
|
| 758 |
+
|
| 759 |
+
Once the first token reaches the client a retry would duplicate content, so
|
| 760 |
+
mid-stream failures propagate to the caller instead. Expired/rejected session
|
| 761 |
+
tokens (401/403) are refreshed before each retry.
|
| 762 |
+
"""
|
| 763 |
+
attempts = UPSTREAM_RETRIES + 1
|
| 764 |
+
last_err: Exception | None = None
|
| 765 |
+
|
| 766 |
+
for attempt in range(attempts):
|
| 767 |
+
emitted = False
|
| 768 |
+
try:
|
| 769 |
+
async for kind, val in engine.chat_events(
|
| 770 |
+
messages, reasoning_effort=reasoning_effort, web_search=web_search
|
| 771 |
+
):
|
| 772 |
+
emitted = True
|
| 773 |
+
yield kind, val
|
| 774 |
+
return
|
| 775 |
+
except Exception as e:
|
| 776 |
+
last_err = e
|
| 777 |
+
if emitted or not _is_retryable(e) or attempt == attempts - 1:
|
| 778 |
+
raise
|
| 779 |
+
delay = min(2 ** attempt, 4)
|
| 780 |
+
print(f"[Retry] attempt {attempt + 1}/{attempts} failed before first token ({e}); retrying in {delay}s", flush=True)
|
| 781 |
+
await asyncio.sleep(delay)
|
| 782 |
+
try:
|
| 783 |
+
await engine.get_token(force_refresh=True)
|
| 784 |
+
except Exception as token_err:
|
| 785 |
+
print(f"[Retry] token refresh failed: {token_err}", flush=True)
|
| 786 |
+
|
| 787 |
+
if last_err is not None:
|
| 788 |
+
raise last_err
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def verify_auth(auth_header: str | None = Header(None)):
|
| 792 |
+
if API_KEY:
|
| 793 |
+
if not auth_header or not auth_header.startswith("Bearer "):
|
| 794 |
+
raise HTTPException(status_code=401, detail="Missing or invalid Bearer token")
|
| 795 |
+
if auth_header.split(" ")[1] != API_KEY:
|
| 796 |
+
raise HTTPException(status_code=403, detail="Invalid API key")
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
@app.on_event("startup")
|
| 800 |
+
async def startup():
|
| 801 |
+
if ENGINE == "browser":
|
| 802 |
+
for _ in range(30):
|
| 803 |
+
if engine._ready.is_set() or engine.failed:
|
| 804 |
+
break
|
| 805 |
+
await asyncio.sleep(1)
|
| 806 |
+
if engine.failed:
|
| 807 |
+
print("[!] Browser engine failed to start; check playwright install")
|
| 808 |
+
else:
|
| 809 |
+
print(f"[*] Browser engine ready: {engine._ready.is_set()}")
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
@app.on_event("shutdown")
|
| 813 |
+
async def shutdown():
|
| 814 |
+
print("[*] Shutting down Inception Web-to-API...")
|
| 815 |
+
if hasattr(engine, "close"):
|
| 816 |
+
try:
|
| 817 |
+
res = engine.close()
|
| 818 |
+
if asyncio.iscoroutine(res):
|
| 819 |
+
await res
|
| 820 |
+
except Exception as e:
|
| 821 |
+
print(f"[!] Error during shutdown: {e}")
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
@app.get("/health")
|
| 825 |
+
async def health():
|
| 826 |
+
return {
|
| 827 |
+
"status": "ok",
|
| 828 |
+
"service": "inception-web-api",
|
| 829 |
+
"engine": ENGINE,
|
| 830 |
+
"pool_size": POOL_SIZE,
|
| 831 |
+
"max_msg_chars": MAX_MSG_CHARS,
|
| 832 |
+
"max_input_tokens": MAX_INPUT_TOKENS,
|
| 833 |
+
"upstream_retries": UPSTREAM_RETRIES,
|
| 834 |
+
"first_token_timeout": FIRST_TOKEN_TIMEOUT,
|
| 835 |
+
"stream_idle_timeout": STREAM_IDLE_TIMEOUT,
|
| 836 |
+
"active_tokens": len(getattr(engine, "token_pool", [])),
|
| 837 |
+
"proxy": PROXY_URL is not None,
|
| 838 |
+
"browser_ready": True,
|
| 839 |
+
}
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
# ---------------------------------------------------------------------------
|
| 843 |
+
# Tool Emulation Helpers (Function Calling virtualization)
|
| 844 |
+
# ---------------------------------------------------------------------------
|
| 845 |
+
def parse_tool_definitions(
|
| 846 |
+
tools: list[dict[str, Any]] | None,
|
| 847 |
+
functions: list[dict[str, Any]] | None = None
|
| 848 |
+
) -> tuple[list[dict[str, Any]], list[str]]:
|
| 849 |
+
"""Normalizes OpenAI tools/functions definitions into a unified format."""
|
| 850 |
+
tool_defs = []
|
| 851 |
+
valid_names = []
|
| 852 |
+
|
| 853 |
+
if tools:
|
| 854 |
+
for t in tools:
|
| 855 |
+
if not isinstance(t, dict):
|
| 856 |
+
continue
|
| 857 |
+
if t.get("type") == "function" and "function" in t:
|
| 858 |
+
fn = t["function"]
|
| 859 |
+
if isinstance(fn, dict):
|
| 860 |
+
tool_defs.append(fn)
|
| 861 |
+
if "name" in fn and isinstance(fn["name"], str):
|
| 862 |
+
valid_names.append(fn["name"])
|
| 863 |
+
elif "name" in t and isinstance(t["name"], str):
|
| 864 |
+
tool_defs.append(t)
|
| 865 |
+
valid_names.append(t["name"])
|
| 866 |
+
elif functions:
|
| 867 |
+
for fn in functions:
|
| 868 |
+
if isinstance(fn, dict) and "name" in fn and isinstance(fn["name"], str):
|
| 869 |
+
tool_defs.append(fn)
|
| 870 |
+
valid_names.append(fn["name"])
|
| 871 |
+
|
| 872 |
+
return tool_defs, valid_names
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def extract_balanced_json(s: str, start_index: int = 0) -> tuple[str, int, int] | None:
|
| 876 |
+
"""
|
| 877 |
+
Finds the first balanced {...} or [...] starting at or after start_index.
|
| 878 |
+
Handles quotes and escaping correctly.
|
| 879 |
+
Returns: (json_str, start_pos, end_pos) or None
|
| 880 |
+
"""
|
| 881 |
+
first_brace = -1
|
| 882 |
+
open_char = None
|
| 883 |
+
close_char = None
|
| 884 |
+
|
| 885 |
+
for i in range(start_index, len(s)):
|
| 886 |
+
if s[i] == '{':
|
| 887 |
+
first_brace = i
|
| 888 |
+
open_char = '{'
|
| 889 |
+
close_char = '}'
|
| 890 |
+
break
|
| 891 |
+
elif s[i] == '[':
|
| 892 |
+
first_brace = i
|
| 893 |
+
open_char = '['
|
| 894 |
+
close_char = ']'
|
| 895 |
+
break
|
| 896 |
+
|
| 897 |
+
if first_brace == -1:
|
| 898 |
+
return None
|
| 899 |
+
|
| 900 |
+
count = 0
|
| 901 |
+
in_string = False
|
| 902 |
+
escape = False
|
| 903 |
+
|
| 904 |
+
for i in range(first_brace, len(s)):
|
| 905 |
+
ch = s[i]
|
| 906 |
+
if escape:
|
| 907 |
+
escape = False
|
| 908 |
+
continue
|
| 909 |
+
if ch == '\\':
|
| 910 |
+
escape = True
|
| 911 |
+
continue
|
| 912 |
+
if ch == '"':
|
| 913 |
+
in_string = not in_string
|
| 914 |
+
continue
|
| 915 |
+
if not in_string:
|
| 916 |
+
if ch == open_char:
|
| 917 |
+
count += 1
|
| 918 |
+
elif ch == close_char:
|
| 919 |
+
count -= 1
|
| 920 |
+
if count == 0:
|
| 921 |
+
return s[first_brace:i+1], first_brace, i+1
|
| 922 |
+
|
| 923 |
+
return None
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def compact_tool_definitions(tool_defs: list[dict[str, Any]], max_tools: int = 50) -> list[dict[str, Any]]:
|
| 927 |
+
"""
|
| 928 |
+
Compacts tool definitions to keep prompt size manageable:
|
| 929 |
+
- Truncates verbose descriptions (> 100 chars).
|
| 930 |
+
- Compacts nested property definitions (> 50 chars).
|
| 931 |
+
- Caps tool count to prevent prompt explosion in multi-tool agent environments.
|
| 932 |
+
"""
|
| 933 |
+
compacted = []
|
| 934 |
+
for td in tool_defs[:max_tools]:
|
| 935 |
+
c = {"name": td.get("name", "")}
|
| 936 |
+
desc = td.get("description", "")
|
| 937 |
+
if desc:
|
| 938 |
+
c["description"] = (desc[:100] + "...") if len(desc) > 100 else desc
|
| 939 |
+
|
| 940 |
+
params = td.get("parameters")
|
| 941 |
+
if isinstance(params, dict):
|
| 942 |
+
clean_params = {"type": params.get("type", "object")}
|
| 943 |
+
if "properties" in params and isinstance(params["properties"], dict):
|
| 944 |
+
clean_props = {}
|
| 945 |
+
for k, v in params["properties"].items():
|
| 946 |
+
if isinstance(v, dict):
|
| 947 |
+
p_desc = v.get("description", "")
|
| 948 |
+
clean_props[k] = {"type": v.get("type", "string")}
|
| 949 |
+
if p_desc:
|
| 950 |
+
clean_props[k]["description"] = (p_desc[:50] + "...") if len(p_desc) > 50 else p_desc
|
| 951 |
+
if "enum" in v:
|
| 952 |
+
clean_props[k]["enum"] = v["enum"]
|
| 953 |
+
else:
|
| 954 |
+
clean_props[k] = v
|
| 955 |
+
clean_params["properties"] = clean_props
|
| 956 |
+
if "required" in params:
|
| 957 |
+
clean_params["required"] = params["required"]
|
| 958 |
+
c["parameters"] = clean_params
|
| 959 |
+
compacted.append(c)
|
| 960 |
+
return compacted
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
def build_tool_system_prompt(tool_defs: list[dict[str, Any]], tool_choice: Any = "auto") -> str:
|
| 964 |
+
"""Builds a compact, unambiguous system prompt instructing the model how to call tools."""
|
| 965 |
+
compacted_defs = compact_tool_definitions(tool_defs)
|
| 966 |
+
tools_json = json.dumps(compacted_defs, ensure_ascii=False, separators=(',', ':'))
|
| 967 |
+
prompt = [
|
| 968 |
+
"## Tools",
|
| 969 |
+
f"You have access to the following functions:\n```json\n{tools_json}\n```",
|
| 970 |
+
"",
|
| 971 |
+
"## Tool Call Protocol",
|
| 972 |
+
"If you decide to invoke any function, you MUST reply with a ```json code block containing:",
|
| 973 |
+
"```json",
|
| 974 |
+
'{"name": "function_name", "arguments": {"param": "value"}}',
|
| 975 |
+
"```",
|
| 976 |
+
"CRITICAL RULES:",
|
| 977 |
+
"1. To invoke a tool, output the ```json ... ``` code block. Do NOT merely say 'Calling tool...' as plain text without emitting the executable call.",
|
| 978 |
+
'2. The "arguments" MUST be a valid JSON dictionary conforming to the parameters schema.',
|
| 979 |
+
"3. If no function needs to be called, answer normally with plain natural language. Do NOT output a tool call JSON.",
|
| 980 |
+
]
|
| 981 |
+
|
| 982 |
+
if isinstance(tool_choice, dict) and tool_choice.get("type") == "function":
|
| 983 |
+
target = tool_choice.get("function", {}).get("name")
|
| 984 |
+
if target:
|
| 985 |
+
prompt.append(f"4. You are REQUIRED to call the function '{target}'.")
|
| 986 |
+
elif tool_choice == "required":
|
| 987 |
+
prompt.append("4. You are REQUIRED to call at least one of the available functions.")
|
| 988 |
+
|
| 989 |
+
return "\n".join(prompt)
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
def prepare_messages_for_tools(
|
| 993 |
+
messages: list[dict[str, Any]],
|
| 994 |
+
tool_prompt: str | None = None
|
| 995 |
+
) -> list[dict[str, Any]]:
|
| 996 |
+
"""Appends tool_prompt to messages as a system message if provided."""
|
| 997 |
+
copied = list(messages)
|
| 998 |
+
if tool_prompt:
|
| 999 |
+
copied.append({"role": "system", "content": tool_prompt})
|
| 1000 |
+
return copied
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def remove_spans(text: str, spans: list[tuple[int, int]]) -> str:
|
| 1004 |
+
"""Removes a list of non-overlapping [start, end) spans from text, preserving other segments."""
|
| 1005 |
+
if not spans:
|
| 1006 |
+
return text
|
| 1007 |
+
spans = sorted(spans, key=lambda x: x[0])
|
| 1008 |
+
parts = []
|
| 1009 |
+
last_idx = 0
|
| 1010 |
+
for s_start, s_end in spans:
|
| 1011 |
+
if s_start > last_idx:
|
| 1012 |
+
parts.append(text[last_idx:s_start])
|
| 1013 |
+
last_idx = max(last_idx, s_end)
|
| 1014 |
+
if last_idx < len(text):
|
| 1015 |
+
parts.append(text[last_idx:])
|
| 1016 |
+
return "\n\n".join(p.strip() for p in parts if p.strip()).strip()
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
def extract_tool_calls(
|
| 1020 |
+
text: str,
|
| 1021 |
+
valid_tool_names: list[str]
|
| 1022 |
+
) -> tuple[list[dict[str, Any]] | None, str]:
|
| 1023 |
+
"""Extracts tool calls from model output with multi-pattern tolerance:
|
| 1024 |
+
1. Natural calling syntax (e.g. Calling tool `todo` with arguments: {...})
|
| 1025 |
+
2. Action / Tool Call syntax (e.g. Tool Call: todo Arguments: {...})
|
| 1026 |
+
3. Markdown ```json ... ``` code blocks (aggregates ALL blocks across the message)
|
| 1027 |
+
4. Raw balanced JSON blocks containing {"name": "..."}
|
| 1028 |
+
Returns: (tool_calls_list or None, remaining_text)
|
| 1029 |
+
"""
|
| 1030 |
+
if not text or not valid_tool_names:
|
| 1031 |
+
return None, text
|
| 1032 |
+
|
| 1033 |
+
valid_names_lower = {name.lower(): name for name in valid_tool_names}
|
| 1034 |
+
collected_tool_calls = []
|
| 1035 |
+
matched_spans = []
|
| 1036 |
+
|
| 1037 |
+
# -----------------------------------------------------------------------
|
| 1038 |
+
# Pattern 1: Natural Calling syntax (e.g. Calling tool `todo` with arguments: {...})
|
| 1039 |
+
# -----------------------------------------------------------------------
|
| 1040 |
+
calling_patterns = [
|
| 1041 |
+
re.compile(r"Calling\s+tool\s+[`'\"]?([a-zA-Z0-9_\-]+)[`'\"]?\s+with\s+arguments:\s*", re.IGNORECASE),
|
| 1042 |
+
re.compile(r"(?:Tool\s+Call|Action):\s*[`'\"]?([a-zA-Z0-9_\-]+)[`'\"]?\s*(?:Arguments|Action\s+Input):\s*", re.IGNORECASE),
|
| 1043 |
+
re.compile(r"Calling\s+(?:tool\s+)?[`'\"]?([a-zA-Z0-9_\-]+)[`'\"]?\s*\(?\s*arguments:\s*", re.IGNORECASE),
|
| 1044 |
+
]
|
| 1045 |
+
|
| 1046 |
+
for pat in calling_patterns:
|
| 1047 |
+
for m in pat.finditer(text):
|
| 1048 |
+
raw_tool_name = m.group(1).strip()
|
| 1049 |
+
matched_name = valid_names_lower.get(raw_tool_name.lower())
|
| 1050 |
+
if matched_name:
|
| 1051 |
+
balanced = extract_balanced_json(text, m.end())
|
| 1052 |
+
if balanced:
|
| 1053 |
+
args_str, b_start, b_end = balanced
|
| 1054 |
+
try:
|
| 1055 |
+
parsed_args = json.loads(args_str)
|
| 1056 |
+
final_args = json.dumps(parsed_args, ensure_ascii=False) if isinstance(parsed_args, dict) else args_str
|
| 1057 |
+
except Exception:
|
| 1058 |
+
final_args = args_str
|
| 1059 |
+
|
| 1060 |
+
call_id = "call_" + uuid.uuid4().hex[:16]
|
| 1061 |
+
collected_tool_calls.append({
|
| 1062 |
+
"id": call_id,
|
| 1063 |
+
"type": "function",
|
| 1064 |
+
"function": {
|
| 1065 |
+
"name": matched_name,
|
| 1066 |
+
"arguments": final_args,
|
| 1067 |
+
}
|
| 1068 |
+
})
|
| 1069 |
+
matched_spans.append((m.start(), b_end))
|
| 1070 |
+
|
| 1071 |
+
# -----------------------------------------------------------------------
|
| 1072 |
+
# Pattern 2: Markdown code blocks (collect ALL blocks across message)
|
| 1073 |
+
# -----------------------------------------------------------------------
|
| 1074 |
+
code_block_pattern = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```", re.IGNORECASE)
|
| 1075 |
+
for match in code_block_pattern.finditer(text):
|
| 1076 |
+
snippet = match.group(1).strip()
|
| 1077 |
+
try:
|
| 1078 |
+
parsed = json.loads(snippet)
|
| 1079 |
+
except (json.JSONDecodeError, TypeError, ValueError):
|
| 1080 |
+
# Not a JSON payload (e.g. prose in a plain fenced block) - skip it
|
| 1081 |
+
continue
|
| 1082 |
+
|
| 1083 |
+
items = parsed if isinstance(parsed, list) else [parsed]
|
| 1084 |
+
block_calls = []
|
| 1085 |
+
|
| 1086 |
+
for item in items:
|
| 1087 |
+
if isinstance(item, dict) and "name" in item:
|
| 1088 |
+
raw_name = str(item["name"]).strip()
|
| 1089 |
+
matched_name = valid_names_lower.get(raw_name.lower())
|
| 1090 |
+
if matched_name:
|
| 1091 |
+
args = item.get("arguments", {})
|
| 1092 |
+
if isinstance(args, (dict, list)):
|
| 1093 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 1094 |
+
elif isinstance(args, str):
|
| 1095 |
+
try:
|
| 1096 |
+
json.loads(args)
|
| 1097 |
+
args_str = args
|
| 1098 |
+
except Exception:
|
| 1099 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 1100 |
+
else:
|
| 1101 |
+
args_str = json.dumps(str(args), ensure_ascii=False)
|
| 1102 |
+
|
| 1103 |
+
call_id = "call_" + uuid.uuid4().hex[:16]
|
| 1104 |
+
block_calls.append({
|
| 1105 |
+
"id": call_id,
|
| 1106 |
+
"type": "function",
|
| 1107 |
+
"function": {
|
| 1108 |
+
"name": matched_name,
|
| 1109 |
+
"arguments": args_str,
|
| 1110 |
+
}
|
| 1111 |
+
})
|
| 1112 |
+
|
| 1113 |
+
if block_calls:
|
| 1114 |
+
collected_tool_calls.extend(block_calls)
|
| 1115 |
+
matched_spans.append(match.span())
|
| 1116 |
+
|
| 1117 |
+
# If any calls found via Pattern 1 or Pattern 2, return aggregated
|
| 1118 |
+
if collected_tool_calls:
|
| 1119 |
+
remaining = remove_spans(text, matched_spans)
|
| 1120 |
+
return collected_tool_calls, remaining
|
| 1121 |
+
|
| 1122 |
+
# -----------------------------------------------------------------------
|
| 1123 |
+
# Pattern 3: Raw balanced JSON blocks containing {"name": ...} (Fallback)
|
| 1124 |
+
# -----------------------------------------------------------------------
|
| 1125 |
+
pos = 0
|
| 1126 |
+
while pos < len(text):
|
| 1127 |
+
balanced = extract_balanced_json(text, pos)
|
| 1128 |
+
if not balanced:
|
| 1129 |
+
break
|
| 1130 |
+
json_str, b_start, b_end = balanced
|
| 1131 |
+
pos = b_end
|
| 1132 |
+
try:
|
| 1133 |
+
parsed = json.loads(json_str)
|
| 1134 |
+
except (json.JSONDecodeError, TypeError, ValueError):
|
| 1135 |
+
# Brace-balanced but not valid JSON - skip it
|
| 1136 |
+
continue
|
| 1137 |
+
|
| 1138 |
+
items = parsed if isinstance(parsed, list) else [parsed]
|
| 1139 |
+
raw_calls = []
|
| 1140 |
+
|
| 1141 |
+
for item in items:
|
| 1142 |
+
if isinstance(item, dict) and "name" in item:
|
| 1143 |
+
raw_name = str(item["name"]).strip()
|
| 1144 |
+
matched_name = valid_names_lower.get(raw_name.lower())
|
| 1145 |
+
if matched_name:
|
| 1146 |
+
args = item.get("arguments", {})
|
| 1147 |
+
if isinstance(args, (dict, list)):
|
| 1148 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 1149 |
+
elif isinstance(args, str):
|
| 1150 |
+
try:
|
| 1151 |
+
json.loads(args)
|
| 1152 |
+
args_str = args
|
| 1153 |
+
except Exception:
|
| 1154 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 1155 |
+
else:
|
| 1156 |
+
args_str = json.dumps(str(args), ensure_ascii=False)
|
| 1157 |
+
|
| 1158 |
+
call_id = "call_" + uuid.uuid4().hex[:16]
|
| 1159 |
+
raw_calls.append({
|
| 1160 |
+
"id": call_id,
|
| 1161 |
+
"type": "function",
|
| 1162 |
+
"function": {
|
| 1163 |
+
"name": matched_name,
|
| 1164 |
+
"arguments": args_str,
|
| 1165 |
+
}
|
| 1166 |
+
})
|
| 1167 |
+
|
| 1168 |
+
if raw_calls:
|
| 1169 |
+
collected_tool_calls.extend(raw_calls)
|
| 1170 |
+
matched_spans.append((b_start, b_end))
|
| 1171 |
+
|
| 1172 |
+
if collected_tool_calls:
|
| 1173 |
+
remaining = remove_spans(text, matched_spans)
|
| 1174 |
+
return collected_tool_calls, remaining
|
| 1175 |
+
|
| 1176 |
+
return None, text
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
@app.get("/v1/models")
|
| 1180 |
+
async def list_models(request: Request):
|
| 1181 |
+
auth = request.headers.get("authorization")
|
| 1182 |
+
verify_auth(auth)
|
| 1183 |
+
return {
|
| 1184 |
+
"object": "list",
|
| 1185 |
+
"data": [
|
| 1186 |
+
{"id": "mercury-3", "object": "model", "created": current_timestamp(),
|
| 1187 |
+
"owned_by": "inceptionlabs", "description": "Mercury 3 Diffusion LLM (Default: medium reasoning)"},
|
| 1188 |
+
{"id": "mercury-3-instant", "object": "model", "created": current_timestamp(),
|
| 1189 |
+
"owned_by": "inceptionlabs", "description": "Mercury 3 with instant response (zero reasoning overhead)"},
|
| 1190 |
+
{"id": "mercury-3-high", "object": "model", "created": current_timestamp(),
|
| 1191 |
+
"owned_by": "inceptionlabs", "description": "Mercury 3 with high reasoning effort (deep thinking)"},
|
| 1192 |
+
{"id": "mercury-3-search", "object": "model", "created": current_timestamp(),
|
| 1193 |
+
"owned_by": "inceptionlabs", "description": "Mercury 3 with live web search enabled"},
|
| 1194 |
+
],
|
| 1195 |
+
}
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
@app.post("/v1/chat/completions")
|
| 1199 |
+
async def chat_completions(request: Request):
|
| 1200 |
+
auth = request.headers.get("authorization")
|
| 1201 |
+
verify_auth(auth)
|
| 1202 |
+
|
| 1203 |
+
try:
|
| 1204 |
+
body = await request.json()
|
| 1205 |
+
except (json.JSONDecodeError, ValueError) as e:
|
| 1206 |
+
raise HTTPException(status_code=400, detail="Invalid JSON body") from e
|
| 1207 |
+
|
| 1208 |
+
messages = body.get("messages", [])
|
| 1209 |
+
model = body.get("model", DEFAULT_MODEL)
|
| 1210 |
+
stream = body.get("stream", False)
|
| 1211 |
+
|
| 1212 |
+
tools = body.get("tools")
|
| 1213 |
+
functions = body.get("functions")
|
| 1214 |
+
tool_choice = body.get("tool_choice", "auto")
|
| 1215 |
+
|
| 1216 |
+
# Tool Emulation detection
|
| 1217 |
+
tool_defs, valid_tool_names = parse_tool_definitions(tools, functions)
|
| 1218 |
+
has_tools = bool(tool_defs) and tool_choice != "none"
|
| 1219 |
+
tool_prompt = build_tool_system_prompt(tool_defs, tool_choice) if has_tools else None
|
| 1220 |
+
effective_messages = prepare_messages_for_tools(messages, tool_prompt=tool_prompt)
|
| 1221 |
+
|
| 1222 |
+
requested_effort = body.get("reasoning_effort") or body.get("reasoning")
|
| 1223 |
+
if not requested_effort:
|
| 1224 |
+
if "instant" in model:
|
| 1225 |
+
requested_effort = "instant"
|
| 1226 |
+
elif "high" in model:
|
| 1227 |
+
requested_effort = "high"
|
| 1228 |
+
elif "low" in model:
|
| 1229 |
+
requested_effort = "low"
|
| 1230 |
+
else:
|
| 1231 |
+
requested_effort = DEFAULT_REASONING_EFFORT
|
| 1232 |
+
reasoning_effort = normalize_reasoning_effort(requested_effort)
|
| 1233 |
+
web_search = bool(body.get("web_search") or ("search" in model))
|
| 1234 |
+
|
| 1235 |
+
if not messages:
|
| 1236 |
+
raise HTTPException(status_code=400, detail="messages array is required")
|
| 1237 |
+
|
| 1238 |
+
req_id = "chatcmpl-" + uuid.uuid4().hex[:16]
|
| 1239 |
+
created = current_timestamp()
|
| 1240 |
+
|
| 1241 |
+
# Generator for raw real-time streaming when no tools are requested
|
| 1242 |
+
async def real_time_stream_generator():
|
| 1243 |
+
try:
|
| 1244 |
+
async for kind, val in chat_events_with_retry(
|
| 1245 |
+
effective_messages,
|
| 1246 |
+
reasoning_effort=reasoning_effort,
|
| 1247 |
+
web_search=web_search,
|
| 1248 |
+
):
|
| 1249 |
+
if kind == "text":
|
| 1250 |
+
chunk = {
|
| 1251 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1252 |
+
"created": created, "model": model,
|
| 1253 |
+
"choices": [{"index": 0, "delta": {"content": val}, "finish_reason": None}],
|
| 1254 |
+
}
|
| 1255 |
+
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 1256 |
+
elif kind == "reasoning":
|
| 1257 |
+
chunk = {
|
| 1258 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1259 |
+
"created": created, "model": model,
|
| 1260 |
+
"choices": [{"index": 0, "delta": {"reasoning_content": val}, "finish_reason": None}],
|
| 1261 |
+
}
|
| 1262 |
+
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 1263 |
+
elif kind == "citation":
|
| 1264 |
+
chunk = {
|
| 1265 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1266 |
+
"created": created, "model": model,
|
| 1267 |
+
"choices": [{"index": 0, "delta": {"citation": val}, "finish_reason": None}],
|
| 1268 |
+
}
|
| 1269 |
+
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 1270 |
+
except Exception as e:
|
| 1271 |
+
err_chunk = {"error": str(e)}
|
| 1272 |
+
yield f"data: {json.dumps(err_chunk, ensure_ascii=False)}\n\n"
|
| 1273 |
+
return
|
| 1274 |
+
|
| 1275 |
+
end_chunk = {
|
| 1276 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1277 |
+
"created": created, "model": model,
|
| 1278 |
+
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
|
| 1279 |
+
}
|
| 1280 |
+
yield f"data: {json.dumps(end_chunk, ensure_ascii=False)}\n\n"
|
| 1281 |
+
yield "data: [DONE]\n\n"
|
| 1282 |
+
|
| 1283 |
+
# Generator for tool-emulated streaming
|
| 1284 |
+
async def tool_stream_generator():
|
| 1285 |
+
# 1. Send initial role chunk immediately so client / proxy (MG) does not timeout
|
| 1286 |
+
init_chunk = {
|
| 1287 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1288 |
+
"created": created, "model": model,
|
| 1289 |
+
"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
|
| 1290 |
+
}
|
| 1291 |
+
yield f"data: {json.dumps(init_chunk, ensure_ascii=False)}\n\n"
|
| 1292 |
+
|
| 1293 |
+
full_text = []
|
| 1294 |
+
try:
|
| 1295 |
+
async for kind, val in chat_events_with_retry(
|
| 1296 |
+
effective_messages,
|
| 1297 |
+
reasoning_effort=reasoning_effort,
|
| 1298 |
+
web_search=web_search,
|
| 1299 |
+
):
|
| 1300 |
+
if kind == "text":
|
| 1301 |
+
full_text.append(val)
|
| 1302 |
+
elif kind == "reasoning":
|
| 1303 |
+
# Stream reasoning content in real-time! Keep connection active & show thinking
|
| 1304 |
+
r_chunk = {
|
| 1305 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1306 |
+
"created": created, "model": model,
|
| 1307 |
+
"choices": [{"index": 0, "delta": {"reasoning_content": val}, "finish_reason": None}],
|
| 1308 |
+
}
|
| 1309 |
+
yield f"data: {json.dumps(r_chunk, ensure_ascii=False)}\n\n"
|
| 1310 |
+
elif kind == "citation":
|
| 1311 |
+
c_chunk = {
|
| 1312 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1313 |
+
"created": created, "model": model,
|
| 1314 |
+
"choices": [{"index": 0, "delta": {"citation": val}, "finish_reason": None}],
|
| 1315 |
+
}
|
| 1316 |
+
yield f"data: {json.dumps(c_chunk, ensure_ascii=False)}\n\n"
|
| 1317 |
+
except Exception as e:
|
| 1318 |
+
err_msg = f"[Upstream Error]: {str(e)}"
|
| 1319 |
+
err_chunk = {
|
| 1320 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1321 |
+
"created": created, "model": model,
|
| 1322 |
+
"choices": [{"index": 0, "delta": {"content": err_msg}, "finish_reason": "stop"}],
|
| 1323 |
+
}
|
| 1324 |
+
yield f"data: {json.dumps(err_chunk, ensure_ascii=False)}\n\n"
|
| 1325 |
+
yield "data: [DONE]\n\n"
|
| 1326 |
+
return
|
| 1327 |
+
|
| 1328 |
+
# Check for tool call in output
|
| 1329 |
+
merged_text = "".join(full_text)
|
| 1330 |
+
tool_calls, remaining_content = extract_tool_calls(merged_text, valid_tool_names)
|
| 1331 |
+
|
| 1332 |
+
if tool_calls:
|
| 1333 |
+
if remaining_content:
|
| 1334 |
+
chunk = {
|
| 1335 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1336 |
+
"created": created, "model": model,
|
| 1337 |
+
"choices": [{"index": 0, "delta": {"content": remaining_content}, "finish_reason": None}],
|
| 1338 |
+
}
|
| 1339 |
+
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 1340 |
+
|
| 1341 |
+
delta_tool_calls = [
|
| 1342 |
+
{
|
| 1343 |
+
"index": idx,
|
| 1344 |
+
"id": tc["id"],
|
| 1345 |
+
"type": "function",
|
| 1346 |
+
"function": {
|
| 1347 |
+
"name": tc["function"]["name"],
|
| 1348 |
+
"arguments": tc["function"]["arguments"],
|
| 1349 |
+
}
|
| 1350 |
+
}
|
| 1351 |
+
for idx, tc in enumerate(tool_calls)
|
| 1352 |
+
]
|
| 1353 |
+
tc_chunk = {
|
| 1354 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1355 |
+
"created": created, "model": model,
|
| 1356 |
+
"choices": [{"index": 0, "delta": {"tool_calls": delta_tool_calls}, "finish_reason": None}],
|
| 1357 |
+
}
|
| 1358 |
+
yield f"data: {json.dumps(tc_chunk, ensure_ascii=False)}\n\n"
|
| 1359 |
+
|
| 1360 |
+
end_chunk = {
|
| 1361 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1362 |
+
"created": created, "model": model,
|
| 1363 |
+
"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
|
| 1364 |
+
}
|
| 1365 |
+
yield f"data: {json.dumps(end_chunk, ensure_ascii=False)}\n\n"
|
| 1366 |
+
else:
|
| 1367 |
+
# Normal plain text output - stream in chunks
|
| 1368 |
+
step = 30
|
| 1369 |
+
for i in range(0, len(merged_text), step):
|
| 1370 |
+
sub_text = merged_text[i:i + step]
|
| 1371 |
+
chunk = {
|
| 1372 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1373 |
+
"created": created, "model": model,
|
| 1374 |
+
"choices": [{"index": 0, "delta": {"content": sub_text}, "finish_reason": None}],
|
| 1375 |
+
}
|
| 1376 |
+
yield f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 1377 |
+
|
| 1378 |
+
end_chunk = {
|
| 1379 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1380 |
+
"created": created, "model": model,
|
| 1381 |
+
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
|
| 1382 |
+
}
|
| 1383 |
+
yield f"data: {json.dumps(end_chunk, ensure_ascii=False)}\n\n"
|
| 1384 |
+
|
| 1385 |
+
yield "data: [DONE]\n\n"
|
| 1386 |
+
|
| 1387 |
+
if stream:
|
| 1388 |
+
if has_tools:
|
| 1389 |
+
return StreamingResponse(tool_stream_generator(), media_type="text/event-stream")
|
| 1390 |
+
else:
|
| 1391 |
+
first_chunk = {
|
| 1392 |
+
"id": req_id, "object": "chat.completion.chunk",
|
| 1393 |
+
"created": created, "model": model,
|
| 1394 |
+
"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}],
|
| 1395 |
+
}
|
| 1396 |
+
async def combined_generator():
|
| 1397 |
+
yield f"data: {json.dumps(first_chunk, ensure_ascii=False)}\n\n"
|
| 1398 |
+
async for item in real_time_stream_generator():
|
| 1399 |
+
yield item
|
| 1400 |
+
return StreamingResponse(combined_generator(), media_type="text/event-stream")
|
| 1401 |
+
|
| 1402 |
+
else:
|
| 1403 |
+
full_text = []
|
| 1404 |
+
full_reasoning = []
|
| 1405 |
+
citations = []
|
| 1406 |
+
try:
|
| 1407 |
+
async for kind, val in chat_events_with_retry(
|
| 1408 |
+
effective_messages,
|
| 1409 |
+
reasoning_effort=reasoning_effort,
|
| 1410 |
+
web_search=web_search,
|
| 1411 |
+
):
|
| 1412 |
+
if kind == "text":
|
| 1413 |
+
full_text.append(val)
|
| 1414 |
+
elif kind == "reasoning":
|
| 1415 |
+
full_reasoning.append(val)
|
| 1416 |
+
elif kind == "citation":
|
| 1417 |
+
citations.append(val)
|
| 1418 |
+
except Exception as e:
|
| 1419 |
+
raise HTTPException(status_code=502, detail=f"Upstream chat error: {str(e)}") from e
|
| 1420 |
+
|
| 1421 |
+
merged_text = "".join(full_text)
|
| 1422 |
+
tool_calls = None
|
| 1423 |
+
finish_reason = "stop"
|
| 1424 |
+
msg_payload: dict[str, Any]
|
| 1425 |
+
|
| 1426 |
+
if has_tools:
|
| 1427 |
+
tool_calls, remaining_content = extract_tool_calls(merged_text, valid_tool_names)
|
| 1428 |
+
if tool_calls:
|
| 1429 |
+
finish_reason = "tool_calls"
|
| 1430 |
+
msg_payload = {
|
| 1431 |
+
"role": "assistant",
|
| 1432 |
+
"content": remaining_content or None,
|
| 1433 |
+
"tool_calls": tool_calls,
|
| 1434 |
+
}
|
| 1435 |
+
else:
|
| 1436 |
+
msg_payload = {"role": "assistant", "content": merged_text}
|
| 1437 |
+
else:
|
| 1438 |
+
msg_payload = {"role": "assistant", "content": merged_text}
|
| 1439 |
+
|
| 1440 |
+
if full_reasoning:
|
| 1441 |
+
msg_payload["reasoning_content"] = "".join(full_reasoning)
|
| 1442 |
+
if citations:
|
| 1443 |
+
msg_payload["citations"] = citations
|
| 1444 |
+
|
| 1445 |
+
return {
|
| 1446 |
+
"id": req_id,
|
| 1447 |
+
"object": "chat.completion",
|
| 1448 |
+
"created": created,
|
| 1449 |
+
"model": model,
|
| 1450 |
+
"choices": [
|
| 1451 |
+
{
|
| 1452 |
+
"index": 0,
|
| 1453 |
+
"message": msg_payload,
|
| 1454 |
+
"finish_reason": finish_reason,
|
| 1455 |
+
}
|
| 1456 |
+
],
|
| 1457 |
+
"usage": {
|
| 1458 |
+
"prompt_tokens": estimate_tokens(
|
| 1459 |
+
"".join(str(m.get("content", "")) for m in effective_messages)
|
| 1460 |
+
),
|
| 1461 |
+
"completion_tokens": estimate_tokens(merged_text),
|
| 1462 |
+
"total_tokens": estimate_tokens(
|
| 1463 |
+
"".join(str(m.get("content", "")) for m in effective_messages)
|
| 1464 |
+
) + estimate_tokens(merged_text),
|
| 1465 |
+
},
|
| 1466 |
+
}
|
| 1467 |
+
|
| 1468 |
+
|
| 1469 |
+
if __name__ == "__main__":
|
| 1470 |
+
print(f"[*] Starting Inception Web-to-API on {HOST}:{PORT}")
|
| 1471 |
+
print(f"[*] Engine: {ENGINE}")
|
| 1472 |
+
print(f"[*] Proxy: {PROXY_URL or 'Direct Connection'}")
|
| 1473 |
+
print(f"[*] API Key Protection: {'Enabled' if API_KEY else 'Disabled (Open)'}")
|
| 1474 |
+
uvicorn.run(app, host=HOST, port=PORT)
|
docker-compose.slim.yml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
inception-api:
|
| 3 |
+
build:
|
| 4 |
+
context: .
|
| 5 |
+
dockerfile: Dockerfile.slim
|
| 6 |
+
container_name: inception-web-api-slim
|
| 7 |
+
restart: unless-stopped
|
| 8 |
+
ports:
|
| 9 |
+
- "8011:8011"
|
| 10 |
+
environment:
|
| 11 |
+
- PORT=8011
|
| 12 |
+
- HOST=0.0.0.0
|
| 13 |
+
- ENGINE=curl
|
| 14 |
+
# - PROXY_URL=http://your-clean-proxy:7890
|
| 15 |
+
# - API_KEY=sk-mysecretkey
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
inception-web-api:
|
| 3 |
+
# 方案一:默认浏览器桥接模式(推荐机房 VPS / 裸金属服务器,自动突破 Vercel Checkpoint,镜像约 650MB)
|
| 4 |
+
build: .
|
| 5 |
+
|
| 6 |
+
# 方案二:极简纯协议零浏览器模式(镜像仅 50MB,内存仅 25MB;若需切换请解除下面两行注释,并注释掉上面的 build: .)
|
| 7 |
+
# build:
|
| 8 |
+
# context: .
|
| 9 |
+
# dockerfile: Dockerfile.slim
|
| 10 |
+
|
| 11 |
+
container_name: inception-web-api
|
| 12 |
+
restart: always
|
| 13 |
+
ports:
|
| 14 |
+
- "8011:8011"
|
| 15 |
+
environment:
|
| 16 |
+
- PORT=8011
|
| 17 |
+
- HOST=0.0.0.0
|
| 18 |
+
# 引擎切换:browser (无头浏览器桥接) 或 curl (零浏览器纯协议)
|
| 19 |
+
- ENGINE=browser
|
| 20 |
+
# 可选:自定义服务鉴权密钥
|
| 21 |
+
# - API_KEY=sk-your-secret-key-here
|
| 22 |
+
# 可选:上游代理地址(若机器处于机房 IP 且需要出口代理,建议配置纯净上游代理)
|
| 23 |
+
# - PROXY_URL=http://your-proxy-here:port
|
| 24 |
+
# 可选:手动指定 Chromium 可执行文件绝对路径
|
| 25 |
+
# - CHROME_PATH=/usr/bin/chromium
|
| 26 |
+
# Chromium 在容器内需要足够的 /dev/shm,否则多标签页会崩溃
|
| 27 |
+
shm_size: '512mb'
|
| 28 |
+
# browser 引擎常驻 Chromium,建议限制内存防止 OOM 拖垮宿主
|
| 29 |
+
# mem_limit: 1g
|
requirements.txt
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
natsort
|
|
|
|
| 1 |
+
fastapi>=0.115.0
|
| 2 |
+
uvicorn>=0.30.0
|
| 3 |
+
playwright>=1.49.0
|
| 4 |
+
curl_cffi>=0.7.0
|
|
|
test_concurrency.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import asyncio
|
| 3 |
+
import time
|
| 4 |
+
import json
|
| 5 |
+
from unittest.mock import patch, AsyncMock
|
| 6 |
+
from httpx import AsyncClient, ASGITransport
|
| 7 |
+
from app import app, CurlEngine, POOL_SIZE
|
| 8 |
+
|
| 9 |
+
class TestConcurrencyAndPooling(unittest.IsolatedAsyncioTestCase):
|
| 10 |
+
async def test_curl_engine_token_pool_round_robin(self):
|
| 11 |
+
"""Verifies that the Token Pool acquires multiple tokens and distributes them via round-robin."""
|
| 12 |
+
engine = CurlEngine(pool_size=3)
|
| 13 |
+
mock_tokens = [
|
| 14 |
+
("tok_aaa_111", time.time() + 600),
|
| 15 |
+
("tok_bbb_222", time.time() + 600),
|
| 16 |
+
("tok_ccc_333", time.time() + 600),
|
| 17 |
+
]
|
| 18 |
+
call_idx = 0
|
| 19 |
+
|
| 20 |
+
async def fake_fetch():
|
| 21 |
+
nonlocal call_idx
|
| 22 |
+
res = mock_tokens[call_idx % len(mock_tokens)]
|
| 23 |
+
call_idx += 1
|
| 24 |
+
return res
|
| 25 |
+
|
| 26 |
+
engine._fetch_single_token = fake_fetch
|
| 27 |
+
|
| 28 |
+
# Fetch 6 times, should cycle through tokens
|
| 29 |
+
collected = []
|
| 30 |
+
for _ in range(6):
|
| 31 |
+
tok = await engine.get_token()
|
| 32 |
+
collected.append(tok)
|
| 33 |
+
|
| 34 |
+
self.assertEqual(len(engine.token_pool), 3)
|
| 35 |
+
# Should cycle in round-robin order
|
| 36 |
+
self.assertEqual(collected[0], collected[3])
|
| 37 |
+
self.assertEqual(collected[1], collected[4])
|
| 38 |
+
self.assertEqual(collected[2], collected[5])
|
| 39 |
+
|
| 40 |
+
async def test_high_concurrency_non_blocking_streaming(self):
|
| 41 |
+
"""
|
| 42 |
+
Simulates 10 concurrent requests executing simultaneously without event loop blocking.
|
| 43 |
+
Each request has a simulated upstream network latency of 50ms.
|
| 44 |
+
If blocking occurred, 10 * 50ms = 500ms+. With async non-blocking, total time ~ 50-100ms.
|
| 45 |
+
"""
|
| 46 |
+
async def mock_events(messages, **kwargs):
|
| 47 |
+
# Simulate upstream streaming latency
|
| 48 |
+
await asyncio.sleep(0.05)
|
| 49 |
+
yield ("text", f"Echo from req")
|
| 50 |
+
await asyncio.sleep(0.05)
|
| 51 |
+
yield ("text", " done")
|
| 52 |
+
|
| 53 |
+
transport = ASGITransport(app=app)
|
| 54 |
+
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
| 55 |
+
with patch("app.engine.chat_events", side_effect=mock_events):
|
| 56 |
+
start_time = time.time()
|
| 57 |
+
|
| 58 |
+
async def single_client(idx: int):
|
| 59 |
+
resp = await ac.post("/v1/chat/completions", json={
|
| 60 |
+
"model": "mercury-3",
|
| 61 |
+
"messages": [{"role": "user", "content": f"Hello {idx}"}],
|
| 62 |
+
"stream": True
|
| 63 |
+
})
|
| 64 |
+
self.assertEqual(resp.status_code, 200)
|
| 65 |
+
chunks = []
|
| 66 |
+
async for line in resp.aiter_lines():
|
| 67 |
+
if line.startswith("data: ") and line != "data: [DONE]":
|
| 68 |
+
chunks.append(json.loads(line[6:]))
|
| 69 |
+
return chunks
|
| 70 |
+
|
| 71 |
+
# Launch 10 requests concurrently
|
| 72 |
+
results = await asyncio.gather(*(single_client(i) for i in range(10)))
|
| 73 |
+
|
| 74 |
+
elapsed = time.time() - start_time
|
| 75 |
+
self.assertEqual(len(results), 10)
|
| 76 |
+
for res in results:
|
| 77 |
+
self.assertTrue(len(res) > 0)
|
| 78 |
+
|
| 79 |
+
# Total elapsed time should be well below sequential 1000ms
|
| 80 |
+
print(f"[*] 10 Concurrent streaming requests finished in: {elapsed:.3f}s")
|
| 81 |
+
self.assertLess(elapsed, 0.5)
|
| 82 |
+
|
| 83 |
+
async def test_health_endpoint_reports_pool_status(self):
|
| 84 |
+
transport = ASGITransport(app=app)
|
| 85 |
+
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
| 86 |
+
resp = await ac.get("/health")
|
| 87 |
+
self.assertEqual(resp.status_code, 200)
|
| 88 |
+
data = resp.json()
|
| 89 |
+
self.assertIn("pool_size", data)
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import json
|
| 3 |
+
import uuid
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
from fastapi.testclient import TestClient
|
| 6 |
+
from app import app, compact_tool_definitions
|
| 7 |
+
|
| 8 |
+
client = TestClient(app)
|
| 9 |
+
|
| 10 |
+
def generate_agent_tools():
|
| 11 |
+
"""Generates a realistic suite of 55 tools matching Pi Coding Agent + OpenViking."""
|
| 12 |
+
base_tools = [
|
| 13 |
+
{
|
| 14 |
+
"type": "function",
|
| 15 |
+
"function": {
|
| 16 |
+
"name": "todo",
|
| 17 |
+
"description": "Manage a task list for tracking multi-step progress. Actions: create, update, list, get, delete, clear.",
|
| 18 |
+
"parameters": {
|
| 19 |
+
"type": "object",
|
| 20 |
+
"properties": {
|
| 21 |
+
"action": {"type": "string", "enum": ["create", "update", "list", "get", "delete", "clear"]},
|
| 22 |
+
"id": {"type": "integer", "description": "Task ID"},
|
| 23 |
+
"subject": {"type": "string", "description": "Short task title"},
|
| 24 |
+
"status": {"type": "string", "enum": ["pending", "in_progress", "completed", "deleted"]},
|
| 25 |
+
"activeForm": {"type": "string", "description": "Present-continuous spinner label"},
|
| 26 |
+
"tasks": {"type": "array", "description": "Batch create tasks"}
|
| 27 |
+
},
|
| 28 |
+
"required": ["action"]
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"type": "function",
|
| 34 |
+
"function": {
|
| 35 |
+
"name": "bash",
|
| 36 |
+
"description": "Execute bash commands in the current working directory.",
|
| 37 |
+
"parameters": {
|
| 38 |
+
"type": "object",
|
| 39 |
+
"properties": {
|
| 40 |
+
"command": {"type": "string", "description": "Shell command to execute"},
|
| 41 |
+
"timeout": {"type": "number", "description": "Timeout in seconds"}
|
| 42 |
+
},
|
| 43 |
+
"required": ["command"]
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"type": "function",
|
| 49 |
+
"function": {
|
| 50 |
+
"name": "read",
|
| 51 |
+
"description": "Read file contents with optional offset and limit.",
|
| 52 |
+
"parameters": {
|
| 53 |
+
"type": "object",
|
| 54 |
+
"properties": {
|
| 55 |
+
"path": {"type": "string", "description": "Path to the file to read"},
|
| 56 |
+
"offset": {"type": "integer", "description": "Line number to start reading from"},
|
| 57 |
+
"limit": {"type": "integer", "description": "Maximum number of lines to read"}
|
| 58 |
+
},
|
| 59 |
+
"required": ["path"]
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"type": "function",
|
| 65 |
+
"function": {
|
| 66 |
+
"name": "edit",
|
| 67 |
+
"description": "Edit a single file using exact text replacement.",
|
| 68 |
+
"parameters": {
|
| 69 |
+
"type": "object",
|
| 70 |
+
"properties": {
|
| 71 |
+
"path": {"type": "string", "description": "Path to file"},
|
| 72 |
+
"edits": {
|
| 73 |
+
"type": "array",
|
| 74 |
+
"items": {
|
| 75 |
+
"type": "object",
|
| 76 |
+
"properties": {
|
| 77 |
+
"oldText": {"type": "string"},
|
| 78 |
+
"newText": {"type": "string"}
|
| 79 |
+
},
|
| 80 |
+
"required": ["oldText", "newText"]
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
},
|
| 84 |
+
"required": ["path", "edits"]
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"type": "function",
|
| 90 |
+
"function": {
|
| 91 |
+
"name": "lens_diagnostics",
|
| 92 |
+
"description": "Query pi-lens diagnostics from LSP probe.",
|
| 93 |
+
"parameters": {
|
| 94 |
+
"type": "object",
|
| 95 |
+
"properties": {
|
| 96 |
+
"paths": {"type": "array", "items": {"type": "string"}},
|
| 97 |
+
"scope": {"type": "string", "enum": ["paths", "workspace"]},
|
| 98 |
+
"source": {"type": "string", "enum": ["lsp", "session"]}
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"type": "function",
|
| 105 |
+
"function": {
|
| 106 |
+
"name": "openviking_search",
|
| 107 |
+
"description": "Retrieval with optional session context from OpenViking long term memory.",
|
| 108 |
+
"parameters": {
|
| 109 |
+
"type": "object",
|
| 110 |
+
"properties": {
|
| 111 |
+
"query": {"type": "string", "description": "Semantic query"},
|
| 112 |
+
"limit": {"type": "integer"}
|
| 113 |
+
},
|
| 114 |
+
"required": ["query"]
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
# Fill up to 55 realistic tools to simulate full Pi environment
|
| 121 |
+
for i in range(1, 50):
|
| 122 |
+
base_tools.append({
|
| 123 |
+
"type": "function",
|
| 124 |
+
"function": {
|
| 125 |
+
"name": f"extra_tool_{i}",
|
| 126 |
+
"description": f"Extended utility tool {i} for specific subsystem operations.",
|
| 127 |
+
"parameters": {
|
| 128 |
+
"type": "object",
|
| 129 |
+
"properties": {
|
| 130 |
+
"target": {"type": "string"},
|
| 131 |
+
"options": {"type": "object"}
|
| 132 |
+
},
|
| 133 |
+
"required": ["target"]
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
})
|
| 137 |
+
|
| 138 |
+
return base_tools
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class TestFullAgentWorkflow(unittest.TestCase):
|
| 142 |
+
def setUp(self):
|
| 143 |
+
self.tools = generate_agent_tools()
|
| 144 |
+
|
| 145 |
+
def test_schema_compaction_on_full_suite(self):
|
| 146 |
+
"""Verifies that 55 tools are compacted without error and remain under budget."""
|
| 147 |
+
raw_defs = [t["function"] for t in self.tools]
|
| 148 |
+
compacted = compact_tool_definitions(raw_defs)
|
| 149 |
+
self.assertLessEqual(len(compacted), 50)
|
| 150 |
+
json_str = json.dumps(compacted, ensure_ascii=False, separators=(',', ':'))
|
| 151 |
+
self.assertLess(len(json_str), 30000)
|
| 152 |
+
|
| 153 |
+
@patch("app.engine.chat_events")
|
| 154 |
+
def test_multi_turn_agent_loop_streaming(self, mock_chat_events):
|
| 155 |
+
"""
|
| 156 |
+
Simulates a complete 5-turn Agent Loop using streaming (stream=True):
|
| 157 |
+
Round 1: Calling tool `todo` with arguments: {...} (Natural format)
|
| 158 |
+
Round 2: Markdown block ````json {"name": "read", ...} ````
|
| 159 |
+
Round 3: Concurrent tools [bash, lens_diagnostics]
|
| 160 |
+
Round 4: Bare json {"name": "edit", ...}
|
| 161 |
+
Round 5: Final text answer (finish_reason='stop')
|
| 162 |
+
"""
|
| 163 |
+
responses_pool = [
|
| 164 |
+
# Round 1: Natural calling syntax (user-reported case)
|
| 165 |
+
[
|
| 166 |
+
("reasoning", "I should create a task first.\n"),
|
| 167 |
+
("text", "✅ 准备就绪,开始创建任务。\nCalling tool `todo` with arguments: {\"action\": \"create\", \"tasks\": [{\"subject\": \"Check system\"}]}")
|
| 168 |
+
],
|
| 169 |
+
# Round 2: Standard markdown code block
|
| 170 |
+
[
|
| 171 |
+
("reasoning", "Now let me inspect app.py.\n"),
|
| 172 |
+
("text", "Task created. Now reading the file.\n```json\n{\"name\": \"read\", \"arguments\": {\"path\": \"app.py\", \"limit\": 50}}\n```")
|
| 173 |
+
],
|
| 174 |
+
# Round 3: Multi-tool concurrent calling
|
| 175 |
+
[
|
| 176 |
+
("reasoning", "Running git check and diagnostics concurrently.\n"),
|
| 177 |
+
("text", "```json\n[\n {\"name\": \"bash\", \"arguments\": {\"command\": \"git status\"}},\n {\"name\": \"lens_diagnostics\", \"arguments\": {\"paths\": [\"app.py\"]}}\n]\n```")
|
| 178 |
+
],
|
| 179 |
+
# Round 4: Bare JSON object with conversational lead
|
| 180 |
+
[
|
| 181 |
+
("reasoning", "Applying the final edit.\n"),
|
| 182 |
+
("text", "I will now edit the file to fix the issue: {\"name\": \"edit\", \"arguments\": {\"path\": \"app.py\", \"edits\": [{\"oldText\": \"A\", \"newText\": \"B\"}]}}")
|
| 183 |
+
],
|
| 184 |
+
# Round 5: Final completion (no tools)
|
| 185 |
+
[
|
| 186 |
+
("reasoning", "All actions complete.\n"),
|
| 187 |
+
("text", "All 4 tasks have been successfully executed! The repository is clean and passing all tests.")
|
| 188 |
+
]
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
turn = 0
|
| 192 |
+
def get_turn_events(*args, **kwargs):
|
| 193 |
+
nonlocal turn
|
| 194 |
+
events = responses_pool[turn]
|
| 195 |
+
turn += 1
|
| 196 |
+
async def gen():
|
| 197 |
+
for k, v in events:
|
| 198 |
+
yield (k, v)
|
| 199 |
+
return gen()
|
| 200 |
+
|
| 201 |
+
mock_chat_events.side_effect = get_turn_events
|
| 202 |
+
|
| 203 |
+
# Initial Agent Message
|
| 204 |
+
messages = [
|
| 205 |
+
{"role": "system", "content": "You are Pi, an autonomous coding agent harness."},
|
| 206 |
+
{"role": "user", "content": "Please inspect app.py, check diagnostics, and apply the fix."}
|
| 207 |
+
]
|
| 208 |
+
|
| 209 |
+
executed_tools = []
|
| 210 |
+
|
| 211 |
+
# Run 5 turns of the Agent Loop
|
| 212 |
+
for round_idx in range(5):
|
| 213 |
+
req_body = {
|
| 214 |
+
"model": "mercury-3",
|
| 215 |
+
"messages": messages,
|
| 216 |
+
"tools": self.tools,
|
| 217 |
+
"tool_choice": "auto",
|
| 218 |
+
"stream": True
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
resp = client.post("/v1/chat/completions", json=req_body)
|
| 222 |
+
self.assertEqual(resp.status_code, 200)
|
| 223 |
+
|
| 224 |
+
# Consume SSE stream
|
| 225 |
+
chunks = []
|
| 226 |
+
for line in resp.iter_lines():
|
| 227 |
+
if line.startswith("data: ") and line != "data: [DONE]":
|
| 228 |
+
chunks.append(json.loads(line[6:]))
|
| 229 |
+
|
| 230 |
+
# Extract tool calls and finish reason from chunks
|
| 231 |
+
tool_calls = []
|
| 232 |
+
finish_reason = None
|
| 233 |
+
assistant_content = []
|
| 234 |
+
|
| 235 |
+
for c in chunks:
|
| 236 |
+
choice = c["choices"][0]
|
| 237 |
+
delta = choice.get("delta", {})
|
| 238 |
+
if "content" in delta and delta["content"]:
|
| 239 |
+
assistant_content.append(delta["content"])
|
| 240 |
+
if "tool_calls" in delta and delta["tool_calls"]:
|
| 241 |
+
tool_calls.extend(delta["tool_calls"])
|
| 242 |
+
if choice.get("finish_reason"):
|
| 243 |
+
finish_reason = choice["finish_reason"]
|
| 244 |
+
|
| 245 |
+
if finish_reason == "tool_calls":
|
| 246 |
+
self.assertTrue(len(tool_calls) > 0)
|
| 247 |
+
# Append assistant message with tool calls
|
| 248 |
+
formatted_tc = []
|
| 249 |
+
for tc in tool_calls:
|
| 250 |
+
fname = tc["function"]["name"]
|
| 251 |
+
fargs = tc["function"]["arguments"]
|
| 252 |
+
call_id = tc.get("id") or ("call_" + uuid.uuid4().hex[:12])
|
| 253 |
+
formatted_tc.append({
|
| 254 |
+
"id": call_id,
|
| 255 |
+
"type": "function",
|
| 256 |
+
"function": {"name": fname, "arguments": fargs}
|
| 257 |
+
})
|
| 258 |
+
executed_tools.append(fname)
|
| 259 |
+
|
| 260 |
+
messages.append({
|
| 261 |
+
"role": "assistant",
|
| 262 |
+
"content": "".join(assistant_content),
|
| 263 |
+
"tool_calls": formatted_tc
|
| 264 |
+
})
|
| 265 |
+
|
| 266 |
+
# Client executes each tool and appends role="tool"
|
| 267 |
+
for tc in formatted_tc:
|
| 268 |
+
mock_tool_result = f'{{"status": "ok", "tool": "{tc["function"]["name"]}", "executed": true}}'
|
| 269 |
+
messages.append({
|
| 270 |
+
"role": "tool",
|
| 271 |
+
"tool_call_id": tc["id"],
|
| 272 |
+
"name": tc["function"]["name"],
|
| 273 |
+
"content": mock_tool_result
|
| 274 |
+
})
|
| 275 |
+
else:
|
| 276 |
+
self.assertEqual(finish_reason, "stop")
|
| 277 |
+
self.assertIn("All 4 tasks have been successfully executed", "".join(assistant_content))
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
# Verify all tools across all turns were captured and executed in order
|
| 281 |
+
self.assertEqual(executed_tools, ["todo", "read", "bash", "lens_diagnostics", "edit"])
|
| 282 |
+
|
| 283 |
+
@patch("app.engine.chat_events")
|
| 284 |
+
def test_multi_turn_agent_loop_non_streaming(self, mock_chat_events):
|
| 285 |
+
"""Verifies the same 5-turn cycle under non-streaming mode (stream=False)."""
|
| 286 |
+
responses_pool = [
|
| 287 |
+
[("text", "Calling tool `bash` with arguments: {\"command\": \"pwd\"}")],
|
| 288 |
+
[("text", "```json\n{\"name\": \"todo\", \"arguments\": {\"action\": \"list\"}}\n```")],
|
| 289 |
+
[("text", "Done! Finished everything.")]
|
| 290 |
+
]
|
| 291 |
+
|
| 292 |
+
turn = 0
|
| 293 |
+
def get_turn_events(*args, **kwargs):
|
| 294 |
+
nonlocal turn
|
| 295 |
+
events = responses_pool[turn]
|
| 296 |
+
turn += 1
|
| 297 |
+
async def gen():
|
| 298 |
+
for k, v in events:
|
| 299 |
+
yield (k, v)
|
| 300 |
+
return gen()
|
| 301 |
+
|
| 302 |
+
mock_chat_events.side_effect = get_turn_events
|
| 303 |
+
|
| 304 |
+
messages = [{"role": "user", "content": "Run commands."}]
|
| 305 |
+
|
| 306 |
+
# Turn 1: bash
|
| 307 |
+
r1 = client.post("/v1/chat/completions", json={
|
| 308 |
+
"model": "mercury-3",
|
| 309 |
+
"messages": messages,
|
| 310 |
+
"tools": self.tools,
|
| 311 |
+
"stream": False
|
| 312 |
+
})
|
| 313 |
+
d1 = r1.json()["choices"][0]
|
| 314 |
+
self.assertEqual(d1["finish_reason"], "tool_calls")
|
| 315 |
+
self.assertEqual(d1["message"]["tool_calls"][0]["function"]["name"], "bash")
|
| 316 |
+
|
| 317 |
+
messages.append(d1["message"])
|
| 318 |
+
messages.append({"role": "tool", "tool_call_id": d1["message"]["tool_calls"][0]["id"], "content": "/home/app"})
|
| 319 |
+
|
| 320 |
+
# Turn 2: todo
|
| 321 |
+
r2 = client.post("/v1/chat/completions", json={
|
| 322 |
+
"model": "mercury-3",
|
| 323 |
+
"messages": messages,
|
| 324 |
+
"tools": self.tools,
|
| 325 |
+
"stream": False
|
| 326 |
+
})
|
| 327 |
+
d2 = r2.json()["choices"][0]
|
| 328 |
+
self.assertEqual(d2["finish_reason"], "tool_calls")
|
| 329 |
+
self.assertEqual(d2["message"]["tool_calls"][0]["function"]["name"], "todo")
|
| 330 |
+
|
| 331 |
+
messages.append(d2["message"])
|
| 332 |
+
messages.append({"role": "tool", "tool_call_id": d2["message"]["tool_calls"][0]["id"], "content": "[]"})
|
| 333 |
+
|
| 334 |
+
# Turn 3: finish
|
| 335 |
+
r3 = client.post("/v1/chat/completions", json={
|
| 336 |
+
"model": "mercury-3",
|
| 337 |
+
"messages": messages,
|
| 338 |
+
"tools": self.tools,
|
| 339 |
+
"stream": False
|
| 340 |
+
})
|
| 341 |
+
d3 = r3.json()["choices"][0]
|
| 342 |
+
self.assertEqual(d3["finish_reason"], "stop")
|
| 343 |
+
self.assertIn("Done! Finished everything.", d3["message"]["content"])
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == "__main__":
|
| 347 |
+
unittest.main()
|
test_tool_emulation.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
import json
|
| 3 |
+
import asyncio
|
| 4 |
+
from unittest.mock import patch, MagicMock
|
| 5 |
+
from app import (
|
| 6 |
+
parse_tool_definitions,
|
| 7 |
+
build_tool_system_prompt,
|
| 8 |
+
prepare_messages_for_tools,
|
| 9 |
+
extract_tool_calls,
|
| 10 |
+
normalize_upstream_messages,
|
| 11 |
+
build_upstream_payload,
|
| 12 |
+
app,
|
| 13 |
+
)
|
| 14 |
+
from fastapi.testclient import TestClient
|
| 15 |
+
|
| 16 |
+
client = TestClient(app)
|
| 17 |
+
|
| 18 |
+
class TestToolEmulation(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.sample_tools = [
|
| 21 |
+
{
|
| 22 |
+
"type": "function",
|
| 23 |
+
"function": {
|
| 24 |
+
"name": "get_weather",
|
| 25 |
+
"description": "Get current weather in city",
|
| 26 |
+
"parameters": {
|
| 27 |
+
"type": "object",
|
| 28 |
+
"properties": {
|
| 29 |
+
"location": {"type": "string", "description": "City name"}
|
| 30 |
+
},
|
| 31 |
+
"required": ["location"]
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"type": "function",
|
| 37 |
+
"function": {
|
| 38 |
+
"name": "calculate",
|
| 39 |
+
"description": "Calculate math expression",
|
| 40 |
+
"parameters": {
|
| 41 |
+
"type": "object",
|
| 42 |
+
"properties": {
|
| 43 |
+
"expr": {"type": "string"}
|
| 44 |
+
},
|
| 45 |
+
"required": ["expr"]
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
def test_parse_tool_definitions(self):
|
| 52 |
+
tool_defs, valid_names = parse_tool_definitions(self.sample_tools)
|
| 53 |
+
self.assertEqual(valid_names, ["get_weather", "calculate"])
|
| 54 |
+
self.assertEqual(len(tool_defs), 2)
|
| 55 |
+
|
| 56 |
+
# Legacy functions support
|
| 57 |
+
legacy_functions = [{"name": "search", "description": "web search"}]
|
| 58 |
+
tool_defs2, valid_names2 = parse_tool_definitions(None, functions=legacy_functions)
|
| 59 |
+
self.assertEqual(valid_names2, ["search"])
|
| 60 |
+
|
| 61 |
+
def test_build_tool_system_prompt(self):
|
| 62 |
+
tool_defs, _ = parse_tool_definitions(self.sample_tools)
|
| 63 |
+
prompt = build_tool_system_prompt(tool_defs, tool_choice="auto")
|
| 64 |
+
self.assertIn("## Tools", prompt)
|
| 65 |
+
self.assertIn("get_weather", prompt)
|
| 66 |
+
self.assertIn("```json", prompt)
|
| 67 |
+
|
| 68 |
+
# Required choice
|
| 69 |
+
req_prompt = build_tool_system_prompt(tool_defs, tool_choice="required")
|
| 70 |
+
self.assertIn("REQUIRED to call at least one", req_prompt)
|
| 71 |
+
|
| 72 |
+
# Specific function choice
|
| 73 |
+
fn_prompt = build_tool_system_prompt(tool_defs, tool_choice={"type": "function", "function": {"name": "calculate"}})
|
| 74 |
+
self.assertIn("REQUIRED to call the function 'calculate'", fn_prompt)
|
| 75 |
+
|
| 76 |
+
def test_prepare_messages_for_tools(self):
|
| 77 |
+
messages = [
|
| 78 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 79 |
+
{"role": "user", "content": "What's the weather in Tokyo?"},
|
| 80 |
+
{
|
| 81 |
+
"role": "assistant",
|
| 82 |
+
"content": None,
|
| 83 |
+
"tool_calls": [
|
| 84 |
+
{
|
| 85 |
+
"id": "call_123",
|
| 86 |
+
"type": "function",
|
| 87 |
+
"function": {"name": "get_weather", "arguments": "{\"location\":\"Tokyo\"}"}
|
| 88 |
+
}
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
{"role": "tool", "tool_call_id": "call_123", "name": "get_weather", "content": "{\"temp\": 22}"}
|
| 92 |
+
]
|
| 93 |
+
tool_prompt = "TOOL_PROMPT_MOCK"
|
| 94 |
+
transformed = prepare_messages_for_tools(messages, tool_prompt=tool_prompt)
|
| 95 |
+
self.assertEqual(len(transformed), 5)
|
| 96 |
+
self.assertEqual(transformed[-1]["role"], "system")
|
| 97 |
+
self.assertEqual(transformed[-1]["content"], "TOOL_PROMPT_MOCK")
|
| 98 |
+
|
| 99 |
+
def test_normalize_upstream_messages(self):
|
| 100 |
+
messages = [
|
| 101 |
+
{"role": "system", "content": "You are a coding agent."},
|
| 102 |
+
{"role": "user", "content": "Write a python script."},
|
| 103 |
+
{
|
| 104 |
+
"role": "assistant",
|
| 105 |
+
"content": "",
|
| 106 |
+
"tool_calls": [
|
| 107 |
+
{
|
| 108 |
+
"id": "call_abc",
|
| 109 |
+
"type": "function",
|
| 110 |
+
"function": {"name": "bash", "arguments": "{\"cmd\": \"ls\"}"}
|
| 111 |
+
}
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{"role": "tool", "tool_call_id": "call_abc", "content": "file1.txt\nfile2.txt"},
|
| 115 |
+
{"role": "system", "content": "Additional tool schema"}
|
| 116 |
+
]
|
| 117 |
+
norm = normalize_upstream_messages(messages)
|
| 118 |
+
|
| 119 |
+
# 1. No system role allowed in upstream
|
| 120 |
+
roles = [m["role"] for m in norm]
|
| 121 |
+
self.assertNotIn("system", roles)
|
| 122 |
+
self.assertNotIn("tool", roles)
|
| 123 |
+
|
| 124 |
+
# 2. System prompt prepended to the first user message
|
| 125 |
+
first_user = norm[0]
|
| 126 |
+
self.assertEqual(first_user["role"], "user")
|
| 127 |
+
self.assertIn("[System Instructions]", first_user["content"])
|
| 128 |
+
self.assertIn("You are a coding agent.", first_user["content"])
|
| 129 |
+
self.assertIn("Additional tool schema", first_user["content"])
|
| 130 |
+
self.assertIn("Write a python script.", first_user["content"])
|
| 131 |
+
|
| 132 |
+
# 3. Assistant tool calls formatted as JSON block for consistent in-context learning
|
| 133 |
+
self.assertIn('"name": "bash"', norm[1]["content"])
|
| 134 |
+
|
| 135 |
+
# 4. Tool result flattened to user
|
| 136 |
+
self.assertEqual(norm[2]["role"], "user")
|
| 137 |
+
self.assertIn("[Tool Execution Result for `call_abc`]:", norm[2]["content"])
|
| 138 |
+
|
| 139 |
+
# 5. Last message must be user
|
| 140 |
+
self.assertEqual(norm[-1]["role"], "user")
|
| 141 |
+
|
| 142 |
+
def test_build_upstream_payload_message_id_binding(self):
|
| 143 |
+
messages = [
|
| 144 |
+
{"role": "system", "content": "sys prompt"},
|
| 145 |
+
{"role": "user", "content": "hello"}
|
| 146 |
+
]
|
| 147 |
+
payload = build_upstream_payload(messages, reasoning_effort="high", web_search=True)
|
| 148 |
+
|
| 149 |
+
self.assertEqual(payload["reasoningEffort"], "high")
|
| 150 |
+
self.assertTrue(payload["webSearchEnabled"])
|
| 151 |
+
self.assertEqual(len(payload["messages"]), 1)
|
| 152 |
+
self.assertEqual(payload["messages"][0]["role"], "user")
|
| 153 |
+
|
| 154 |
+
# messageId must strictly equal the id of the last message in messages array
|
| 155 |
+
last_id = payload["messages"][-1]["id"]
|
| 156 |
+
self.assertEqual(payload["messageId"], last_id)
|
| 157 |
+
|
| 158 |
+
def test_extract_tool_calls_markdown(self):
|
| 159 |
+
text = """I will check the weather for you.
|
| 160 |
+
```json
|
| 161 |
+
{
|
| 162 |
+
"name": "get_weather",
|
| 163 |
+
"arguments": {
|
| 164 |
+
"location": "Tokyo"
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
```
|
| 168 |
+
"""
|
| 169 |
+
tool_calls, remaining = extract_tool_calls(text, ["get_weather", "calculate"])
|
| 170 |
+
self.assertIsNotNone(tool_calls)
|
| 171 |
+
self.assertEqual(len(tool_calls), 1)
|
| 172 |
+
self.assertEqual(tool_calls[0]["function"]["name"], "get_weather")
|
| 173 |
+
args = json.loads(tool_calls[0]["function"]["arguments"])
|
| 174 |
+
self.assertEqual(args.get("location"), "Tokyo")
|
| 175 |
+
self.assertEqual(remaining, "I will check the weather for you.")
|
| 176 |
+
|
| 177 |
+
def test_extract_tool_calls_raw_json(self):
|
| 178 |
+
text = '{"name": "calculate", "arguments": {"expr": "12 * 8"}}'
|
| 179 |
+
tool_calls, remaining = extract_tool_calls(text, ["get_weather", "calculate"])
|
| 180 |
+
self.assertIsNotNone(tool_calls)
|
| 181 |
+
self.assertEqual(len(tool_calls), 1)
|
| 182 |
+
self.assertEqual(tool_calls[0]["function"]["name"], "calculate")
|
| 183 |
+
self.assertEqual(remaining, "")
|
| 184 |
+
|
| 185 |
+
def test_extract_tool_calls_multiple(self):
|
| 186 |
+
text = """```json
|
| 187 |
+
[
|
| 188 |
+
{"name": "get_weather", "arguments": {"location": "Beijing"}},
|
| 189 |
+
{"name": "get_weather", "arguments": {"location": "Shanghai"}}
|
| 190 |
+
]
|
| 191 |
+
```"""
|
| 192 |
+
tool_calls, remaining = extract_tool_calls(text, ["get_weather"])
|
| 193 |
+
self.assertIsNotNone(tool_calls)
|
| 194 |
+
self.assertEqual(len(tool_calls), 2)
|
| 195 |
+
self.assertEqual(tool_calls[0]["function"]["name"], "get_weather")
|
| 196 |
+
self.assertEqual(tool_calls[1]["function"]["name"], "get_weather")
|
| 197 |
+
|
| 198 |
+
def test_extract_tool_calls_user_reported_case(self):
|
| 199 |
+
# Exact reproduction of user issue: natural calling text + prefix
|
| 200 |
+
text = """✅ `todo` 正常(#1-#6 已创建)。
|
| 201 |
+
|
| 202 |
+
开始任务 #1,标记为进行中:
|
| 203 |
+
Calling tool `todo` with arguments: {"action":"update","id":1,"status":"in_progress","activeForm":"测试基础工具"}"""
|
| 204 |
+
|
| 205 |
+
tool_calls, remaining = extract_tool_calls(text, ["todo", "bash"])
|
| 206 |
+
self.assertIsNotNone(tool_calls)
|
| 207 |
+
self.assertEqual(len(tool_calls), 1)
|
| 208 |
+
self.assertEqual(tool_calls[0]["function"]["name"], "todo")
|
| 209 |
+
args = json.loads(tool_calls[0]["function"]["arguments"])
|
| 210 |
+
self.assertEqual(args["action"], "update")
|
| 211 |
+
self.assertEqual(args["id"], 1)
|
| 212 |
+
self.assertEqual(args["status"], "in_progress")
|
| 213 |
+
self.assertIn("✅ `todo` 正常", remaining)
|
| 214 |
+
self.assertIn("开始任务 #1,标记为进行中:", remaining)
|
| 215 |
+
|
| 216 |
+
def test_extract_tool_calls_action_format(self):
|
| 217 |
+
text = """Action: bash
|
| 218 |
+
Action Input: {"command": "ls -la"}"""
|
| 219 |
+
tool_calls, remaining = extract_tool_calls(text, ["bash"])
|
| 220 |
+
self.assertIsNotNone(tool_calls)
|
| 221 |
+
self.assertEqual(len(tool_calls), 1)
|
| 222 |
+
self.assertEqual(tool_calls[0]["function"]["name"], "bash")
|
| 223 |
+
args = json.loads(tool_calls[0]["function"]["arguments"])
|
| 224 |
+
self.assertEqual(args["command"], "ls -la")
|
| 225 |
+
|
| 226 |
+
def test_extract_tool_calls_multiple_independent_blocks(self):
|
| 227 |
+
text = """准备查看文件列表:
|
| 228 |
+
```json
|
| 229 |
+
{"name": "bash", "arguments": {"command": "ls"}}
|
| 230 |
+
```
|
| 231 |
+
同时查看当前路径:
|
| 232 |
+
```json
|
| 233 |
+
{"name": "bash", "arguments": {"command": "pwd"}}
|
| 234 |
+
```
|
| 235 |
+
操作准备完毕。"""
|
| 236 |
+
tool_calls, remaining = extract_tool_calls(text, ["bash"])
|
| 237 |
+
self.assertIsNotNone(tool_calls)
|
| 238 |
+
self.assertEqual(len(tool_calls), 2)
|
| 239 |
+
self.assertEqual(json.loads(tool_calls[0]["function"]["arguments"])["command"], "ls")
|
| 240 |
+
self.assertEqual(json.loads(tool_calls[1]["function"]["arguments"])["command"], "pwd")
|
| 241 |
+
self.assertIn("准备查看文件列表:", remaining)
|
| 242 |
+
self.assertIn("同时查看当前路径:", remaining)
|
| 243 |
+
self.assertIn("操作准备完毕。", remaining)
|
| 244 |
+
|
| 245 |
+
def test_compact_tool_definitions(self):
|
| 246 |
+
tools = [
|
| 247 |
+
{
|
| 248 |
+
"type": "function",
|
| 249 |
+
"function": {
|
| 250 |
+
"name": f"tool_{i}",
|
| 251 |
+
"description": "Very long description " * 20,
|
| 252 |
+
"parameters": {
|
| 253 |
+
"type": "object",
|
| 254 |
+
"properties": {
|
| 255 |
+
f"arg_{j}": {"type": "string", "description": "arg desc " * 20}
|
| 256 |
+
for j in range(5)
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
for i in range(70)
|
| 262 |
+
]
|
| 263 |
+
tool_defs, valid_names = parse_tool_definitions(tools)
|
| 264 |
+
prompt = build_tool_system_prompt(tool_defs)
|
| 265 |
+
self.assertLess(len(prompt), 35000)
|
| 266 |
+
|
| 267 |
+
def test_extract_tool_calls_no_match(self):
|
| 268 |
+
text = "Hello! Tokyo is a great city. No tools needed."
|
| 269 |
+
tool_calls, remaining = extract_tool_calls(text, ["get_weather"])
|
| 270 |
+
self.assertIsNone(tool_calls)
|
| 271 |
+
self.assertEqual(remaining, text)
|
| 272 |
+
|
| 273 |
+
def test_extract_tool_calls_unknown_function(self):
|
| 274 |
+
text = '```json\n{"name": "unknown_tool", "arguments": {}}\n```'
|
| 275 |
+
tool_calls, remaining = extract_tool_calls(text, ["get_weather"])
|
| 276 |
+
self.assertIsNone(tool_calls)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class TestChatCompletionEndpointWithTools(unittest.TestCase):
|
| 280 |
+
@patch("app.engine.chat_events")
|
| 281 |
+
def test_chat_completions_non_stream_tool_call(self, mock_chat_events):
|
| 282 |
+
async def fake_events(*args, **kwargs):
|
| 283 |
+
yield ("reasoning", "Thinking about what tool to use...")
|
| 284 |
+
yield ("text", '```json\n{"name": "get_weather", "arguments": {"location": "Paris"}}\n```')
|
| 285 |
+
|
| 286 |
+
mock_chat_events.side_effect = fake_events
|
| 287 |
+
|
| 288 |
+
req_payload = {
|
| 289 |
+
"model": "mercury-3",
|
| 290 |
+
"messages": [{"role": "user", "content": "What is the weather in Paris?"}],
|
| 291 |
+
"tools": [
|
| 292 |
+
{
|
| 293 |
+
"type": "function",
|
| 294 |
+
"function": {
|
| 295 |
+
"name": "get_weather",
|
| 296 |
+
"description": "Get weather",
|
| 297 |
+
"parameters": {"type": "object", "properties": {"location": {"type": "string"}}}
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
],
|
| 301 |
+
"stream": False
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
response = client.post("/v1/chat/completions", json=req_payload)
|
| 305 |
+
self.assertEqual(response.status_code, 200)
|
| 306 |
+
data = response.json()
|
| 307 |
+
choice = data["choices"][0]
|
| 308 |
+
self.assertEqual(choice["finish_reason"], "tool_calls")
|
| 309 |
+
self.assertIn("tool_calls", choice["message"])
|
| 310 |
+
self.assertEqual(choice["message"]["tool_calls"][0]["function"]["name"], "get_weather")
|
| 311 |
+
self.assertIn("reasoning_content", choice["message"])
|
| 312 |
+
self.assertEqual(choice["message"]["reasoning_content"], "Thinking about what tool to use...")
|
| 313 |
+
|
| 314 |
+
@patch("app.engine.chat_events")
|
| 315 |
+
def test_chat_completions_stream_tool_call(self, mock_chat_events):
|
| 316 |
+
async def fake_events(*args, **kwargs):
|
| 317 |
+
yield ("reasoning", "Thinking...")
|
| 318 |
+
yield ("text", '```json\n{"name": "get_weather", "arguments": {"location": "London"}}\n```')
|
| 319 |
+
|
| 320 |
+
mock_chat_events.side_effect = fake_events
|
| 321 |
+
|
| 322 |
+
req_payload = {
|
| 323 |
+
"model": "mercury-3",
|
| 324 |
+
"messages": [{"role": "user", "content": "What is the weather in London?"}],
|
| 325 |
+
"tools": [
|
| 326 |
+
{
|
| 327 |
+
"type": "function",
|
| 328 |
+
"function": {
|
| 329 |
+
"name": "get_weather",
|
| 330 |
+
"description": "Get weather",
|
| 331 |
+
"parameters": {"type": "object", "properties": {"location": {"type": "string"}}}
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
],
|
| 335 |
+
"stream": True
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
response = client.post("/v1/chat/completions", json=req_payload)
|
| 339 |
+
self.assertEqual(response.status_code, 200)
|
| 340 |
+
chunks = []
|
| 341 |
+
for line in response.iter_lines():
|
| 342 |
+
if line.startswith("data: ") and line != "data: [DONE]":
|
| 343 |
+
chunks.append(json.loads(line[6:]))
|
| 344 |
+
|
| 345 |
+
# Verify stream chunk formats
|
| 346 |
+
self.assertTrue(any("reasoning_content" in c["choices"][0]["delta"] for c in chunks))
|
| 347 |
+
tool_call_chunks = [c for c in chunks if "tool_calls" in c["choices"][0]["delta"]]
|
| 348 |
+
self.assertTrue(len(tool_call_chunks) > 0)
|
| 349 |
+
self.assertEqual(tool_call_chunks[0]["choices"][0]["delta"]["tool_calls"][0]["function"]["name"], "get_weather")
|
| 350 |
+
end_chunks = [c for c in chunks if c["choices"][0].get("finish_reason") == "tool_calls"]
|
| 351 |
+
self.assertEqual(len(end_chunks), 1)
|
| 352 |
+
|
| 353 |
+
@patch("app.engine.chat_events")
|
| 354 |
+
def test_chat_completions_normal_chat_without_tools(self, mock_chat_events):
|
| 355 |
+
async def fake_events(*args, **kwargs):
|
| 356 |
+
yield ("text", "Hello there!")
|
| 357 |
+
|
| 358 |
+
mock_chat_events.side_effect = fake_events
|
| 359 |
+
|
| 360 |
+
req_payload = {
|
| 361 |
+
"model": "mercury-3",
|
| 362 |
+
"messages": [{"role": "user", "content": "Hi"}],
|
| 363 |
+
"stream": False
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
response = client.post("/v1/chat/completions", json=req_payload)
|
| 367 |
+
self.assertEqual(response.status_code, 200)
|
| 368 |
+
data = response.json()
|
| 369 |
+
self.assertEqual(data["choices"][0]["finish_reason"], "stop")
|
| 370 |
+
self.assertEqual(data["choices"][0]["message"]["content"], "Hello there!")
|
| 371 |
+
self.assertNotIn("tool_calls", data["choices"][0]["message"])
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
unittest.main()
|