hequ commited on
Commit
456cef9
·
verified ·
1 Parent(s): aabff84

Upload 11 files

Browse files
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ __pycache__
3
+ *.pyc
4
+ .vscode
5
+ .idea
6
+ *.md
7
+ Dockerfile
8
+ docker-compose.yml
9
+ .dockerignore
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ COPY . .
10
+
11
+ EXPOSE 8000
12
+
13
+ ENV PYTHONUNBUFFERED=1 \
14
+ PYTHONIOENCODING=UTF-8 \
15
+ PYTHONDONTWRITEBYTECODE=1 \
16
+ CONFIG_PATH=/app/config.yaml
17
+
18
+ RUN chmod +x /app/docker-entrypoint.sh
19
+
20
+ ENTRYPOINT ["/app/docker-entrypoint.sh"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
config.example.yaml ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Toolify Configuration Example File
2
+ # Please copy this file as config.yaml and modify the configuration according to your actual needs
3
+
4
+ # Server configuration
5
+ server:
6
+ port: 8000 # Server listening port
7
+ host: "0.0.0.0" # Server listening address
8
+ timeout: 180 # Request timeout (seconds)
9
+
10
+ # Upstream OpenAI compatible service configuration
11
+ upstream_services:
12
+ - name: "openai"
13
+ base_url: "https://api.openai.com/v1"
14
+ api_key: "your-openai-api-key-here"
15
+ description: "OpenAI Official Service"
16
+ is_default: true
17
+ models:
18
+ - "gpt-3.5-turbo"
19
+ - "gpt-3.5-turbo-16k"
20
+ - "gpt-4"
21
+ - "gpt-4-turbo"
22
+ - "gpt-4o"
23
+ - "gpt-4o-mini"
24
+
25
+ - name: "google"
26
+ base_url: "https://generativelanguage.googleapis.com/v1beta/openai/"
27
+ api_key: "your-google-api-key-here"
28
+ description: "Google Gemini Service"
29
+ is_default: false
30
+ models:
31
+ # Use alias "gemini-2.5" to randomly select one of the following models
32
+ - "gemini-2.5:gemini-2.5-pro"
33
+ - "gemini-2.5:gemini-2.5-flash"
34
+ # You can also define models that can be used directly
35
+ - "gemini-2.5-pro"
36
+ - "gemini-2.5-flash"
37
+
38
+ # Client authentication configuration
39
+ client_authentication:
40
+ allowed_keys:
41
+ - "sk-my-secret-key-1"
42
+ - "sk-my-secret-key-2"
43
+
44
+ # Feature configuration
45
+ features:
46
+ enable_function_calling: true # Enable function calling feature
47
+ log_level: "INFO" # Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL, or DISABLED
48
+ convert_developer_to_system: true # Whether to convert the developer role to the system role
49
+ key_passthrough: false # If true, directly forward client-provided API key to upstream instead of using configured upstream key
50
+ model_passthrough: false # If true, forward all requests directly to the 'openai' upstream service, ignoring model-based routing
51
+
52
+ # Custom prompt template (optional). If not provided, the default prompt will be used.
53
+ # The default prompt includes comprehensive features:
54
+ # - Support for multiple tool calls in a single response
55
+ # - Context awareness to avoid duplicate tool calls
56
+ # - Strict parameter matching rules (preserving special characters like hyphens)
57
+ # - Clear format requirements with correct and incorrect examples
58
+ # - Tool result tracking via XML tags
59
+ #
60
+ # You can uncomment and customize the following template if needed:
61
+ # prompt_template: |
62
+ # Your custom prompt template here...
63
+ # Must include {tools_list} and {trigger_signal} placeholders
64
+
65
+ # Configuration explanation:
66
+ # 1. upstream_services: Configure multiple OpenAI compatible API services
67
+ # - name: Service name (for identification)
68
+ # - base_url: Base URL of the service
69
+ # - api_key: API key for the corresponding service
70
+ # - models: Complete list of models supported by the service
71
+ # - is_default: Whether it is the default service (used when the requested model is not in any service's model list)
72
+ # - description: Service description (optional)
73
+ #
74
+ # 2. Routing matching rules:
75
+ # - The system will exactly match the corresponding service based on the model name in the request
76
+ # - If the model name is not in the models list of any service, the service with is_default set to true will be used
77
+ # - There must be one and only one service marked as is_default: true
78
+ #
79
+ # 3. Client authentication:
80
+ # - allowed_keys: List of client API keys allowed to access this middleware
81
+ #
82
+ # 4. Logging levels:
83
+ # - DEBUG: Show all debug information (most verbose)
84
+ # - INFO: Show general information, warnings and errors
85
+ # - WARNING: Show only warnings and errors
86
+ # - ERROR: Show only errors
87
+ # - CRITICAL: Show only critical errors
88
+ # - DISABLED: Disable all logging
89
+ #
90
+ # 5. Security reminders:
91
+ # - Please keep API keys safe and do not commit configuration files containing real keys to version control systems
92
+ # - It is recommended to use different configuration files for different environments
93
+ # - Environment variables can be used to manage sensitive information
config_loader.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ #
3
+ # Toolify: Empower any LLM with function calling capabilities.
4
+ # Copyright (C) 2025 FunnyCups (https://github.com/funnycups)
5
+
6
+ import os
7
+ import yaml
8
+ from typing import List, Dict, Any, Set, Optional
9
+ from pydantic import BaseModel, Field, field_validator
10
+
11
+
12
+ class ServerConfig(BaseModel):
13
+ """Server configuration"""
14
+ port: int = Field(default=8000, ge=1, le=65535, description="Server port")
15
+ host: str = Field(default="0.0.0.0", description="Server host address")
16
+ timeout: int = Field(default=180, ge=1, description="Request timeout (seconds)")
17
+
18
+
19
+ class UpstreamService(BaseModel):
20
+ """Upstream service configuration"""
21
+ name: str = Field(description="Service name")
22
+ base_url: str = Field(description="Service base URL")
23
+ api_key: str = Field(description="API key")
24
+ models: List[str] = Field(description="List of supported models")
25
+ description: str = Field(default="", description="Service description")
26
+ is_default: bool = Field(default=False, description="Is default service")
27
+
28
+ @field_validator('base_url')
29
+ def validate_base_url(cls, v):
30
+ if not v.startswith(('http://', 'https://')):
31
+ raise ValueError('base_url must start with http:// or https://')
32
+ return v.rstrip('/')
33
+
34
+ @field_validator('api_key')
35
+ def validate_api_key(cls, v):
36
+ if not v or v.strip() == "":
37
+ raise ValueError('api_key cannot be empty')
38
+ return v
39
+
40
+ @field_validator('models')
41
+ def validate_models(cls, v):
42
+ if not v or len(v) == 0:
43
+ raise ValueError('models list cannot be empty')
44
+ for model in v:
45
+ if not model or model.strip() == "":
46
+ raise ValueError('model name cannot be empty')
47
+ return v
48
+
49
+
50
+ class ClientAuthConfig(BaseModel):
51
+ """Client authentication configuration"""
52
+ allowed_keys: List[str] = Field(description="List of allowed client API keys")
53
+
54
+ @field_validator('allowed_keys')
55
+ def validate_allowed_keys(cls, v):
56
+ if not v or len(v) == 0:
57
+ raise ValueError('allowed_keys cannot be empty')
58
+ for key in v:
59
+ if not key or key.strip() == "":
60
+ raise ValueError('API key cannot be empty')
61
+ return v
62
+
63
+
64
+ class FeaturesConfig(BaseModel):
65
+ """Feature configuration"""
66
+ enable_function_calling: bool = Field(default=True, description="Enable function calling")
67
+ log_level: str = Field(default="INFO", description="Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL, or DISABLED")
68
+ convert_developer_to_system: bool = Field(default=True, description="Convert developer role to system role")
69
+ prompt_template: Optional[str] = Field(default=None, description="Custom prompt template for function calling")
70
+ key_passthrough: bool = Field(default=False, description="If true, directly forward client-provided API key to upstream instead of using configured upstream key")
71
+ model_passthrough: bool = Field(default=False, description="If true, forward all requests directly to the 'openai' upstream service, ignoring model-based routing")
72
+
73
+ @field_validator('log_level')
74
+ def validate_log_level(cls, v):
75
+ valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL", "DISABLED"]
76
+ if v.upper() not in valid_levels:
77
+ raise ValueError(f"log_level must be one of {valid_levels}")
78
+ return v.upper()
79
+
80
+ @field_validator('prompt_template')
81
+ def validate_prompt_template(cls, v):
82
+ if v:
83
+ if "{tools_list}" not in v or "{trigger_signal}" not in v:
84
+ raise ValueError("prompt_template must contain {tools_list} and {trigger_signal} placeholders")
85
+ return v
86
+
87
+
88
+ class AppConfig(BaseModel):
89
+ """Application full configuration"""
90
+ server: ServerConfig = Field(default_factory=ServerConfig)
91
+ upstream_services: List[UpstreamService] = Field(description="List of upstream services")
92
+ client_authentication: ClientAuthConfig = Field(description="Client authentication configuration")
93
+ features: FeaturesConfig = Field(default_factory=FeaturesConfig)
94
+
95
+ @field_validator('upstream_services')
96
+ def validate_upstream_services(cls, v):
97
+ if not v or len(v) == 0:
98
+ raise ValueError('upstream_services cannot be empty')
99
+
100
+ default_services = [service for service in v if service.is_default]
101
+ if len(default_services) == 0:
102
+ raise ValueError('Must have at least one default upstream service (is_default: true)')
103
+ if len(default_services) > 1:
104
+ raise ValueError('Only one upstream service can be marked as default')
105
+
106
+ all_models = set()
107
+ all_aliases = set()
108
+
109
+ for service in v:
110
+ for model in service.models:
111
+ if model in all_models:
112
+ raise ValueError(f'Duplicate model entry found: {model}')
113
+ all_models.add(model)
114
+
115
+ if ':' in model:
116
+ parts = model.split(':', 1)
117
+ if len(parts) == 2:
118
+ alias, real_model = parts
119
+ if not alias.strip() or not real_model.strip():
120
+ raise ValueError(f"Invalid alias format in '{model}'. Both parts must not be empty.")
121
+ all_aliases.add(alias)
122
+ else:
123
+ raise ValueError(f"Invalid model format with colon: {model}")
124
+
125
+ regular_models = {m for m in all_models if ':' not in m}
126
+ conflicts = all_aliases.intersection(regular_models)
127
+ if conflicts:
128
+ raise ValueError(f"Alias names {conflicts} conflict with model names.")
129
+
130
+ return v
131
+
132
+
133
+ class ConfigLoader:
134
+ """Configuration loader"""
135
+
136
+ def __init__(self, config_path: str = "config.yaml"):
137
+ self.config_path = config_path
138
+ self._config: AppConfig = None
139
+
140
+ def load_config(self) -> AppConfig:
141
+ """Load configuration file"""
142
+ if not os.path.exists(self.config_path):
143
+ raise FileNotFoundError(
144
+ f"Configuration file '{self.config_path}' not found. "
145
+ f"Please copy 'config.example.yaml' to '{self.config_path}' and modify the configuration as needed."
146
+ )
147
+
148
+ try:
149
+ with open(self.config_path, 'r', encoding='utf-8') as f:
150
+ config_data = yaml.safe_load(f)
151
+ except yaml.YAMLError as e:
152
+ raise ValueError(f"Configuration file format error: {e}")
153
+ except Exception as e:
154
+ raise ValueError(f"Failed to read configuration file: {e}")
155
+
156
+ if not config_data:
157
+ raise ValueError("Configuration file is empty")
158
+
159
+ try:
160
+ self._config = AppConfig(**config_data)
161
+ return self._config
162
+ except Exception as e:
163
+ raise ValueError(f"Configuration validation failed: {e}")
164
+
165
+ @property
166
+ def config(self) -> AppConfig:
167
+ """Get configuration object"""
168
+ if self._config is None:
169
+ self.load_config()
170
+ return self._config
171
+
172
+ def get_model_to_service_mapping(self) -> tuple[Dict[str, Dict[str, Any]], Dict[str, List[str]]]:
173
+ """Get model to service mapping and model aliases"""
174
+ config = self.config
175
+ model_mapping = {}
176
+ alias_mapping = {}
177
+
178
+ for service in config.upstream_services:
179
+ service_info = {
180
+ "name": service.name,
181
+ "base_url": service.base_url,
182
+ "api_key": service.api_key,
183
+ "description": service.description,
184
+ "is_default": service.is_default
185
+ }
186
+
187
+ for model_entry in service.models:
188
+ model_mapping[model_entry] = service_info
189
+ if ':' in model_entry:
190
+ parts = model_entry.split(':', 1)
191
+ if len(parts) == 2:
192
+ alias, _ = parts
193
+ if alias not in alias_mapping:
194
+ alias_mapping[alias] = []
195
+ alias_mapping[alias].append(model_entry)
196
+
197
+ return model_mapping, alias_mapping
198
+
199
+ def get_default_service(self) -> Dict[str, Any]:
200
+ """Get default service configuration"""
201
+ config = self.config
202
+ for service in config.upstream_services:
203
+ if service.is_default:
204
+ return {
205
+ "name": service.name,
206
+ "base_url": service.base_url,
207
+ "api_key": service.api_key,
208
+ "description": service.description,
209
+ "is_default": service.is_default
210
+ }
211
+ raise ValueError("No default service configured")
212
+
213
+ def get_allowed_client_keys(self) -> Set[str]:
214
+ """Get set of allowed client keys"""
215
+ return set(self.config.client_authentication.allowed_keys)
216
+
217
+ def get_log_level(self) -> str:
218
+ """Get configured log level"""
219
+ return self.config.features.log_level
220
+
221
+ def get_features_config(self) -> Dict[str, Any]:
222
+ """Get feature configuration"""
223
+ return {
224
+ "function_calling": self.config.features.enable_function_calling,
225
+ "log_level": self.config.features.log_level,
226
+ "convert_developer_to_system": self.config.features.convert_developer_to_system
227
+ }
228
+
229
+
230
+ config_loader = ConfigLoader()
docker-compose.yml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ toolify:
5
+ image: toolify
6
+ build:
7
+ context: .
8
+ dockerfile: Dockerfile
9
+ container_name: toolify
10
+ ports:
11
+ - "8000:8000"
12
+ volumes:
13
+ - ./config.yaml:/app/config.yaml
14
+ restart: unless-stopped
docker-entrypoint.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -e
3
+
4
+ # 如果缺少配置文件且允许自动生成,则触发脚本生成
5
+ PORT="${PORT:-8000}"
6
+ CONFIG_PATH="${CONFIG_PATH:-/app/config.yaml}"
7
+ GENERATE_CONFIG="${GENERATE_CONFIG:-0}"
8
+
9
+ if [ ! -f "$CONFIG_PATH" ]; then
10
+ if [ "$GENERATE_CONFIG" != "0" ]; then
11
+ echo "正在基于环境变量生成配置文件..."
12
+ python -m scripts.generate_config
13
+ else
14
+ echo "警告: 未找到配置文件 $CONFIG_PATH,且未启用自动生成。" >&2
15
+ fi
16
+ fi
17
+
18
+ exec uvicorn main:app --host 0.0.0.0 --port "$PORT"
main.py ADDED
@@ -0,0 +1,1360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ #
3
+ # Toolify: Empower any LLM with function calling capabilities.
4
+ # Copyright (C) 2025 FunnyCups (https://github.com/funnycups)
5
+
6
+ import os
7
+ import re
8
+ import json
9
+ import uuid
10
+ import httpx
11
+ import secrets
12
+ import string
13
+ import traceback
14
+ import time
15
+ import random
16
+ import threading
17
+ import logging
18
+ from typing import List, Dict, Any, Optional, Literal, Union
19
+ from collections import OrderedDict
20
+
21
+ from fastapi import FastAPI, Request, Header, HTTPException, Depends
22
+ from fastapi.responses import JSONResponse, StreamingResponse
23
+ from pydantic import BaseModel, ValidationError
24
+
25
+ from config_loader import config_loader
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ def generate_random_trigger_signal() -> str:
30
+ """Generate a random, self-closing trigger signal like <Function_AB1c_Start/>."""
31
+ chars = string.ascii_letters + string.digits
32
+ random_str = ''.join(secrets.choice(chars) for _ in range(4))
33
+ return f"<Function_{random_str}_Start/>"
34
+
35
+ try:
36
+ app_config = config_loader.load_config()
37
+
38
+ log_level_str = app_config.features.log_level
39
+ if log_level_str == "DISABLED":
40
+ log_level = logging.CRITICAL + 1
41
+ else:
42
+ log_level = getattr(logging, log_level_str, logging.INFO)
43
+
44
+ logging.basicConfig(
45
+ level=log_level,
46
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
47
+ datefmt='%Y-%m-%d %H:%M:%S'
48
+ )
49
+
50
+ logger.info(f"✅ Configuration loaded successfully: {config_loader.config_path}")
51
+ logger.info(f"📊 Configured {len(app_config.upstream_services)} upstream services")
52
+ logger.info(f"🔑 Configured {len(app_config.client_authentication.allowed_keys)} client keys")
53
+
54
+ MODEL_TO_SERVICE_MAPPING, ALIAS_MAPPING = config_loader.get_model_to_service_mapping()
55
+ DEFAULT_SERVICE = config_loader.get_default_service()
56
+ ALLOWED_CLIENT_KEYS = config_loader.get_allowed_client_keys()
57
+ GLOBAL_TRIGGER_SIGNAL = generate_random_trigger_signal()
58
+
59
+ logger.info(f"🎯 Configured {len(MODEL_TO_SERVICE_MAPPING)} model mappings")
60
+ if ALIAS_MAPPING:
61
+ logger.info(f"🔄 Configured {len(ALIAS_MAPPING)} model aliases: {list(ALIAS_MAPPING.keys())}")
62
+ logger.info(f"🔄 Default service: {DEFAULT_SERVICE['name']}")
63
+
64
+ except Exception as e:
65
+ logger.error(f"❌ Configuration loading failed: {type(e).__name__}")
66
+ logger.error(f"❌ Error details: {str(e)}")
67
+ logger.error("💡 Please ensure config.yaml file exists and is properly formatted")
68
+ exit(1)
69
+ class ToolCallMappingManager:
70
+ """
71
+ Tool call mapping manager with TTL (Time To Live) and size limit
72
+
73
+ Features:
74
+ 1. Automatic expiration cleanup - entries are automatically deleted after specified time
75
+ 2. Size limit - prevents unlimited memory growth
76
+ 3. LRU eviction - removes least recently used entries when size limit is reached
77
+ 4. Thread safe - supports concurrent access
78
+ 5. Periodic cleanup - background thread regularly cleans up expired entries
79
+ """
80
+
81
+ def __init__(self, max_size: int = 1000, ttl_seconds: int = 3600, cleanup_interval: int = 300):
82
+ """
83
+ Initialize mapping manager
84
+
85
+ Args:
86
+ max_size: Maximum number of stored entries
87
+ ttl_seconds: Entry time to live (seconds)
88
+ cleanup_interval: Cleanup interval (seconds)
89
+ """
90
+ self.max_size = max_size
91
+ self.ttl_seconds = ttl_seconds
92
+ self.cleanup_interval = cleanup_interval
93
+
94
+ self._data: OrderedDict[str, Dict[str, Any]] = OrderedDict()
95
+ self._timestamps: Dict[str, float] = {}
96
+ self._lock = threading.RLock()
97
+
98
+ self._cleanup_thread = threading.Thread(target=self._periodic_cleanup, daemon=True)
99
+ self._cleanup_thread.start()
100
+
101
+ logger.debug(f"🔧 [INIT] Tool call mapping manager started - Max entries: {max_size}, TTL: {ttl_seconds}s, Cleanup interval: {cleanup_interval}s")
102
+
103
+ def store(self, tool_call_id: str, name: str, args: dict, description: str = "") -> None:
104
+ """Store tool call mapping"""
105
+ with self._lock:
106
+ current_time = time.time()
107
+
108
+ if tool_call_id in self._data:
109
+ del self._data[tool_call_id]
110
+ del self._timestamps[tool_call_id]
111
+
112
+ while len(self._data) >= self.max_size:
113
+ oldest_key = next(iter(self._data))
114
+ del self._data[oldest_key]
115
+ del self._timestamps[oldest_key]
116
+ logger.debug(f"🔧 [CLEANUP] Removed oldest entry due to size limit: {oldest_key}")
117
+
118
+ self._data[tool_call_id] = {
119
+ "name": name,
120
+ "args": args,
121
+ "description": description,
122
+ "created_at": current_time
123
+ }
124
+ self._timestamps[tool_call_id] = current_time
125
+
126
+ logger.debug(f"🔧 Stored tool call mapping: {tool_call_id} -> {name}")
127
+ logger.debug(f"🔧 Current mapping table size: {len(self._data)}")
128
+
129
+ def get(self, tool_call_id: str) -> Optional[Dict[str, Any]]:
130
+ """Get tool call mapping (updates LRU order)"""
131
+ with self._lock:
132
+ current_time = time.time()
133
+
134
+ if tool_call_id not in self._data:
135
+ logger.debug(f"🔧 Tool call mapping not found: {tool_call_id}")
136
+ logger.debug(f"🔧 All IDs in current mapping table: {list(self._data.keys())}")
137
+ return None
138
+
139
+ if current_time - self._timestamps[tool_call_id] > self.ttl_seconds:
140
+ logger.debug(f"🔧 Tool call mapping expired: {tool_call_id}")
141
+ del self._data[tool_call_id]
142
+ del self._timestamps[tool_call_id]
143
+ return None
144
+
145
+ result = self._data[tool_call_id]
146
+ self._data.move_to_end(tool_call_id)
147
+
148
+ logger.debug(f"🔧 Found tool call mapping: {tool_call_id} -> {result['name']}")
149
+ return result
150
+
151
+ def cleanup_expired(self) -> int:
152
+ """Clean up expired entries, return the number of cleaned entries"""
153
+ with self._lock:
154
+ current_time = time.time()
155
+ expired_keys = []
156
+
157
+ for key, timestamp in self._timestamps.items():
158
+ if current_time - timestamp > self.ttl_seconds:
159
+ expired_keys.append(key)
160
+
161
+ for key in expired_keys:
162
+ del self._data[key]
163
+ del self._timestamps[key]
164
+
165
+ if expired_keys:
166
+ logger.debug(f"🔧 [CLEANUP] Cleaned up {len(expired_keys)} expired entries")
167
+
168
+ return len(expired_keys)
169
+
170
+ def get_stats(self) -> Dict[str, Any]:
171
+ """Get statistics"""
172
+ with self._lock:
173
+ current_time = time.time()
174
+ expired_count = sum(1 for ts in self._timestamps.values()
175
+ if current_time - ts > self.ttl_seconds)
176
+
177
+ return {
178
+ "total_entries": len(self._data),
179
+ "expired_entries": expired_count,
180
+ "active_entries": len(self._data) - expired_count,
181
+ "max_size": self.max_size,
182
+ "ttl_seconds": self.ttl_seconds,
183
+ "memory_usage_ratio": len(self._data) / self.max_size
184
+ }
185
+
186
+ def _periodic_cleanup(self) -> None:
187
+ """Background periodic cleanup thread"""
188
+ while True:
189
+ try:
190
+ time.sleep(self.cleanup_interval)
191
+ cleaned = self.cleanup_expired()
192
+
193
+ stats = self.get_stats()
194
+ if stats["total_entries"] > 0:
195
+ logger.debug(f"🔧 [STATS] Mapping table status: Total={stats['total_entries']}, "
196
+ f"Active={stats['active_entries']}, Memory usage={stats['memory_usage_ratio']:.1%}")
197
+
198
+ except Exception as e:
199
+ logger.error(f"❌ Background cleanup thread exception: {e}")
200
+
201
+ TOOL_CALL_MAPPING_MANAGER = ToolCallMappingManager(
202
+ max_size=1000,
203
+ ttl_seconds=3600,
204
+ cleanup_interval=300
205
+ )
206
+
207
+ def store_tool_call_mapping(tool_call_id: str, name: str, args: dict, description: str = ""):
208
+ """Store mapping between tool call ID and call content"""
209
+ TOOL_CALL_MAPPING_MANAGER.store(tool_call_id, name, args, description)
210
+
211
+ def get_tool_call_mapping(tool_call_id: str) -> Optional[Dict[str, Any]]:
212
+ """Get call content corresponding to tool call ID"""
213
+ return TOOL_CALL_MAPPING_MANAGER.get(tool_call_id)
214
+
215
+ def format_tool_result_for_ai(tool_call_id: str, result_content: str) -> str:
216
+ """Format tool call results for AI understanding with English prompts and XML structure"""
217
+ logger.debug(f"🔧 Formatting tool call result: tool_call_id={tool_call_id}")
218
+ tool_info = get_tool_call_mapping(tool_call_id)
219
+ if not tool_info:
220
+ logger.debug(f"🔧 Tool call mapping not found, using default format")
221
+ return f"Tool execution result:\n<tool_result>\n{result_content}\n</tool_result>"
222
+
223
+ formatted_text = f"""Tool execution result:
224
+ - Tool name: {tool_info['name']}
225
+ - Execution result:
226
+ <tool_result>
227
+ {result_content}
228
+ </tool_result>"""
229
+
230
+ logger.debug(f"🔧 Formatting completed, tool name: {tool_info['name']}")
231
+ return formatted_text
232
+
233
+ def format_assistant_tool_calls_for_ai(tool_calls: List[Dict[str, Any]], trigger_signal: str) -> str:
234
+ """Format assistant tool calls into AI-readable string format."""
235
+ logger.debug(f"🔧 Formatting assistant tool calls. Count: {len(tool_calls)}")
236
+
237
+ xml_calls_parts = []
238
+ for tool_call in tool_calls:
239
+ function_info = tool_call.get("function", {})
240
+ name = function_info.get("name", "")
241
+ arguments_json = function_info.get("arguments", "{}")
242
+
243
+ try:
244
+ # First, try to load as JSON. If it's a string that's a valid JSON, we parse it.
245
+ args_dict = json.loads(arguments_json)
246
+ except (json.JSONDecodeError, TypeError):
247
+ # If it's not a valid JSON string, treat it as a simple string.
248
+ args_dict = {"raw_arguments": arguments_json}
249
+
250
+ args_parts = []
251
+ for key, value in args_dict.items():
252
+ # Dump the value back to a JSON string for consistent representation inside XML.
253
+ json_value = json.dumps(value, ensure_ascii=False)
254
+ args_parts.append(f"<{key}>{json_value}</{key}>")
255
+
256
+ args_content = "\n".join(args_parts)
257
+
258
+ xml_call = f"<function_call>\n<tool>{name}</tool>\n<args>\n{args_content}\n</args>\n</function_call>"
259
+ xml_calls_parts.append(xml_call)
260
+
261
+ all_calls = "\n".join(xml_calls_parts)
262
+ final_str = f"{trigger_signal}\n<function_calls>\n{all_calls}\n</function_calls>"
263
+
264
+ logger.debug("🔧 Assistant tool calls formatted successfully.")
265
+ return final_str
266
+
267
+ def get_function_call_prompt_template(trigger_signal: str) -> str:
268
+ """
269
+ Generate prompt template based on dynamic trigger signal
270
+ """
271
+ custom_template = app_config.features.prompt_template
272
+ if custom_template:
273
+ logger.info("🔧 Using custom prompt template from configuration")
274
+ return custom_template.format(
275
+ trigger_signal=trigger_signal,
276
+ tools_list="{tools_list}"
277
+ )
278
+
279
+ return f"""
280
+ You have access to the following available tools to help solve problems:
281
+
282
+ {{tools_list}}
283
+
284
+ **IMPORTANT CONTEXT NOTES:**
285
+ 1. You can call MULTIPLE tools in a single response if needed.
286
+ 2. The conversation context may already contain tool execution results from previous function calls. Review the conversation history carefully to avoid unnecessary duplicate tool calls.
287
+ 3. When tool execution results are present in the context, they will be formatted with XML tags like <tool_result>...</tool_result> for easy identification.
288
+ 4. This is the ONLY format you can use for tool calls, and any deviation will result in failure.
289
+
290
+ When you need to use tools, you **MUST** strictly follow this format. Do NOT include any extra text, explanations, or dialogue on the first and second lines of the tool call syntax:
291
+
292
+ 1. When starting tool calls, begin on a new line with exactly:
293
+ {trigger_signal}
294
+ No leading or trailing spaces, output exactly as shown above. The trigger signal MUST be on its own line and appear only once.
295
+
296
+ 2. Starting from the second line, **immediately** follow with the complete <function_calls> XML block.
297
+
298
+ 3. For multiple tool calls, include multiple <function_call> blocks within the same <function_calls> wrapper.
299
+
300
+ 4. Do not add any text or explanation after the closing </function_calls> tag.
301
+
302
+ STRICT ARGUMENT KEY RULES:
303
+ - You MUST use parameter keys EXACTLY as defined (case- and punctuation-sensitive). Do NOT rename, add, or remove characters.
304
+ - If a key starts with a hyphen (e.g., -i, -C), you MUST keep the hyphen in the tag name. Example: <-i>true</-i>, <-C>2</-C>.
305
+ - Never convert "-i" to "i" or "-C" to "C". Do not pluralize, translate, or alias parameter keys.
306
+ - The <tool> tag must contain the exact name of a tool from the list. Any other tool name is invalid.
307
+ - The <args> must contain all required arguments for that tool.
308
+
309
+ CORRECT Example (multiple tool calls, including hyphenated keys):
310
+ ...response content (optional)...
311
+ {trigger_signal}
312
+ <function_calls>
313
+ <function_call>
314
+ <tool>Grep</tool>
315
+ <args>
316
+ <-i>true</-i>
317
+ <-C>2</-C>
318
+ <path>.</path>
319
+ </args>
320
+ </function_call>
321
+ <function_call>
322
+ <tool>search</tool>
323
+ <args>
324
+ <keywords>["Python Document", "how to use python"]</keywords>
325
+ </args>
326
+ </function_call>
327
+ </function_calls>
328
+
329
+ INCORRECT Example (extra text + wrong key names — DO NOT DO THIS):
330
+ ...response content (optional)...
331
+ {trigger_signal}
332
+ I will call the tools for you.
333
+ <function_calls>
334
+ <function_call>
335
+ <tool>Grep</tool>
336
+ <args>
337
+ <i>true</i>
338
+ <C>2</C>
339
+ <path>.</path>
340
+ </args>
341
+ </function_call>
342
+ </function_calls>
343
+
344
+ Now please be ready to strictly follow the above specifications.
345
+ """
346
+
347
+ class ToolFunction(BaseModel):
348
+ name: str
349
+ description: Optional[str] = None
350
+ parameters: Dict[str, Any]
351
+
352
+ class Tool(BaseModel):
353
+ type: Literal["function"]
354
+ function: ToolFunction
355
+
356
+ class Message(BaseModel):
357
+ role: str
358
+ content: Optional[str] = None
359
+ tool_calls: Optional[List[Dict[str, Any]]] = None
360
+ tool_call_id: Optional[str] = None
361
+ name: Optional[str] = None
362
+
363
+ class Config:
364
+ extra = "allow"
365
+
366
+ class ToolChoice(BaseModel):
367
+ type: Literal["function"]
368
+ function: Dict[str, str]
369
+
370
+ class ChatCompletionRequest(BaseModel):
371
+ model: str
372
+ messages: List[Dict[str, Any]]
373
+ tools: Optional[List[Tool]] = None
374
+ tool_choice: Optional[Union[str, ToolChoice]] = None
375
+ stream: Optional[bool] = False
376
+ stream_options: Optional[Dict[str, Any]] = None
377
+ temperature: Optional[float] = None
378
+ max_tokens: Optional[int] = None
379
+ top_p: Optional[float] = None
380
+ frequency_penalty: Optional[float] = None
381
+ presence_penalty: Optional[float] = None
382
+ n: Optional[int] = None
383
+ stop: Optional[Union[str, List[str]]] = None
384
+
385
+ class Config:
386
+ extra = "allow"
387
+
388
+
389
+ def generate_function_prompt(tools: List[Tool], trigger_signal: str) -> tuple[str, str]:
390
+ """
391
+ Generate injected system prompt based on tools definition in client request.
392
+ Returns: (prompt_content, trigger_signal)
393
+ """
394
+ tools_list_str = []
395
+ for i, tool in enumerate(tools):
396
+ func = tool.function
397
+ name = func.name
398
+ description = func.description or ""
399
+
400
+ # Robustly read JSON Schema fields
401
+ schema: Dict[str, Any] = func.parameters or {}
402
+ props: Dict[str, Any] = schema.get("properties", {}) or {}
403
+ required_list: List[str] = schema.get("required", []) or []
404
+
405
+ # Brief summary line: name (type)
406
+ params_summary = ", ".join([
407
+ f"{p_name} ({(p_info or {}).get('type', 'any')})" for p_name, p_info in props.items()
408
+ ]) or "None"
409
+
410
+ # Build detailed parameter spec for prompt injection (default enabled)
411
+ detail_lines: List[str] = []
412
+ for p_name, p_info in props.items():
413
+ p_info = p_info or {}
414
+ p_type = p_info.get("type", "any")
415
+ is_required = "Yes" if p_name in required_list else "No"
416
+ p_desc = p_info.get("description")
417
+ enum_vals = p_info.get("enum")
418
+ default_val = p_info.get("default")
419
+ examples_val = p_info.get("examples") or p_info.get("example")
420
+
421
+ # Common constraints and hints
422
+ constraints: Dict[str, Any] = {}
423
+ for key in [
424
+ "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum",
425
+ "minLength", "maxLength", "pattern", "format",
426
+ "minItems", "maxItems", "uniqueItems"
427
+ ]:
428
+ if key in p_info:
429
+ constraints[key] = p_info.get(key)
430
+
431
+ # Array item type hint
432
+ if p_type == "array":
433
+ items = p_info.get("items") or {}
434
+ if isinstance(items, dict):
435
+ itype = items.get("type")
436
+ if itype:
437
+ constraints["items.type"] = itype
438
+
439
+ # Compose pretty lines
440
+ detail_lines.append(f"- {p_name}:")
441
+ detail_lines.append(f" - type: {p_type}")
442
+ detail_lines.append(f" - required: {is_required}")
443
+ if p_desc:
444
+ detail_lines.append(f" - description: {p_desc}")
445
+ if enum_vals is not None:
446
+ try:
447
+ detail_lines.append(f" - enum: {json.dumps(enum_vals, ensure_ascii=False)}")
448
+ except Exception:
449
+ detail_lines.append(f" - enum: {enum_vals}")
450
+ if default_val is not None:
451
+ try:
452
+ detail_lines.append(f" - default: {json.dumps(default_val, ensure_ascii=False)}")
453
+ except Exception:
454
+ detail_lines.append(f" - default: {default_val}")
455
+ if examples_val is not None:
456
+ try:
457
+ detail_lines.append(f" - examples: {json.dumps(examples_val, ensure_ascii=False)}")
458
+ except Exception:
459
+ detail_lines.append(f" - examples: {examples_val}")
460
+ if constraints:
461
+ try:
462
+ detail_lines.append(f" - constraints: {json.dumps(constraints, ensure_ascii=False)}")
463
+ except Exception:
464
+ detail_lines.append(f" - constraints: {constraints}")
465
+
466
+ detail_block = "\n".join(detail_lines) if detail_lines else "(no parameter details)"
467
+
468
+ desc_block = f"```\n{description}\n```" if description else "None"
469
+
470
+ tools_list_str.append(
471
+ f"{i + 1}. <tool name=\"{name}\">\n"
472
+ f" Description:\n{desc_block}\n"
473
+ f" Parameters summary: {params_summary}\n"
474
+ f" Required parameters: {', '.join(required_list) if required_list else 'None'}\n"
475
+ f" Parameter details:\n{detail_block}"
476
+ )
477
+
478
+ prompt_template = get_function_call_prompt_template(trigger_signal)
479
+ prompt_content = prompt_template.replace("{tools_list}", "\n\n".join(tools_list_str))
480
+
481
+ return prompt_content, trigger_signal
482
+
483
+ def remove_think_blocks(text: str) -> str:
484
+ """
485
+ Temporarily remove all <think>...</think> blocks for XML parsing
486
+ Supports nested think tags
487
+ Note: This function is only used for temporary parsing and does not affect the original content returned to the user
488
+ """
489
+ while '<think>' in text and '</think>' in text:
490
+ start_pos = text.find('<think>')
491
+ if start_pos == -1:
492
+ break
493
+
494
+ pos = start_pos + 7
495
+ depth = 1
496
+
497
+ while pos < len(text) and depth > 0:
498
+ if text[pos:pos+7] == '<think>':
499
+ depth += 1
500
+ pos += 7
501
+ elif text[pos:pos+8] == '</think>':
502
+ depth -= 1
503
+ pos += 8
504
+ else:
505
+ pos += 1
506
+
507
+ if depth == 0:
508
+ text = text[:start_pos] + text[pos:]
509
+ else:
510
+ break
511
+
512
+ return text
513
+
514
+ class StreamingFunctionCallDetector:
515
+ """Enhanced streaming function call detector, supports dynamic trigger signals, avoids misjudgment within <think> tags
516
+
517
+ Core features:
518
+ 1. Avoid triggering tool call detection within <think> blocks
519
+ 2. Normally output <think> block content to the user
520
+ 3. Supports nested think tags
521
+ """
522
+
523
+ def __init__(self, trigger_signal: str):
524
+ self.trigger_signal = trigger_signal
525
+ self.reset()
526
+
527
+ def reset(self):
528
+ self.content_buffer = ""
529
+ self.state = "detecting" # detecting, tool_parsing
530
+ self.in_think_block = False
531
+ self.think_depth = 0
532
+ self.signal = self.trigger_signal
533
+ self.signal_len = len(self.signal)
534
+
535
+ def process_chunk(self, delta_content: str) -> tuple[bool, str]:
536
+ """
537
+ Process streaming content chunk
538
+ Returns: (is_tool_call_detected, content_to_yield)
539
+ """
540
+ if not delta_content:
541
+ return False, ""
542
+
543
+ self.content_buffer += delta_content
544
+ content_to_yield = ""
545
+
546
+ if self.state == "tool_parsing":
547
+ return False, ""
548
+
549
+ if delta_content:
550
+ logger.debug(f"🔧 Processing chunk: {repr(delta_content[:50])}{'...' if len(delta_content) > 50 else ''}, buffer length: {len(self.content_buffer)}, think state: {self.in_think_block}")
551
+
552
+ i = 0
553
+ while i < len(self.content_buffer):
554
+ skip_chars = self._update_think_state(i)
555
+ if skip_chars > 0:
556
+ for j in range(skip_chars):
557
+ if i + j < len(self.content_buffer):
558
+ content_to_yield += self.content_buffer[i + j]
559
+ i += skip_chars
560
+ continue
561
+
562
+ if not self.in_think_block and self._can_detect_signal_at(i):
563
+ if self.content_buffer[i:i+self.signal_len] == self.signal:
564
+ logger.debug(f"🔧 Improved detector: detected trigger signal in non-think block! Signal: {self.signal[:20]}...")
565
+ logger.debug(f"🔧 Trigger signal position: {i}, think state: {self.in_think_block}, think depth: {self.think_depth}")
566
+ self.state = "tool_parsing"
567
+ self.content_buffer = self.content_buffer[i:]
568
+ return True, content_to_yield
569
+
570
+ remaining_len = len(self.content_buffer) - i
571
+ if remaining_len < self.signal_len or remaining_len < 8:
572
+ break
573
+
574
+ content_to_yield += self.content_buffer[i]
575
+ i += 1
576
+
577
+ self.content_buffer = self.content_buffer[i:]
578
+ return False, content_to_yield
579
+
580
+ def _update_think_state(self, pos: int):
581
+ """Update think tag state, supports nesting"""
582
+ remaining = self.content_buffer[pos:]
583
+
584
+ if remaining.startswith('<think>'):
585
+ self.think_depth += 1
586
+ self.in_think_block = True
587
+ logger.debug(f"🔧 Entering think block, depth: {self.think_depth}")
588
+ return 7
589
+
590
+ elif remaining.startswith('</think>'):
591
+ self.think_depth = max(0, self.think_depth - 1)
592
+ self.in_think_block = self.think_depth > 0
593
+ logger.debug(f"🔧 Exiting think block, depth: {self.think_depth}")
594
+ return 8
595
+
596
+ return 0
597
+
598
+ def _can_detect_signal_at(self, pos: int) -> bool:
599
+ """Check if signal can be detected at the specified position"""
600
+ return (pos + self.signal_len <= len(self.content_buffer) and
601
+ not self.in_think_block)
602
+
603
+ def finalize(self) -> Optional[List[Dict[str, Any]]]:
604
+ """Final processing when stream ends"""
605
+ if self.state == "tool_parsing":
606
+ return parse_function_calls_xml(self.content_buffer, self.trigger_signal)
607
+ return None
608
+
609
+ def parse_function_calls_xml(xml_string: str, trigger_signal: str) -> Optional[List[Dict[str, Any]]]:
610
+ """
611
+ Enhanced XML parsing function, supports dynamic trigger signals
612
+ 1. Retain <think>...</think> blocks (they should be returned normally to the user)
613
+ 2. Temporarily remove think blocks only when parsing function_calls to prevent think content from interfering with XML parsing
614
+ 3. Find the last occurrence of the trigger signal
615
+ 4. Start parsing function_calls from the last trigger signal
616
+ """
617
+ logger.debug(f"🔧 Improved parser starting processing, input length: {len(xml_string) if xml_string else 0}")
618
+ logger.debug(f"🔧 Using trigger signal: {trigger_signal[:20]}...")
619
+
620
+ if not xml_string or trigger_signal not in xml_string:
621
+ logger.debug(f"🔧 Input is empty or doesn't contain trigger signal")
622
+ return None
623
+
624
+ cleaned_content = remove_think_blocks(xml_string)
625
+ logger.debug(f"🔧 Content length after temporarily removing think blocks: {len(cleaned_content)}")
626
+
627
+ signal_positions = []
628
+ start_pos = 0
629
+ while True:
630
+ pos = cleaned_content.find(trigger_signal, start_pos)
631
+ if pos == -1:
632
+ break
633
+ signal_positions.append(pos)
634
+ start_pos = pos + 1
635
+
636
+ if not signal_positions:
637
+ logger.debug(f"🔧 No trigger signal found in cleaned content")
638
+ return None
639
+
640
+ logger.debug(f"🔧 Found {len(signal_positions)} trigger signal positions: {signal_positions}")
641
+
642
+ last_signal_pos = signal_positions[-1]
643
+ content_after_signal = cleaned_content[last_signal_pos:]
644
+ logger.debug(f"🔧 Content starting from last trigger signal: {repr(content_after_signal[:100])}")
645
+
646
+ calls_content_match = re.search(r"<function_calls>([\s\S]*?)</function_calls>", content_after_signal)
647
+ if not calls_content_match:
648
+ logger.debug(f"🔧 No function_calls tag found")
649
+ return None
650
+
651
+ calls_content = calls_content_match.group(1)
652
+ logger.debug(f"🔧 function_calls content: {repr(calls_content)}")
653
+
654
+ results = []
655
+ call_blocks = re.findall(r"<function_call>([\s\S]*?)</function_call>", calls_content)
656
+ logger.debug(f"🔧 Found {len(call_blocks)} function_call blocks")
657
+
658
+ for i, block in enumerate(call_blocks):
659
+ logger.debug(f"🔧 Processing function_call #{i+1}: {repr(block)}")
660
+
661
+ tool_match = re.search(r"<tool>(.*?)</tool>", block)
662
+ if not tool_match:
663
+ logger.debug(f"🔧 No tool tag found in block #{i+1}")
664
+ continue
665
+
666
+ name = tool_match.group(1).strip()
667
+ args = {}
668
+
669
+ args_block_match = re.search(r"<args>([\s\S]*?)</args>", block)
670
+ if args_block_match:
671
+ args_content = args_block_match.group(1)
672
+ # Support arg tag names containing hyphens (e.g., -i, -A); match any non-space, non-'>' and non-'/' chars
673
+ arg_matches = re.findall(r"<([^\s>/]+)>([\s\S]*?)</\1>", args_content)
674
+
675
+ def _coerce_value(v: str):
676
+ try:
677
+ return json.loads(v)
678
+ except Exception:
679
+ pass
680
+ return v
681
+
682
+ for k, v in arg_matches:
683
+ args[k] = _coerce_value(v)
684
+
685
+ result = {"name": name, "args": args}
686
+ results.append(result)
687
+ logger.debug(f"🔧 Added tool call: {result}")
688
+
689
+ logger.debug(f"🔧 Final parsing result: {results}")
690
+ return results if results else None
691
+
692
+ def find_upstream(model_name: str) -> tuple[Dict[str, Any], str]:
693
+ """Find upstream configuration by model name, handling aliases and passthrough mode."""
694
+
695
+ # Handle model passthrough mode
696
+ if app_config.features.model_passthrough:
697
+ logger.info("🔄 Model passthrough mode is active. Forwarding to 'openai' service.")
698
+ openai_service = None
699
+ for service in app_config.upstream_services:
700
+ if service.name == "openai":
701
+ openai_service = service.model_dump()
702
+ break
703
+
704
+ if openai_service:
705
+ if not openai_service.get("api_key"):
706
+ raise HTTPException(status_code=500, detail="Configuration error: API key not found for the 'openai' service in model passthrough mode.")
707
+ # In passthrough mode, the model name from the request is used directly.
708
+ return openai_service, model_name
709
+ else:
710
+ raise HTTPException(status_code=500, detail="Configuration error: 'model_passthrough' is enabled, but no upstream service named 'openai' was found.")
711
+
712
+ # Default routing logic
713
+ chosen_model_entry = model_name
714
+
715
+ if model_name in ALIAS_MAPPING:
716
+ chosen_model_entry = random.choice(ALIAS_MAPPING[model_name])
717
+ logger.info(f"🔄 Model alias '{model_name}' detected. Randomly selected '{chosen_model_entry}' for this request.")
718
+
719
+ service = MODEL_TO_SERVICE_MAPPING.get(chosen_model_entry)
720
+
721
+ if service:
722
+ if not service.get("api_key"):
723
+ raise HTTPException(status_code=500, detail=f"Model configuration error: API key not found for service '{service.get('name')}'.")
724
+ else:
725
+ logger.warning(f"⚠️ Model '{model_name}' not found in configuration, using default service")
726
+ service = DEFAULT_SERVICE
727
+ if not service.get("api_key"):
728
+ raise HTTPException(status_code=500, detail="Service configuration error: Default API key not found.")
729
+
730
+ actual_model_name = chosen_model_entry
731
+ if ':' in chosen_model_entry:
732
+ parts = chosen_model_entry.split(':', 1)
733
+ if len(parts) == 2:
734
+ _, actual_model_name = parts
735
+
736
+ return service, actual_model_name
737
+
738
+ app = FastAPI()
739
+ http_client = httpx.AsyncClient()
740
+
741
+ @app.middleware("http")
742
+ async def debug_middleware(request: Request, call_next):
743
+ """Middleware for debugging validation errors, does not log conversation content."""
744
+ response = await call_next(request)
745
+
746
+ if response.status_code == 422:
747
+ logger.debug(f"🔍 Validation error detected for {request.method} {request.url.path}")
748
+ logger.debug(f"🔍 Response status code: 422 (Pydantic validation failure)")
749
+
750
+ return response
751
+
752
+ @app.exception_handler(ValidationError)
753
+ async def validation_exception_handler(request: Request, exc: ValidationError):
754
+ """Handle Pydantic validation errors with detailed error information"""
755
+ logger.error(f"❌ Pydantic validation error: {exc}")
756
+ logger.error(f"❌ Request URL: {request.url}")
757
+ logger.error(f"❌ Error details: {exc.errors()}")
758
+
759
+ for error in exc.errors():
760
+ logger.error(f"❌ Validation error location: {error.get('loc')}")
761
+ logger.error(f"❌ Validation error message: {error.get('msg')}")
762
+ logger.error(f"❌ Validation error type: {error.get('type')}")
763
+
764
+ return JSONResponse(
765
+ status_code=422,
766
+ content={
767
+ "error": {
768
+ "message": "Invalid request format",
769
+ "type": "invalid_request_error",
770
+ "code": "invalid_request"
771
+ }
772
+ }
773
+ )
774
+
775
+ @app.exception_handler(Exception)
776
+ async def general_exception_handler(request: Request, exc: Exception):
777
+ """Handle all uncaught exceptions"""
778
+ logger.error(f"❌ Unhandled exception: {exc}")
779
+ logger.error(f"❌ Request URL: {request.url}")
780
+ logger.error(f"❌ Exception type: {type(exc).__name__}")
781
+ logger.error(f"❌ Error stack: {traceback.format_exc()}")
782
+
783
+ return JSONResponse(
784
+ status_code=500,
785
+ content={
786
+ "error": {
787
+ "message": "Internal server error",
788
+ "type": "server_error",
789
+ "code": "internal_error"
790
+ }
791
+ }
792
+ )
793
+
794
+ async def verify_api_key(authorization: str = Header(...)):
795
+ """Dependency: verify client API key"""
796
+ client_key = authorization.replace("Bearer ", "")
797
+ if app_config.features.key_passthrough:
798
+ # In passthrough mode, skip allowed_keys check
799
+ return client_key
800
+ if client_key not in ALLOWED_CLIENT_KEYS:
801
+ raise HTTPException(status_code=401, detail="Unauthorized")
802
+ return client_key
803
+
804
+ def preprocess_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
805
+ """Preprocess messages, convert tool-type messages to AI-understandable format, return dictionary list to avoid Pydantic validation issues"""
806
+ processed_messages = []
807
+
808
+ for message in messages:
809
+ if isinstance(message, dict):
810
+ if message.get("role") == "tool":
811
+ tool_call_id = message.get("tool_call_id")
812
+ content = message.get("content")
813
+
814
+ if tool_call_id and content:
815
+ formatted_content = format_tool_result_for_ai(tool_call_id, content)
816
+ processed_message = {
817
+ "role": "user",
818
+ "content": formatted_content
819
+ }
820
+ processed_messages.append(processed_message)
821
+ logger.debug(f"🔧 Converted tool message to user message: tool_call_id={tool_call_id}")
822
+ else:
823
+ logger.debug(f"🔧 Skipped invalid tool message: tool_call_id={tool_call_id}, content={bool(content)}")
824
+ elif message.get("role") == "assistant" and "tool_calls" in message and message["tool_calls"]:
825
+ tool_calls = message.get("tool_calls", [])
826
+ formatted_tool_calls_str = format_assistant_tool_calls_for_ai(tool_calls, GLOBAL_TRIGGER_SIGNAL)
827
+
828
+ # Combine with original content if it exists
829
+ original_content = message.get("content") or ""
830
+ final_content = f"{original_content}\n{formatted_tool_calls_str}".strip()
831
+
832
+ processed_message = {
833
+ "role": "assistant",
834
+ "content": final_content
835
+ }
836
+ # Copy other potential keys from the original message, except tool_calls
837
+ for key, value in message.items():
838
+ if key not in ["role", "content", "tool_calls"]:
839
+ processed_message[key] = value
840
+
841
+ processed_messages.append(processed_message)
842
+ logger.debug(f"🔧 Converted assistant tool_calls to content.")
843
+
844
+ elif message.get("role") == "developer":
845
+ if app_config.features.convert_developer_to_system:
846
+ processed_message = message.copy()
847
+ processed_message["role"] = "system"
848
+ processed_messages.append(processed_message)
849
+ logger.debug(f"🔧 Converted developer message to system message for better upstream compatibility")
850
+ else:
851
+ processed_messages.append(message)
852
+ logger.debug(f"🔧 Keeping developer role unchanged (based on configuration)")
853
+ else:
854
+ processed_messages.append(message)
855
+ else:
856
+ processed_messages.append(message)
857
+
858
+ return processed_messages
859
+
860
+ @app.post("/v1/chat/completions")
861
+ async def chat_completions(
862
+ request: Request,
863
+ body: ChatCompletionRequest,
864
+ _api_key: str = Depends(verify_api_key)
865
+ ):
866
+ """Main chat completion endpoint, proxy and inject function calling capabilities."""
867
+ try:
868
+ logger.debug(f"🔧 Received request, model: {body.model}")
869
+ logger.debug(f"🔧 Number of messages: {len(body.messages)}")
870
+ logger.debug(f"🔧 Number of tools: {len(body.tools) if body.tools else 0}")
871
+ logger.debug(f"🔧 Streaming: {body.stream}")
872
+
873
+ upstream, actual_model = find_upstream(body.model)
874
+ upstream_url = f"{upstream['base_url']}/chat/completions"
875
+
876
+ logger.debug(f"🔧 Starting message preprocessing, original message count: {len(body.messages)}")
877
+ processed_messages = preprocess_messages(body.messages)
878
+ logger.debug(f"🔧 Preprocessing completed, processed message count: {len(processed_messages)}")
879
+
880
+ if not validate_message_structure(processed_messages):
881
+ logger.error(f"❌ Message structure validation failed, but continuing processing")
882
+
883
+ request_body_dict = body.model_dump(exclude_unset=True)
884
+ request_body_dict["model"] = actual_model
885
+ request_body_dict["messages"] = processed_messages
886
+ is_fc_enabled = app_config.features.enable_function_calling
887
+ has_tools_in_request = bool(body.tools)
888
+ has_function_call = is_fc_enabled and has_tools_in_request
889
+
890
+ logger.debug(f"🔧 Request body constructed, message count: {len(processed_messages)}")
891
+
892
+ except Exception as e:
893
+ logger.error(f"❌ Request preprocessing failed: {str(e)}")
894
+ logger.error(f"❌ Error type: {type(e).__name__}")
895
+ if hasattr(app_config, 'debug') and app_config.debug:
896
+ logger.error(f"❌ Error stack: {traceback.format_exc()}")
897
+
898
+ return JSONResponse(
899
+ status_code=422,
900
+ content={
901
+ "error": {
902
+ "message": "Invalid request format",
903
+ "type": "invalid_request_error",
904
+ "code": "invalid_request"
905
+ }
906
+ }
907
+ )
908
+
909
+ if has_function_call:
910
+ logger.debug(f"🔧 Using global trigger signal for this request: {GLOBAL_TRIGGER_SIGNAL}")
911
+
912
+ function_prompt, _ = generate_function_prompt(body.tools, GLOBAL_TRIGGER_SIGNAL)
913
+
914
+ tool_choice_prompt = safe_process_tool_choice(body.tool_choice)
915
+ if tool_choice_prompt:
916
+ function_prompt += tool_choice_prompt
917
+
918
+ system_message = {"role": "system", "content": function_prompt}
919
+ request_body_dict["messages"].insert(0, system_message)
920
+
921
+ if "tools" in request_body_dict:
922
+ del request_body_dict["tools"]
923
+ if "tool_choice" in request_body_dict:
924
+ del request_body_dict["tool_choice"]
925
+
926
+ elif has_tools_in_request and not is_fc_enabled:
927
+ logger.info(f"🔧 Function calling is disabled by configuration, ignoring 'tools' and 'tool_choice' in request.")
928
+ if "tools" in request_body_dict:
929
+ del request_body_dict["tools"]
930
+ if "tool_choice" in request_body_dict:
931
+ del request_body_dict["tool_choice"]
932
+
933
+ headers = {
934
+ "Content-Type": "application/json",
935
+ "Authorization": f"Bearer {_api_key}" if app_config.features.key_passthrough else f"Bearer {upstream['api_key']}",
936
+ "Accept": "application/json" if not body.stream else "text/event-stream"
937
+ }
938
+
939
+ logger.info(f"📝 Forwarding request to upstream: {upstream['name']}")
940
+ logger.info(f"📝 Model: {request_body_dict.get('model', 'unknown')}, Messages: {len(request_body_dict.get('messages', []))}")
941
+
942
+ if not body.stream:
943
+ try:
944
+ logger.debug(f"🔧 Sending upstream request to: {upstream_url}")
945
+ logger.debug(f"🔧 has_function_call: {has_function_call}")
946
+ logger.debug(f"🔧 Request body contains tools: {bool(body.tools)}")
947
+
948
+ upstream_response = await http_client.post(
949
+ upstream_url, json=request_body_dict, headers=headers, timeout=app_config.server.timeout
950
+ )
951
+ upstream_response.raise_for_status() # If status code is 4xx or 5xx, raise exception
952
+
953
+ response_json = upstream_response.json()
954
+ logger.debug(f"🔧 Upstream response status code: {upstream_response.status_code}")
955
+
956
+ if has_function_call:
957
+ content = response_json["choices"][0]["message"]["content"]
958
+ logger.debug(f"🔧 Complete response content: {repr(content)}")
959
+
960
+ parsed_tools = parse_function_calls_xml(content, GLOBAL_TRIGGER_SIGNAL)
961
+ logger.debug(f"🔧 XML parsing result: {parsed_tools}")
962
+
963
+ if parsed_tools:
964
+ logger.debug(f"🔧 Successfully parsed {len(parsed_tools)} tool calls")
965
+ tool_calls = []
966
+ for tool in parsed_tools:
967
+ tool_call_id = f"call_{uuid.uuid4().hex}"
968
+ store_tool_call_mapping(
969
+ tool_call_id,
970
+ tool["name"],
971
+ tool["args"],
972
+ f"Calling tool {tool['name']}"
973
+ )
974
+ tool_calls.append({
975
+ "id": tool_call_id,
976
+ "type": "function",
977
+ "function": {
978
+ "name": tool["name"],
979
+ "arguments": json.dumps(tool["args"])
980
+ }
981
+ })
982
+ logger.debug(f"🔧 Converted tool_calls: {tool_calls}")
983
+
984
+ response_json["choices"][0]["message"] = {
985
+ "role": "assistant",
986
+ "content": None,
987
+ "tool_calls": tool_calls,
988
+ }
989
+ response_json["choices"][0]["finish_reason"] = "tool_calls"
990
+ logger.debug(f"🔧 Function call conversion completed")
991
+ else:
992
+ logger.debug(f"🔧 No tool calls detected, returning original content (including think blocks)")
993
+ else:
994
+ logger.debug(f"🔧 No function calls detected or conversion conditions not met")
995
+
996
+ return JSONResponse(content=response_json)
997
+
998
+ except httpx.HTTPStatusError as e:
999
+ logger.error(f"❌ Upstream service response error: status_code={e.response.status_code}")
1000
+ logger.error(f"❌ Upstream error details: {e.response.text}")
1001
+
1002
+ if e.response.status_code == 400:
1003
+ error_response = {
1004
+ "error": {
1005
+ "message": "Invalid request parameters",
1006
+ "type": "invalid_request_error",
1007
+ "code": "bad_request"
1008
+ }
1009
+ }
1010
+ elif e.response.status_code == 401:
1011
+ error_response = {
1012
+ "error": {
1013
+ "message": "Authentication failed",
1014
+ "type": "authentication_error",
1015
+ "code": "unauthorized"
1016
+ }
1017
+ }
1018
+ elif e.response.status_code == 403:
1019
+ error_response = {
1020
+ "error": {
1021
+ "message": "Access forbidden",
1022
+ "type": "permission_error",
1023
+ "code": "forbidden"
1024
+ }
1025
+ }
1026
+ elif e.response.status_code == 429:
1027
+ error_response = {
1028
+ "error": {
1029
+ "message": "Rate limit exceeded",
1030
+ "type": "rate_limit_error",
1031
+ "code": "rate_limit_exceeded"
1032
+ }
1033
+ }
1034
+ elif e.response.status_code >= 500:
1035
+ error_response = {
1036
+ "error": {
1037
+ "message": "Upstream service temporarily unavailable",
1038
+ "type": "service_error",
1039
+ "code": "upstream_error"
1040
+ }
1041
+ }
1042
+ else:
1043
+ error_response = {
1044
+ "error": {
1045
+ "message": "Request processing failed",
1046
+ "type": "api_error",
1047
+ "code": "unknown_error"
1048
+ }
1049
+ }
1050
+
1051
+ return JSONResponse(content=error_response, status_code=e.response.status_code)
1052
+
1053
+ else:
1054
+ return StreamingResponse(
1055
+ stream_proxy_with_fc_transform(upstream_url, request_body_dict, headers, body.model, has_function_call, GLOBAL_TRIGGER_SIGNAL),
1056
+ media_type="text/event-stream"
1057
+ )
1058
+
1059
+ async def stream_proxy_with_fc_transform(url: str, body: dict, headers: dict, model: str, has_fc: bool, trigger_signal: str):
1060
+ """
1061
+ Enhanced streaming proxy, supports dynamic trigger signals, avoids misjudgment within think tags
1062
+ """
1063
+ logger.info(f"📝 Starting streaming response from: {url}")
1064
+ logger.info(f"📝 Function calling enabled: {has_fc}")
1065
+
1066
+ if not has_fc or not trigger_signal:
1067
+ try:
1068
+ async with http_client.stream("POST", url, json=body, headers=headers, timeout=app_config.server.timeout) as response:
1069
+ async for chunk in response.aiter_bytes():
1070
+ yield chunk
1071
+ except httpx.RemoteProtocolError:
1072
+ logger.debug("🔧 Upstream closed connection prematurely, ending stream response")
1073
+ return
1074
+ return
1075
+ # setattr()``
1076
+ detector = StreamingFunctionCallDetector(trigger_signal)
1077
+
1078
+ def _prepare_tool_calls(parsed_tools: List[Dict[str, Any]]):
1079
+ tool_calls = []
1080
+ for i, tool in enumerate(parsed_tools):
1081
+ tool_call_id = f"call_{uuid.uuid4().hex}"
1082
+ store_tool_call_mapping(
1083
+ tool_call_id,
1084
+ tool["name"],
1085
+ tool["args"],
1086
+ f"Calling tool {tool['name']}"
1087
+ )
1088
+ tool_calls.append({
1089
+ "index": i, "id": tool_call_id, "type": "function",
1090
+ "function": { "name": tool["name"], "arguments": json.dumps(tool["args"]) }
1091
+ })
1092
+ return tool_calls
1093
+
1094
+ def _build_tool_call_sse_chunks(parsed_tools: List[Dict[str, Any]], model_id: str) -> List[str]:
1095
+ tool_calls = _prepare_tool_calls(parsed_tools)
1096
+ chunks: List[str] = []
1097
+
1098
+ initial_chunk = {
1099
+ "id": f"chatcmpl-{uuid.uuid4().hex}", "object": "chat.completion.chunk",
1100
+ "created": int(os.path.getmtime(__file__)), "model": model_id,
1101
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": None, "tool_calls": tool_calls}, "finish_reason": None}],
1102
+ }
1103
+ chunks.append(f"data: {json.dumps(initial_chunk)}\n\n")
1104
+
1105
+
1106
+ final_chunk = {
1107
+ "id": f"chatcmpl-{uuid.uuid4().hex}", "object": "chat.completion.chunk",
1108
+ "created": int(os.path.getmtime(__file__)), "model": model_id,
1109
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
1110
+ }
1111
+ chunks.append(f"data: {json.dumps(final_chunk)}\n\n")
1112
+ chunks.append("data: [DONE]\n\n")
1113
+ return chunks
1114
+
1115
+ try:
1116
+ async with http_client.stream("POST", url, json=body, headers=headers, timeout=app_config.server.timeout) as response:
1117
+ if response.status_code != 200:
1118
+ error_content = await response.aread()
1119
+ logger.error(f"❌ Upstream service stream response error: status_code={response.status_code}")
1120
+ logger.error(f"❌ Upstream error details: {error_content.decode('utf-8', errors='ignore')}")
1121
+
1122
+ if response.status_code == 401:
1123
+ error_message = "Authentication failed"
1124
+ elif response.status_code == 403:
1125
+ error_message = "Access forbidden"
1126
+ elif response.status_code == 429:
1127
+ error_message = "Rate limit exceeded"
1128
+ elif response.status_code >= 500:
1129
+ error_message = "Upstream service temporarily unavailable"
1130
+ else:
1131
+ error_message = "Request processing failed"
1132
+
1133
+ error_chunk = {"error": {"message": error_message, "type": "upstream_error"}}
1134
+ yield f"data: {json.dumps(error_chunk)}\n\n"
1135
+ yield "data: [DONE]\n\n"
1136
+ return
1137
+
1138
+ async for line in response.aiter_lines():
1139
+ if detector.state == "tool_parsing":
1140
+ if line.startswith("data:"):
1141
+ line_data = line[len("data: "):].strip()
1142
+ if line_data and line_data != "[DONE]":
1143
+ try:
1144
+ chunk_json = json.loads(line_data)
1145
+ delta_content = chunk_json.get("choices", [{}])[0].get("delta", {}).get("content", "") or ""
1146
+ detector.content_buffer += delta_content
1147
+ # Early termination: once </function_calls> appears, parse and finish immediately
1148
+ if "</function_calls>" in detector.content_buffer:
1149
+ logger.debug("🔧 Detected </function_calls> in stream, finalizing early...")
1150
+ parsed_tools = detector.finalize()
1151
+ if parsed_tools:
1152
+ logger.debug(f"🔧 Early finalize: parsed {len(parsed_tools)} tool calls")
1153
+ for sse in _build_tool_call_sse_chunks(parsed_tools, model):
1154
+ yield sse
1155
+ return
1156
+ else:
1157
+ logger.error("❌ Early finalize failed to parse tool calls")
1158
+ error_content = "Error: Detected tool use signal but failed to parse function call format"
1159
+ error_chunk = { "id": "error-chunk", "choices": [{"delta": {"content": error_content}}]}
1160
+ yield f"data: {json.dumps(error_chunk)}\n\n"
1161
+ yield "data: [DONE]\n\n"
1162
+ return
1163
+ except (json.JSONDecodeError, IndexError):
1164
+ pass
1165
+ continue
1166
+
1167
+ if line.startswith("data:"):
1168
+ line_data = line[len("data: "):].strip()
1169
+ if not line_data or line_data == "[DONE]":
1170
+ continue
1171
+
1172
+ try:
1173
+ chunk_json = json.loads(line_data)
1174
+ delta_content = chunk_json.get("choices", [{}])[0].get("delta", {}).get("content", "") or ""
1175
+
1176
+ if delta_content:
1177
+ is_detected, content_to_yield = detector.process_chunk(delta_content)
1178
+
1179
+ if content_to_yield:
1180
+ yield_chunk = {
1181
+ "id": f"chatcmpl-passthrough-{uuid.uuid4().hex}",
1182
+ "object": "chat.completion.chunk",
1183
+ "created": int(os.path.getmtime(__file__)),
1184
+ "model": model,
1185
+ "choices": [{"index": 0, "delta": {"content": content_to_yield}}]
1186
+ }
1187
+ yield f"data: {json.dumps(yield_chunk)}\n\n"
1188
+
1189
+ if is_detected:
1190
+ # Tool call signal detected, switch to parsing mode
1191
+ continue
1192
+
1193
+ except (json.JSONDecodeError, IndexError):
1194
+ yield line + "\n\n"
1195
+
1196
+ except httpx.RequestError as e:
1197
+ logger.error(f"❌ Failed to connect to upstream service: {e}")
1198
+ logger.error(f"❌ Error type: {type(e).__name__}")
1199
+
1200
+ error_message = "Failed to connect to upstream service"
1201
+ error_chunk = {"error": {"message": error_message, "type": "connection_error"}}
1202
+ yield f"data: {json.dumps(error_chunk)}\n\n"
1203
+ yield "data: [DONE]\n\n"
1204
+ return
1205
+
1206
+ if detector.state == "tool_parsing":
1207
+ logger.debug(f"🔧 Stream ended, starting to parse tool call XML...")
1208
+ parsed_tools = detector.finalize()
1209
+ if parsed_tools:
1210
+ logger.debug(f"🔧 Streaming processing: Successfully parsed {len(parsed_tools)} tool calls")
1211
+ for sse in _build_tool_call_sse_chunks(parsed_tools, model):
1212
+ yield sse
1213
+ return
1214
+ else:
1215
+ logger.error(f"❌ Detected tool call signal but XML parsing failed, buffer content: {detector.content_buffer}")
1216
+ error_content = "Error: Detected tool use signal but failed to parse function call format"
1217
+ error_chunk = { "id": "error-chunk", "choices": [{"delta": {"content": error_content}}]}
1218
+ yield f"data: {json.dumps(error_chunk)}\n\n"
1219
+
1220
+ elif detector.state == "detecting" and detector.content_buffer:
1221
+ # If stream has ended but buffer still has remaining characters insufficient to form signal, output them
1222
+ final_yield_chunk = {
1223
+ "id": f"chatcmpl-finalflush-{uuid.uuid4().hex}", "object": "chat.completion.chunk",
1224
+ "created": int(os.path.getmtime(__file__)), "model": model,
1225
+ "choices": [{"index": 0, "delta": {"content": detector.content_buffer}}]
1226
+ }
1227
+ yield f"data: {json.dumps(final_yield_chunk)}\n\n"
1228
+
1229
+ yield "data: [DONE]\n\n"
1230
+
1231
+
1232
+ @app.get("/")
1233
+ def read_root():
1234
+ return {
1235
+ "status": "OpenAI Function Call Middleware is running",
1236
+ "config": {
1237
+ "upstream_services_count": len(app_config.upstream_services),
1238
+ "client_keys_count": len(app_config.client_authentication.allowed_keys),
1239
+ "models_count": len(MODEL_TO_SERVICE_MAPPING),
1240
+ "features": {
1241
+ "function_calling": app_config.features.enable_function_calling,
1242
+ "log_level": app_config.features.log_level,
1243
+ "convert_developer_to_system": app_config.features.convert_developer_to_system,
1244
+ "random_trigger": True
1245
+ }
1246
+ }
1247
+ }
1248
+
1249
+ @app.get("/v1/models")
1250
+ async def list_models(_api_key: str = Depends(verify_api_key)):
1251
+ """List all available models"""
1252
+ visible_models = set()
1253
+ for model_name in MODEL_TO_SERVICE_MAPPING.keys():
1254
+ if ':' in model_name:
1255
+ parts = model_name.split(':', 1)
1256
+ if len(parts) == 2:
1257
+ alias, _ = parts
1258
+ visible_models.add(alias)
1259
+ else:
1260
+ visible_models.add(model_name)
1261
+ else:
1262
+ visible_models.add(model_name)
1263
+
1264
+ models = []
1265
+ for model_id in sorted(visible_models):
1266
+ models.append({
1267
+ "id": model_id,
1268
+ "object": "model",
1269
+ "created": 1677610602,
1270
+ "owned_by": "openai",
1271
+ "permission": [],
1272
+ "root": model_id,
1273
+ "parent": None
1274
+ })
1275
+
1276
+ return {
1277
+ "object": "list",
1278
+ "data": models
1279
+ }
1280
+
1281
+
1282
+ def validate_message_structure(messages: List[Dict[str, Any]]) -> bool:
1283
+ """Validate if message structure meets requirements"""
1284
+ try:
1285
+ valid_roles = ["system", "user", "assistant", "tool"]
1286
+ if not app_config.features.convert_developer_to_system:
1287
+ valid_roles.append("developer")
1288
+
1289
+ for i, msg in enumerate(messages):
1290
+ if "role" not in msg:
1291
+ logger.error(f"❌ Message {i} missing role field")
1292
+ return False
1293
+
1294
+ if msg["role"] not in valid_roles:
1295
+ logger.error(f"❌ Invalid role value for message {i}: {msg['role']}")
1296
+ return False
1297
+
1298
+ if msg["role"] == "tool":
1299
+ if "tool_call_id" not in msg:
1300
+ logger.error(f"❌ Tool message {i} missing tool_call_id field")
1301
+ return False
1302
+
1303
+ content = msg.get("content")
1304
+ content_info = ""
1305
+ if content:
1306
+ if isinstance(content, str):
1307
+ content_info = f", content=text({len(content)} chars)"
1308
+ elif isinstance(content, list):
1309
+ text_parts = [item for item in content if isinstance(item, dict) and item.get('type') == 'text']
1310
+ image_parts = [item for item in content if isinstance(item, dict) and item.get('type') == 'image_url']
1311
+ content_info = f", content=multimodal(text={len(text_parts)}, images={len(image_parts)})"
1312
+ else:
1313
+ content_info = f", content={type(content).__name__}"
1314
+ else:
1315
+ content_info = ", content=empty"
1316
+
1317
+ logger.debug(f"✅ Message {i} validation passed: role={msg['role']}{content_info}")
1318
+
1319
+ logger.debug(f"✅ All messages validated successfully, total {len(messages)} messages")
1320
+ return True
1321
+ except Exception as e:
1322
+ logger.error(f"❌ Message validation exception: {e}")
1323
+ return False
1324
+
1325
+ def safe_process_tool_choice(tool_choice) -> str:
1326
+ """Safely process tool_choice field to avoid type errors"""
1327
+ try:
1328
+ if tool_choice is None:
1329
+ return ""
1330
+
1331
+ if isinstance(tool_choice, str):
1332
+ if tool_choice == "none":
1333
+ return "\n\n**IMPORTANT:** You are prohibited from using any tools in this round. Please respond like a normal chat assistant and answer the user's question directly."
1334
+ else:
1335
+ logger.debug(f"🔧 Unknown tool_choice string value: {tool_choice}")
1336
+ return ""
1337
+
1338
+ elif hasattr(tool_choice, 'function') and hasattr(tool_choice.function, 'name'):
1339
+ required_tool_name = tool_choice.function.name
1340
+ return f"\n\n**IMPORTANT:** In this round, you must use ONLY the tool named `{required_tool_name}`. Generate the necessary parameters and output in the specified XML format."
1341
+
1342
+ else:
1343
+ logger.debug(f"🔧 Unsupported tool_choice type: {type(tool_choice)}")
1344
+ return ""
1345
+
1346
+ except Exception as e:
1347
+ logger.error(f"❌ Error processing tool_choice: {e}")
1348
+ return ""
1349
+
1350
+ if __name__ == "__main__":
1351
+ import uvicorn
1352
+ logger.info(f"🚀 Starting server on {app_config.server.host}:{app_config.server.port}")
1353
+ logger.info(f"⏱️ Request timeout: {app_config.server.timeout} seconds")
1354
+
1355
+ uvicorn.run(
1356
+ app,
1357
+ host=app_config.server.host,
1358
+ port=app_config.server.port,
1359
+ log_level=app_config.features.log_level.lower() if app_config.features.log_level != "DISABLED" else "critical"
1360
+ )
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ httpx
4
+ pydantic
5
+ pyyaml
scripts/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
scripts/generate_config.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """基于环境变量生成 Toolify 配置文件。"""
3
+
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, List
8
+
9
+ import yaml
10
+
11
+
12
+ def _str_to_bool(value: str | None, default: bool) -> bool:
13
+ """将字符串环境变量解析为布尔值。"""
14
+ if value is None:
15
+ return default
16
+ normalized = value.strip().lower()
17
+ if normalized in {"1", "true", "yes", "y", "on"}:
18
+ return True
19
+ if normalized in {"0", "false", "no", "n", "off"}:
20
+ return False
21
+ return default
22
+
23
+
24
+ def _parse_list(env_value: str | None) -> List[str]:
25
+ """将逗号分隔的环境变量解析为字符串列表。"""
26
+ if not env_value:
27
+ return []
28
+ return [item.strip() for item in env_value.split(",") if item.strip()]
29
+
30
+
31
+ def _load_config_from_env() -> Any:
32
+ """尝试从直接提供的 YAML 或 JSON 环境变量加载配置。"""
33
+ direct_yaml = os.getenv("TOOLIFY_CONFIG_YAML")
34
+ if direct_yaml:
35
+ return yaml.safe_load(direct_yaml)
36
+
37
+ direct_json = os.getenv("TOOLIFY_CONFIG_JSON")
38
+ if direct_json:
39
+ return yaml.safe_load(direct_json)
40
+
41
+ return None
42
+
43
+
44
+ def _build_default_config() -> dict:
45
+ """根据基础环境变量构造最小可用配置。"""
46
+ openai_api_key = os.getenv("OPENAI_API_KEY")
47
+ allowed_keys = _parse_list(os.getenv("CLIENT_ALLOWED_KEYS"))
48
+
49
+ if not openai_api_key:
50
+ raise RuntimeError("缺少 OPENAI_API_KEY 环境变量,无法生成配置。")
51
+
52
+ if not allowed_keys:
53
+ raise RuntimeError("缺少 CLIENT_ALLOWED_KEYS 环境变量,无法生成配置。")
54
+
55
+ base_url = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1").rstrip("/")
56
+ models = _parse_list(os.getenv("OPENAI_MODELS", "gpt-4o-mini,gpt-4o"))
57
+ if not models:
58
+ raise RuntimeError("OPENAI_MODELS 环境变量解析为空,请至少指定一个模型。")
59
+
60
+ server_port = int(os.getenv("SERVER_PORT", os.getenv("PORT", "8000")))
61
+ server_host = os.getenv("SERVER_HOST", "0.0.0.0")
62
+ server_timeout = int(os.getenv("SERVER_TIMEOUT", "180"))
63
+
64
+ features_log_level = os.getenv("FEATURE_LOG_LEVEL", "INFO").upper()
65
+
66
+ prompt_template = os.getenv("FEATURE_PROMPT_TEMPLATE")
67
+ if prompt_template:
68
+ prompt_template = prompt_template.replace("\\n", "\n")
69
+
70
+ return {
71
+ "server": {
72
+ "port": server_port,
73
+ "host": server_host,
74
+ "timeout": server_timeout,
75
+ },
76
+ "upstream_services": [
77
+ {
78
+ "name": os.getenv("OPENAI_NAME", "openai"),
79
+ "base_url": base_url,
80
+ "api_key": openai_api_key,
81
+ "description": os.getenv("OPENAI_DESCRIPTION", "OpenAI Service"),
82
+ "is_default": True,
83
+ "models": models,
84
+ }
85
+ ],
86
+ "client_authentication": {
87
+ "allowed_keys": allowed_keys,
88
+ },
89
+ "features": {
90
+ "enable_function_calling": _str_to_bool(os.getenv("FEATURE_ENABLE_FUNCTION_CALLING"), True),
91
+ "log_level": features_log_level if features_log_level else "INFO",
92
+ "convert_developer_to_system": _str_to_bool(os.getenv("FEATURE_CONVERT_DEVELOPER_TO_SYSTEM"), True),
93
+ "prompt_template": prompt_template,
94
+ "key_passthrough": _str_to_bool(os.getenv("FEATURE_KEY_PASSTHROUGH"), False),
95
+ "model_passthrough": _str_to_bool(os.getenv("FEATURE_MODEL_PASSTHROUGH"), False),
96
+ },
97
+ }
98
+
99
+
100
+ def main() -> None:
101
+ """入口函数:生成配置文件。"""
102
+ config_path = Path(os.getenv("CONFIG_PATH", "/app/config.yaml"))
103
+
104
+ if config_path.exists():
105
+ print(f"配置文件已存在,跳过生成: {config_path}")
106
+ return
107
+
108
+ config_obj = _load_config_from_env()
109
+ if config_obj is None:
110
+ config_obj = _build_default_config()
111
+
112
+ if not isinstance(config_obj, dict):
113
+ raise ValueError("环境变量提供的配置必须是字典结构。")
114
+
115
+ config_path.parent.mkdir(parents=True, exist_ok=True)
116
+ config_yaml = yaml.safe_dump(config_obj, sort_keys=False, allow_unicode=True)
117
+ config_path.write_text(config_yaml, encoding="utf-8")
118
+ print(f"已生成配置文件: {config_path}")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ try:
123
+ main()
124
+ except Exception as exc: # noqa: BLE001
125
+ print(f"生成配置文件时出现错误: {exc}", file=sys.stderr)
126
+ sys.exit(1)