├── .github
└── workflows
│ └── deploy.yml
├── .gitignore
├── .vscode
└── launch.json
├── LICENSE
├── README.md
├── README.zh-CN.md
├── package.json
├── pnpm-lock.yaml
├── src
├── __tests__
│ └── index.test.ts
├── api
│ ├── common.ts
│ ├── ollama
│ │ ├── __test__
│ │ │ └── index.test.ts
│ │ └── index.ts
│ └── openai
│ │ └── index.ts
├── claude
│ ├── __tests__
│ │ ├── authenticate.test.ts
│ │ └── web.test.ts
│ ├── authenticate.ts
│ └── web.ts
├── index.ts
├── llm
│ ├── anthropic.test.ts
│ ├── anthropic.ts
│ ├── azure.test.ts
│ ├── azure.ts
│ ├── bailian.test.ts
│ ├── bailian.ts
│ ├── base.ts
│ ├── cerebras.ts
│ ├── cohere.test.ts
│ ├── cohere.ts
│ ├── deepseek.test.ts
│ ├── deepseek.ts
│ ├── google.test.ts
│ ├── google.ts
│ ├── grok.test.ts
│ ├── grok.ts
│ ├── groq.test.ts
│ ├── groq.ts
│ ├── lingyiwanwu.ts
│ ├── moonshot.test.ts
│ ├── moonshot.ts
│ ├── ollama.test.ts
│ ├── ollama.ts
│ ├── openai.test.ts
│ ├── openai.ts
│ ├── openrouter.test.ts
│ └── openrouter.ts
└── vite-env.d.ts
├── tsconfig.json
├── vitest.config.ts
└── wrangler.jsonc
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Deploy Worker
2 | on:
3 | push:
4 | branches:
5 | - main
6 | jobs:
7 | deploy:
8 | runs-on: ubuntu-latest
9 | timeout-minutes: 60
10 | steps:
11 | - uses: actions/checkout@v2
12 | - name: Setup pnpm
13 | uses: pnpm/action-setup@v4
14 | - name: Setup Node
15 | uses: actions/setup-node@v4
16 | with:
17 | node-version: 22
18 | cache: pnpm
19 | - name: Install dependencies
20 | run: pnpm i --frozen-lockfile
21 | - name: Build & Deploy Worker
22 | uses: cloudflare/wrangler-action@v3
23 | with:
24 | apiToken: ${{ secrets.CF_API_TOKEN }}
25 | accountId: ${{ secrets.CF_ACCOUNT_ID }}
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # prod
2 | dist/
3 |
4 | # dev
5 | .yarn/
6 | !.yarn/releases
7 | .vscode/*
8 | !.vscode/launch.json
9 | !.vscode/*.code-snippets
10 | .idea/workspace.xml
11 | .idea/usage.statistics.xml
12 | .idea/shelf
13 |
14 | # deps
15 | node_modules/
16 | .wrangler
17 |
18 | # env
19 | .env
20 | .env.production
21 | .dev.vars
22 |
23 | # logs
24 | logs/
25 | *.log
26 | npm-debug.log*
27 | yarn-debug.log*
28 | yarn-error.log*
29 | pnpm-debug.log*
30 | lerna-debug.log*
31 |
32 | # misc
33 | .DS_Store
34 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "configurations": [
3 | {
4 | "name": "Wrangler",
5 | "type": "node",
6 | "request": "attach",
7 | "port": 9229,
8 | "cwd": "/",
9 | "resolveSourceMapLocations": null,
10 | "attachExistingChildren": false,
11 | "autoAttachChildProcesses": false,
12 | "sourceMaps": true // works with or without this line
13 | }
14 | ]
15 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
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 |
635 | Copyright (C)
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 .
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 | Copyright (C)
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 | .
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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OpenAI API Proxy
2 |
3 | ## Introduction
4 |
5 | Provides the same proxy OpenAI API and Ollama API interface for different LLM models, and supports deployment to any Edge Runtime environment.
6 |
7 | Supported models
8 |
9 | - [x] OpenAI
10 | - [x] Anthropic
11 | - [x] Google Vertex Anthropic
12 | - [x] Google Gemini
13 | - [x] DeepSeek
14 | - [x] Groq
15 | - [x] Cerebras
16 | - [x] Azure OpenAI
17 | - [x] Cohere
18 | - [x] Aliyun Bailian
19 | - [x] Ollama
20 | - [x] Grok
21 | - [x] OpenRouter
22 | - [ ] Cloudflare Workers AI
23 | - [ ] Coze
24 |
25 | ## Deployment
26 |
27 | [](https://deploy.workers.cloudflare.com/?url=https://github.com/rxliuli/openai-api-proxy)
28 |
29 | Environment variables
30 |
31 | - `API_KEY`: Proxy API Key, required when calling the proxy API
32 | - `CORS_ORIGIN`: Allowed CORS domain, e.g. `https://example.com`
33 |
34 | - OpenAI: Supports OpenAI models, e.g. `gpt-4o-mini`
35 | - `OPENAI_API_KEY`: OpenAI API Key
36 | - VertexAI Anthropic: Supports Anthropic models on Google Vertex AI, e.g. `claude-3-5-sonnet@20240620`
37 | - `VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL`: Google Cloud Service Account Email
38 | - `VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY`: Google Cloud Service Account Private Key
39 | - `VERTEX_ANTROPIC_REGION`: Google Vertex AI Anthropic Region
40 | - `VERTEX_ANTROPIC_PROJECTID`: Google Vertex AI Anthropic Project ID
41 | - Anthropic: Supports Anthropic models, e.g. `claude-3-5-sonnet-20240620`
42 | - `ANTROPIC_API_KEY`: Anthropic API Key
43 | - Google Gemini: Supports Google Gemini models, e.g. `gemini-1.5-flash`
44 | - `GOOGLE_GEN_AI_API_KEY`: Google Gemini API Key
45 | - DeepSeek: Supports DeepSeek models, e.g. `deepseek-chat`
46 | - `DEEPSEEK_API_KEY`: DeepSeek API Key
47 | - Groq: Supports Groq models, e.g. `llama3-8b-8192`
48 | - `GROQ_API_KEY`: Groq API Key
49 | - Cerebras: Supports Cerebras models, e.g. `llama-3-8b`
50 | - `CEREBRAS_API_KEY`: Cerebras API Key
51 | - Azure OpenAI: Supports Azure OpenAI models, e.g. `gpt-4o-mini`
52 | - `AZURE_OPENAI_API_KEY`: Azure OpenAI API Key
53 | - `AZURE_OPENAI_ENDPOINT`: Azure OpenAI Endpoint
54 | - `AZURE_API_VERSION`: Azure OpenAI API Version
55 | - `AZURE_DEPLOYMENT_MODELS`: Azure OpenAI Deployment Models, such as `gpt-4o-mini:gpt-4o-mini-dev,gpt-35-turbo:gpt-35-dev`, represent two models, `gpt-4o-mini` and `gpt-35-turbo`, corresponding to two deployments, `gpt-4o-mini-dev` and `gpt-35-dev` respectively.
56 | - Cohere: Supports Cohere models, e.g. `command-r`
57 | - `COHERE_API_KEY`: Cohere API Key
58 | - Aliyun Bailian: Supports Aliyun Bailian models, e.g. `qwen-max`
59 | - `ALIYUN_BAILIAN_API_KEY`: Aliyun Bailian API Key
60 | - `ALIYUN_BAILIAN_MODELS`: Custom supported Aliyun Bailian models, e.g. `qwen-max,qwen-7b-chat`, default to `qwen-max`
61 | - Ollama:
62 | - `OLLAMA_BASE_URL`: Ollama Base URL, e.g. `http://localhost:11434/v1`
63 | - `OLLAMA_MODELS`: Ollama Models, e.g. `deepseek-r1,lama3.3:70b,phi4:latest`
64 | - OpenRouter: Supports OpenRouter models, e.g. `openai/gpt-4o-mini`
65 | - `OPENROUTER_API_KEY`: OpenRouter API Key
66 | - `OPENROUTER_MODELS`: OpenRouter Models, e.g. `openai/gpt-4o-mini,anthropic/claude-3-5-sonnet-20240620`
67 | - Grok: Supports grok3 models, e.g. `grok-3-latest`, `grok-3-mini-latest`
68 | - `GROK_API_KEY`: Grok API key
69 |
70 | ## Usage
71 |
72 | Once deployed successfully, you can call different models through OpenAI's API interface.
73 |
74 | For example, calling OpenAI's API interface:
75 |
76 | ```bash
77 | curl http://localhost:8787/v1/chat/completions \
78 | -H "Content-Type: application/json" \
79 | -H "Authorization: Bearer $API_KEY" \
80 | -d '{
81 | "model": "gpt-4o-mini",
82 | "messages": [
83 | {
84 | "role": "user",
85 | "content": "Hello, world!"
86 | }
87 | ]
88 | }'
89 | ```
90 |
91 | Or calling Anthropic's API interface:
92 |
93 | ```bash
94 | curl http://localhost:8787/v1/chat/completions \
95 | -H "Content-Type: application/json" \
96 | -H "Authorization: Bearer $API_KEY" \
97 | -d '{
98 | "model": "claude-3-5-sonnet-20240620",
99 | "messages": [
100 | {
101 | "role": "user",
102 | "content": "Hello, world!"
103 | }
104 | ]
105 | }'
106 | ```
107 |
108 | And it can be used in OpenAI's official SDK, for example:
109 |
110 | ```ts
111 | const openai = new OpenAI({
112 | baseURL: 'http://localhost:8787/v1',
113 | apiKey: '$API_KEY',
114 | })
115 |
116 | const response = await openai.chat.completions.create({
117 | model: 'gpt-4o-mini',
118 | messages: [{ role: 'user', content: 'Hello, world!' }],
119 | })
120 |
121 | console.log(response)
122 | ```
123 |
124 | And Ollama API interface:
125 |
126 | Ollama provides local model serving. Since some clients, similar to certain IntelliJ IDEA integrations, don't support custom headers, the approach of placing the API Key (AK) in the path was adopted. Therefore, within IntelliJ, you can configure the endpoint as `http://localhost:8787/ollama/$API_KEY/v1`
127 |
128 | ```bash
129 | curl http://localhost:8787/ollama/$API_KEY/v1/api/chat \
130 | -H "Content-Type: application/json" \
131 | -d '{
132 | "model": "gemini-2.0-flash",
133 | "stream": true,
134 | "messages": [
135 | {
136 | "role": "user",
137 | "content": "Hello, world!"
138 | }
139 | ]
140 | }'
141 | ```
142 |
143 | ### OpenAI Compatibility
144 |
145 | - [/v1/chat/completions](https://platform.openai.com/docs/api-reference/chat/create)
146 | - [/v1/models](https://platform.openai.com/docs/api-reference/models)
147 |
148 | ### Ollama Compatibility
149 |
150 | - [/api/chat](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-a-chat-completion)
151 | - [/api/tags](https://github.com/ollama/ollama/blob/main/docs/api.md#list-local-models)
152 |
153 | ### Supported Models
154 |
155 | Due to some models existing across multiple vendors, certain model names may have prefixes added, such as `groq/llama3-8b-8192`, indicating Groq's `llama3-8b-8192` model.
156 |
157 | Get a list of supported models via API:
158 |
159 | ```bash
160 | curl http://localhost:8787/v1/models \
161 | -H "Authorization: Bearer $API_KEY" \
162 | -H "Content-Type: application/json"
163 | ```
164 |
165 | ## Motivation
166 |
167 | I'm using Vertex AI's Anthropic model, but found that many LLM tools don't support configuring it directly. This prompted me to develop an API proxy. With this proxy, I can seamlessly use other AI models in any tool that supports the OpenAI API.
168 |
169 | Although there are some commercial services that resell LLM tokens, they usually require routing through their servers. Well, there's no need for another third party to know how I'm using it. This proxy can be deployed to any Edge Runtime environment, such as Cloudflare Workers, which provides up to 100k free requests per day for individuals.
170 |
--------------------------------------------------------------------------------
/README.zh-CN.md:
--------------------------------------------------------------------------------
1 | # OpenAI API Proxy
2 |
3 | ## 介绍
4 |
5 | 为不同的 LLM 模型提供相同的代理 OpenAI API 接口 和 Ollama API 接口,并且支持部署到任何 Edge Runtime 环境。
6 |
7 | 支持的模型
8 |
9 | - [x] OpenAI
10 | - [x] Anthropic
11 | - [x] Google Vertex Anthropic
12 | - [x] Google Gemini
13 | - [x] DeepSeek
14 | - [x] Groq
15 | - [x] Moonshot
16 | - [x] 零一万物
17 | - [x] Cerebras
18 | - [x] Azure OpenAI
19 | - [x] Cohere
20 | - [x] Aliyun Bailian
21 | - [x] Ollama
22 | - [x] Grok
23 | - [x] OpenRouter
24 | - [ ] Cloudflare Workers AI
25 | - [ ] Coze
26 | - [ ] 豆包
27 |
28 | ## 部署
29 |
30 | [](https://deploy.workers.cloudflare.com/?url=https://github.com/rxliuli/openai-api-proxy)
31 |
32 | 环境变量
33 |
34 | - `API_KEY`: 代理 API Key,要求调用代理 API 时必须设置
35 | - `CORS_ORIGIN`: 允许的 CORS 域名,例如 `https://example.com`
36 |
37 | - OpenAI: 支持 OpenAI 模型,例如 `gpt-4o-mini`
38 | - `OPENAI_API_KEY`: OpenAI API Key
39 | - VertexAI Anthropic: 支持 Google Vertex AI 上的 Anthropic 模型,例如 `claude-3-5-sonnet@20240620`
40 | - `VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL`: Google Cloud Service Account Email
41 | - `VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY`: Google Cloud Service Account Private Key
42 | - `VERTEX_ANTROPIC_REGION`: Google Vertex AI Anthropic Region
43 | - `VERTEX_ANTROPIC_PROJECTID`: Google Vertex AI Anthropic Project ID
44 | - Anthropic: 支持 Anthropic 模型,例如 `claude-3-5-sonnet-20240620`
45 | - `ANTROPIC_API_KEY`: Anthropic API Key
46 | - Google Gemini: 支持 Google Gemini 模型,例如 `gemini-1.5-flash`
47 | - `GOOGLE_GEN_AI_API_KEY`: Google Gemini API Key
48 | - DeepSeek: 支持 DeepSeek 模型,例如 `deepseek-chat`
49 | - `DEEPSEEK_API_KEY`: DeepSeek API Key
50 | - Moonshot: 支持 Moonshot 模型,例如 `moonshot-v1-8k`
51 | - `MOONSHOT_API_KEY`: Moonshot API Key
52 | - 零一万物: 支持零一万物模型,例如 `yi-large`
53 | - `LINGYIWANWU_API_KEY`: 零一万物 API Key
54 | - Groq: 支持 Groq 模型,例如 `llama3-8b-8192`
55 | - `GROQ_API_KEY`: Groq API Key
56 | - Cerebras: 支持 Cerebras 模型,例如 `llama-3-8b`
57 | - `CEREBRAS_API_KEY`: Cerebras API Key
58 | - Azure OpenAI: 支持 Azure OpenAI 模型,例如 `gpt-4o-mini`
59 | - `AZURE_OPENAI_API_KEY`: Azure OpenAI API Key
60 | - `AZURE_OPENAI_ENDPOINT`: Azure OpenAI Endpoint
61 | - `AZURE_API_VERSION`: Azure OpenAI API Version
62 | - `AZURE_DEPLOYMENT_MODELS`: Azure OpenAI Deployment Models, 例如 `gpt-4o-mini:gpt-4o-mini-dev,gpt-35-turbo:gpt-35-dev`,表示 `gpt-4o-mini` 和 `gpt-35-turbo` 两个模型,分别对应 `gpt-4o-mini-dev` 和 `gpt-35-dev` 两个部署。
63 | - Cohere: 支持 Cohere 模型,例如 `command-r`
64 | - `COHERE_API_KEY`: Cohere API Key
65 | - Aliyun Bailian: 支持阿里云百炼模型,例如 `qwen-max`
66 | - `ALIYUN_BAILIAN_API_KEY`: 阿里云百炼 API Key
67 | - `ALIYUN_BAILIAN_MODELS`: 自定义支持的阿里云百炼模型列表,例如 `qwen-max,qwen-7b-chat`,默认为 `qwen-max`
68 | - Ollama: 支持 Ollama 模型,例如 `deepseek-r1`
69 | - `OLLAMA_BASE_URL`: Ollama Base URL, 例如 `http://localhost:11434/v1`
70 | - `OLLAMA_MODELS`: Ollama Models, 例如 `deepseek-r1,lama3.3:70b,phi4:latest`
71 | - OpenRouter: 支持 OpenRouter 模型,例如 `openai/gpt-4o-mini`
72 | - `OPENROUTER_API_KEY`: OpenRouter API Key
73 | - `OPENROUTER_MODELS`: OpenRouter Models, 例如 `openai/gpt-4o-mini,anthropic/claude-3-5-sonnet-20240620`
74 | - Grok: 支持 grok3 系列模型, e.g. `grok-3-latest`, `grok-3-mini-latest`
75 | - `GROK_API_KEY`: Grok API key
76 |
77 | ## 使用
78 |
79 | 一旦部署成功,就可以通过 OpenAI 的 API 接口来调用不同的模型。
80 |
81 | 例如,调用 OpenAI 的 API 接口:
82 |
83 | ```bash
84 | curl http://localhost:8787/v1/chat/completions \
85 | -H "Content-Type: application/json" \
86 | -H "Authorization: Bearer $API_KEY" \
87 | -d '{
88 | "model": "gpt-4o-mini",
89 | "messages": [
90 | {
91 | "role": "user",
92 | "content": "Hello, world!"
93 | }
94 | ]
95 | }'
96 | ```
97 |
98 | 或者调用 Anthropic 的 API 接口:
99 |
100 | ```bash
101 | curl http://localhost:8787/v1/chat/completions \
102 | -H "Content-Type: application/json" \
103 | -H "Authorization: Bearer $API_KEY" \
104 | -d '{
105 | "model": "claude-3-5-sonnet-20240620",
106 | "messages": [
107 | {
108 | "role": "user",
109 | "content": "Hello, world!"
110 | }
111 | ]
112 | }'
113 | ```
114 |
115 | 并且可以在 OpenAI 的官方 SDK 中使用,例如:
116 |
117 | ```ts
118 | const openai = new OpenAI({
119 | baseURL: 'http://localhost:8787/v1',
120 | apiKey: '$API_KEY',
121 | })
122 |
123 | const response = await openai.chat.completions.create({
124 | model: 'gpt-4o-mini',
125 | messages: [{ role: 'user', content: 'Hello, world!' }],
126 | })
127 |
128 | console.log(response)
129 | ```
130 |
131 | Ollama API的接口:
132 |
133 | Ollama为本地模型服务,类似IntelliJ IDEA不支持自定义header,因此采取AK放路径思路.在IntelliJ内可以配置`https://$YOUR_HOST/ollama/$API_KEY/v1`
134 |
135 | ```bash
136 | curl http://localhost:8787/ollama/$API_KEY/v1/api/chat \
137 | -H "Content-Type: application/json" \
138 | -d '{
139 | "model": "gemini-2.0-flash",
140 | "stream": true,
141 | "messages": [
142 | {
143 | "role": "user",
144 | "content": "Hello, world!"
145 | }
146 | ]
147 | }'
148 | ```
149 |
150 | ### OpenAI 兼容性
151 |
152 | - [/v1/chat/completions](https://platform.openai.com/docs/api-reference/chat/create)
153 | - [/v1/models](https://platform.openai.com/docs/api-reference/models)
154 |
155 | ### Ollama API 兼容性
156 |
157 | - [/api/chat](https://github.com/ollama/ollama/blob/main/docs/api.md#generate-a-chat-completion)
158 | - [/api/tags](https://github.com/ollama/ollama/blob/main/docs/api.md#list-local-models)
159 |
160 | ### 支持的模型列表
161 |
162 | 由于一些模型在多个供应商中存在,所以一些模型的名称可能会添加前缀,例如 `groq/llama3-8b-8192`,表示 Groq 的 `llama3-8b-8192` 模型。
163 |
164 | 通过 API 获取支持的模型列表:
165 |
166 | ```bash
167 | curl http://localhost:8787/v1/models \
168 | -H "Authorization: Bearer $API_KEY" \
169 | -H "Content-Type: application/json"
170 | ```
171 |
172 | ## 动机
173 |
174 | 我正在使用 Vertex AI 的 Anthropic 模型,但发现许多 LLM 工具不支持直接配置它。这促使我萌生了开发一个 API 代理的想法。通过这个代理,我可以在任何支持 OpenAI API 的工具中无缝使用其他 AI 模型。
175 |
176 | 虽然已经有一些转卖 LLM token 的商业服务,但它们通常需要通过他们的服务器中转。嗯,没必要让另一个第三方知道我如何使用的。这个代理可以部署到任何 Edge Runtime 环境,例如 Cloudflare Workers,对于个人而言,它提供高达 100k/天的免费请求次数。
177 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "openai-api-proxy",
3 | "type": "module",
4 | "scripts": {
5 | "dev": "wrangler dev src/index.ts",
6 | "deploy": "wrangler deploy --minify src/index.ts",
7 | "test": "vitest run",
8 | "postinstall": "npx simple-git-hooks"
9 | },
10 | "prettier": "@liuli-util/prettier-standard-config",
11 | "lint-staged": {
12 | "*.{ts,tsx,js,jsx,css,md,json}": [
13 | "prettier --write"
14 | ]
15 | },
16 | "simple-git-hooks": {
17 | "pre-commit": "pnpm lint-staged"
18 | },
19 | "dependencies": {
20 | "@anthropic-ai/sdk": "^0.27.3",
21 | "@anthropic-ai/vertex-sdk": "^0.4.1",
22 | "@azure/identity": "^4.4.1",
23 | "@google/generative-ai": "^0.20.0",
24 | "cohere-ai": "^7.14.0",
25 | "hono": "^4.6.3",
26 | "jose": "^5.9.3",
27 | "lodash-es": "^4.17.21",
28 | "mime": "^4.0.7",
29 | "openai": "^5.0.1",
30 | "serialize-error": "^11.0.3",
31 | "zod": "^3.23.8"
32 | },
33 | "devDependencies": {
34 | "@cloudflare/workers-types": "^4.20240925.0",
35 | "@langchain/anthropic": "^0.3.3",
36 | "@liuli-util/prettier-standard-config": "^0.3.0",
37 | "@types/lodash-es": "^4.17.12",
38 | "dotenv": "^16.5.0",
39 | "google-auth-library": "^9.14.1",
40 | "lint-staged": "^16.1.0",
41 | "prettier": "^3.5.3",
42 | "simple-git-hooks": "^2.13.0",
43 | "vite": "^5.4.8",
44 | "vitest": "^2.1.1",
45 | "wrangler": "^4.18.0",
46 | "zx": "^8.1.8"
47 | },
48 | "packageManager": "pnpm@10.5.2+sha512.da9dc28cd3ff40d0592188235ab25d3202add8a207afbedc682220e4a0029ffbff4562102b9e6e46b4e3f9e8bd53e6d05de48544b0c57d4b0179e22c76d1199b"
49 | }
50 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeAll, beforeEach, describe, expect, it } from 'vitest'
2 | import app from '..'
3 | import OpenAI from 'openai'
4 | import { omit, pick } from 'lodash-es'
5 | import { AnthropicVertex } from '@anthropic-ai/vertex-sdk'
6 | import { GoogleAuth } from 'google-auth-library'
7 | import { TextBlock } from '@anthropic-ai/sdk/resources/messages.mjs'
8 | import { anthropic } from '../llm/anthropic'
9 |
10 | const MOCK_ENV = {
11 | API_KEY: import.meta.env.VITE_API_KEY,
12 |
13 | OPENAI_API_KEY: import.meta.env.VITE_OPENAI_API_KEY,
14 | VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL,
15 | VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY,
16 | VERTEX_ANTROPIC_REGION: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
17 | VERTEX_ANTROPIC_PROJECTID: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
18 | ANTROPIC_API_KEY: import.meta.env.VITE_ANTROPIC_API_KEY,
19 | }
20 |
21 | let mock: OpenAI
22 | beforeAll(() => {
23 | mock = new OpenAI({
24 | apiKey: import.meta.env.VITE_API_KEY,
25 | fetch: async (_url, init) => {
26 | return app.request('/v1/chat/completions', { method: 'POST', ...init }, MOCK_ENV)
27 | },
28 | })
29 | })
30 |
31 | describe('invoke', () => {
32 | async function invokeOpenAI(chat: OpenAI, model: string) {
33 | return await chat.chat.completions.create({
34 | model,
35 | temperature: 0,
36 | messages: [{ role: 'user', content: 'Hello!' }],
37 | })
38 | }
39 | describe('openai api', () => {
40 | let origin: OpenAI
41 | beforeEach(() => {
42 | origin = new OpenAI({
43 | apiKey: import.meta.env.VITE_OPENAI_API_KEY,
44 | })
45 | })
46 | it('call openai invoke function', async () => {
47 | const [r1, r2] = await Promise.all([invokeOpenAI(origin, 'gpt-4o-mini'), invokeOpenAI(mock, 'gpt-4o-mini')])
48 | expect(r1).not.undefined
49 | expect(r2).not.undefined
50 | expect(omit(r1, 'created', 'id', 'system_fingerprint')).deep.equal(
51 | omit(r2, 'created', 'id', 'system_fingerprint'),
52 | )
53 | })
54 | })
55 |
56 | describe('vertex api', () => {
57 | let origin: AnthropicVertex
58 | beforeEach(() => {
59 | origin = new AnthropicVertex({
60 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
61 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
62 | googleAuth: new GoogleAuth({
63 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
64 | scopes: ['https://www.googleapis.com/auth/cloud-platform'],
65 | credentials: {
66 | type: 'service_account',
67 | client_email: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL,
68 | private_key: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY,
69 | },
70 | }),
71 | })
72 | })
73 | it('call vertex invoke function', async () => {
74 | const [r1, r2] = await Promise.all([
75 | origin.messages.create({
76 | model: 'claude-3-5-sonnet@20240620',
77 | max_tokens: 1000,
78 | temperature: 0,
79 | messages: [{ role: 'user', content: 'Hello!' }],
80 | }),
81 | invokeOpenAI(mock, 'claude-3-5-sonnet@20240620'),
82 | ])
83 | expect(r1).not.undefined
84 | expect(r2).not.undefined
85 | // console.log('r1: ', r1)
86 | // console.log('r2: ', r2)
87 | expect((r1.content[0] as TextBlock).text).equal(r2.choices[0].message.content)
88 | expect(r1.model).equal(r2.model)
89 | expect({
90 | prompt_tokens: r1.usage.input_tokens,
91 | completion_tokens: r1.usage.output_tokens,
92 | total_tokens: r1.usage.input_tokens + r1.usage.output_tokens,
93 | }).deep.equal(r2.usage)
94 | }, 10_000)
95 |
96 | it('call vertex-ai claude 3 haiku', async () => {
97 | const r = await invokeOpenAI(mock, 'claude-3-haiku@20240307')
98 | expect(r.model).eq('claude-3-haiku-20240307')
99 | })
100 | })
101 | })
102 |
103 | describe('stream', () => {
104 | async function streamOpenAI(chat: OpenAI, model: string) {
105 | const stream = await chat.chat.completions.create({
106 | model: model,
107 | temperature: 0,
108 | messages: [{ role: 'user', content: 'Hello!' }],
109 | stream: true,
110 | stream_options: {
111 | include_usage: true,
112 | },
113 | })
114 | const res: OpenAI.Chat.Completions.ChatCompletionChunk[] = []
115 | for await (const it of stream) {
116 | res.push(it)
117 | }
118 | return res
119 | }
120 | describe('openai api', () => {
121 | let origin: OpenAI
122 | beforeEach(() => {
123 | origin = new OpenAI({
124 | apiKey: import.meta.env.VITE_OPENAI_API_KEY,
125 | })
126 | })
127 | it('call openai stream function', async () => {
128 | const [r1, r2] = await Promise.all([streamOpenAI(origin, 'gpt-4o-mini'), streamOpenAI(mock, 'gpt-4o-mini')])
129 | // console.log(JSON.stringify(r1, null, 2))
130 | const f = (it: OpenAI.Chat.Completions.ChatCompletionChunk) => omit(it, 'created', 'id', 'system_fingerprint')
131 | // console.log(JSON.stringify(r2, null, 2))
132 | expect(r1.map(f)).deep.equal(r2.map(f))
133 | })
134 | })
135 |
136 | describe('vertex api', () => {
137 | let client: AnthropicVertex
138 | beforeEach(() => {
139 | client = new AnthropicVertex({
140 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
141 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
142 | googleAuth: new GoogleAuth({
143 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
144 | scopes: ['https://www.googleapis.com/auth/cloud-platform'],
145 | credentials: {
146 | type: 'service_account',
147 | client_email: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL,
148 | private_key: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY,
149 | },
150 | }),
151 | })
152 | })
153 |
154 | it('call vertex stream function', async () => {
155 | const [r1, r2] = await Promise.all([
156 | client.messages.stream({
157 | model: 'claude-3-5-sonnet@20240620',
158 | max_tokens: 1000,
159 | temperature: 0,
160 | messages: [{ role: 'user', content: 'Hello!' }],
161 | stream: true,
162 | }),
163 | streamOpenAI(mock, 'claude-3-5-sonnet@20240620'),
164 | ])
165 | const message = await r1.finalMessage()
166 | const usage = r2.find((it) => it.usage)!.usage!
167 | const content = r2.map((it) => it.choices[0]?.delta.content ?? '').join('')
168 | expect((message.content[0] as TextBlock).text).equal(content)
169 | expect(usage.prompt_tokens).equal(message.usage.input_tokens)
170 | expect(usage.completion_tokens).equal(message.usage.output_tokens)
171 | })
172 | })
173 | })
174 |
175 | describe('list models', async () => {
176 | it('no api key', async () => {
177 | const r = (await (
178 | await app.request(
179 | '/v1/models',
180 | {
181 | headers: { Authorization: 'Bearer ' + import.meta.env.VITE_API_KEY },
182 | },
183 | pick(MOCK_ENV, 'API_KEY'),
184 | )
185 | ).json()) as OpenAI.Models.ModelsPage
186 | expect(r.data).empty
187 | })
188 | it('anthropic api key', async () => {
189 | const r = (await (
190 | await app.request(
191 | '/v1/models',
192 | {
193 | headers: {
194 | Authorization: 'Bearer ' + import.meta.env.VITE_API_KEY,
195 | },
196 | },
197 | pick(MOCK_ENV, 'API_KEY', 'ANTROPIC_API_KEY'),
198 | )
199 | ).json()) as OpenAI.Models.ModelsPage
200 | expect(r.data.map((it) => it.id)).deep.eq(anthropic(MOCK_ENV).supportModels)
201 | })
202 | it('openai api key', async () => {
203 | const client = new OpenAI({
204 | apiKey: import.meta.env.VITE_API_KEY,
205 | fetch: async (_url, init) => {
206 | return app.request('/v1/models', init, MOCK_ENV)
207 | },
208 | })
209 | const r = await client.models.list()
210 | expect(r.data).not.empty
211 | })
212 | })
213 |
--------------------------------------------------------------------------------
/src/api/common.ts:
--------------------------------------------------------------------------------
1 | import { openai } from '../llm/openai'
2 | import { anthropic, anthropicVertex } from '../llm/anthropic'
3 | import { google } from '../llm/google'
4 | import { deepseek } from '../llm/deepseek'
5 | import { moonshot } from '../llm/moonshot'
6 | import { lingyiwanwu } from '../llm/lingyiwanwu'
7 | import { groq } from '../llm/groq'
8 | import { auzreOpenAI } from '../llm/azure'
9 | import { cohere } from '../llm/cohere'
10 | import { bailian } from '../llm/bailian'
11 | import { ollama } from '../llm/ollama'
12 | import { grok } from '../llm/grok'
13 | import { openrouter } from '../llm/openrouter'
14 |
15 | // --- getModels: Lists all REAL, configured backend providers ---
16 | export function getModels(env: Record) {
17 | return [
18 | openai(env),
19 | anthropic(env),
20 | anthropicVertex(env),
21 | google(env),
22 | deepseek(env),
23 | moonshot(env),
24 | lingyiwanwu(env),
25 | groq(env),
26 | auzreOpenAI(env),
27 | cohere(env),
28 | bailian(env),
29 | ollama(env),
30 | grok(env),
31 | openrouter(env),
32 | ].filter((it) => it.requiredEnv.every((it) => it in env))
33 | }
34 |
--------------------------------------------------------------------------------
/src/api/ollama/__test__/index.test.ts:
--------------------------------------------------------------------------------
1 | import { describe, expect, it } from 'vitest'
2 | import app from '../../../index'
3 | import { pick } from 'lodash-es'
4 | import OpenAI from 'openai'
5 |
6 | const MOCK_ENV = {
7 | API_KEY: import.meta.env.VITE_API_KEY,
8 | GOOGLE_GEN_AI_API_KEY: import.meta.env.VITE_GOOGLE_GEN_AI_API_KEY,
9 | }
10 |
11 | describe('list models', async () => {
12 | it('no right api key', async () => {
13 | const r = (await (
14 | await app.request(
15 | 'ollama/xxx/v1/api/tags',
16 | {
17 | headers: {},
18 | },
19 | pick(MOCK_ENV, 'API_KEY'),
20 | )
21 | ).json()) as OpenAI.Models.ModelsPage
22 |
23 | expect(JSON.stringify(r)).eq('{"error":"Unauthorized"}')
24 | })
25 |
26 | it('gemini api key', async () => {
27 | const r = (await (
28 | await app.request(
29 | 'ollama/123456/v1/api/tags',
30 | {
31 | headers: {},
32 | },
33 | pick(MOCK_ENV, 'API_KEY'),
34 | )
35 | ).json()) as any
36 |
37 | expect(r.models).toEqual([])
38 | })
39 | })
40 |
--------------------------------------------------------------------------------
/src/api/ollama/index.ts:
--------------------------------------------------------------------------------
1 | import { Context, Hono } from 'hono'
2 | import { Bindings } from '../../index'
3 | import OpenAI from 'openai'
4 | import { getModels } from '../common'
5 | import { streamSSE } from 'hono/streaming'
6 |
7 | export function ollamaRouter(): Hono<{ Bindings: Bindings }> {
8 | const app = new Hono<{
9 | Bindings: Bindings
10 | }>().basePath('/:apiKey')
11 |
12 | app.use('*', async (c, next) => {
13 | const apiKey = c.req.param('apiKey')
14 |
15 | if (!c.env.API_KEY) {
16 | return c.json({ error: 'Unauthorized' }, 401)
17 | }
18 |
19 | if (apiKey !== c.env.API_KEY) {
20 | return c.json({ error: 'Unauthorized' }, 401)
21 | }
22 | return next() // Proceed only if authorized
23 | })
24 |
25 | // 我也不知道hono在这里怎么路由的。。。。都加肯定对
26 | app.get('/v1/', async (c) => {
27 | return c.text('Ollama is running')
28 | })
29 | app.get('/v1', async (c) => {
30 | return c.text('Ollama is running')
31 | })
32 |
33 | app.post('/v1/api/chat', completions)
34 |
35 | app.get('/v1/api/tags', models)
36 |
37 | return app
38 | }
39 |
40 | async function completions(c: Context<{ Bindings: Bindings }>) {
41 | const req = (await c.req.json()) as
42 | | OpenAI.ChatCompletionCreateParamsNonStreaming
43 | | OpenAI.ChatCompletionCreateParamsStreaming
44 |
45 | const list = getModels(c.env as any)
46 | const llm = list.find((it) => it.supportModels.includes(req.model))
47 | if (!llm) {
48 | return c.json({ error: `Model ${req.model} not supported` }, 400)
49 | }
50 | // console.log(req, llm.name)
51 | if (req.stream) {
52 | const abortController = new AbortController()
53 | return streamSSE(
54 | c,
55 | async (stream) => {
56 | stream.onAbort(() => abortController.abort())
57 | for await (const it of llm.stream(req, abortController.signal)) {
58 | stream.write(JSON.stringify(convertOpenaiChunkToOllama(it)) + '\n')
59 | }
60 | },
61 | async (err, stream) => {
62 | await stream.writeSSE({
63 | data:
64 | JSON.stringify({
65 | error: err.message,
66 | }) + '\n',
67 | })
68 | return stream.close()
69 | },
70 | )
71 | }
72 | return c.json(convertOpenaiToOllama(await llm?.invoke(req)))
73 | }
74 |
75 | async function models(c: Context<{ Bindings: Bindings }>) {
76 | return c.json({
77 | models: getModels(c.env as any).flatMap((it) => {
78 | return it.supportModels.map((model) => ({
79 | name: model,
80 | model: model,
81 | details: {},
82 | created: Math.floor(Date.now() / 1000),
83 | modified_at: Math.floor(Date.now() / 1000),
84 | }))
85 | }),
86 | })
87 | }
88 |
89 | function convertOpenaiChunkToOllama(req: OpenAI.ChatCompletionChunk) {
90 | return {
91 | model: req.model,
92 | created_at: new Date(req.created).toISOString(),
93 | message: {
94 | role: 'assistant',
95 | content: req.choices[0].delta?.content,
96 | tool_calls: req.choices[0].delta?.tool_calls,
97 | },
98 | done_reason: req.choices[0].finish_reason,
99 | done: req.choices[0].finish_reason === 'stop',
100 | prompt_eval_count: req.usage?.prompt_tokens,
101 | eval_count: req.usage?.completion_tokens,
102 | }
103 | }
104 |
105 | function convertOpenaiToOllama(req: OpenAI.ChatCompletion) {
106 | return {
107 | model: req.model,
108 | created_at: new Date(req.created * 1000).toISOString(),
109 | message: {
110 | role: 'assistant',
111 | content: req.choices[0].message.content,
112 | tool_calls: req.choices[0].message.tool_calls,
113 | },
114 | done_reason: req.choices[0].finish_reason,
115 | done: req.choices[0].finish_reason === 'stop',
116 | prompt_eval_count: req.usage?.prompt_tokens,
117 | eval_count: req.usage?.completion_tokens,
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/api/openai/index.ts:
--------------------------------------------------------------------------------
1 | import { Context, Hono } from 'hono'
2 | import { Bindings } from '../../index'
3 | import OpenAI from 'openai'
4 | import { getModels } from '../common'
5 | import { streamSSE } from 'hono/streaming'
6 |
7 | export function openAiRouter(): Hono<{
8 | Bindings: Bindings
9 | }> {
10 | const app = new Hono<{
11 | Bindings: Bindings
12 | }>()
13 |
14 | app
15 | .options('/chat/completions', async (c) => {
16 | return c.json({ body: 'ok' })
17 | })
18 | .use('*', async (c, next) => {
19 | if (!c.env.API_KEY) {
20 | return c.json({ error: 'Unauthorized' }, 401)
21 | }
22 | if (`Bearer ${c.env.API_KEY}` !== c.req.header('Authorization')) {
23 | return c.json({ error: 'Unauthorized' }, 401)
24 | }
25 | return next()
26 | })
27 | .post('/chat/completions', completions)
28 | .get('/models', models)
29 |
30 | return app
31 | }
32 |
33 | async function completions(c: Context<{ Bindings: Bindings }>) {
34 | const req = (await c.req.json()) as
35 | | OpenAI.ChatCompletionCreateParamsNonStreaming
36 | | OpenAI.ChatCompletionCreateParamsStreaming
37 | const list = getModels(c.env as any)
38 | const llm = list.find((it) => it.supportModels.includes(req.model))
39 | if (!llm) {
40 | return c.json({ error: `Model ${req.model} not supported` }, 400)
41 | }
42 | if (req.stream) {
43 | const abortController = new AbortController()
44 | return streamSSE(
45 | c,
46 | async (stream) => {
47 | stream.onAbort(() => abortController.abort())
48 | for await (const it of llm.stream(req, abortController.signal)) {
49 | stream.writeSSE({ data: JSON.stringify(it) })
50 | }
51 | },
52 | async (err, stream) => {
53 | await stream.writeSSE({
54 | data: JSON.stringify({
55 | error: err.message,
56 | }),
57 | })
58 | return stream.close()
59 | },
60 | )
61 | }
62 | return c.json(await llm?.invoke(req))
63 | }
64 |
65 | async function models(c: Context<{ Bindings: Bindings }>) {
66 | return c.json({
67 | object: 'list',
68 | data: getModels(c.env as any).flatMap((it) =>
69 | it.supportModels.map(
70 | (model) =>
71 | ({
72 | id: model,
73 | object: 'model',
74 | owned_by: it.name,
75 | created: Math.floor(Date.now() / 1000),
76 | }) as OpenAI.Models.Model,
77 | ),
78 | ),
79 | } as OpenAI.Models.ModelsPage)
80 | }
81 |
--------------------------------------------------------------------------------
/src/claude/__tests__/authenticate.test.ts:
--------------------------------------------------------------------------------
1 | import { AnthropicVertexWeb } from '../web'
2 | import { authenticate } from '../authenticate'
3 | import { it, expect } from 'vitest'
4 |
5 | it('should authenticate', async () => {
6 | const token = await authenticate({
7 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
8 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
9 | })
10 | expect(token).toBeDefined()
11 | })
12 |
13 | it('should call anthropic vertex', async () => {
14 | const token = await authenticate({
15 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
16 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
17 | })
18 | const client = new AnthropicVertexWeb({
19 | accessToken: token.access_token,
20 | region: 'us-east5',
21 | projectId: 'development-334207',
22 | })
23 | const response = await client.messages.create({
24 | messages: [{ role: 'user', content: 'Hello, world!' }],
25 | model: 'claude-3-5-sonnet@20240620',
26 | max_tokens: 1000,
27 | })
28 | console.log(response)
29 | })
30 |
31 | function buildUrl({ region, projectId, model }: { region: string; projectId: string; model: string }) {
32 | return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/anthropic/models/${model}:streamRawPredict`
33 | }
34 |
35 | it('should authenticate on edge runtime', async () => {
36 | const token = await authenticate({
37 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
38 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
39 | })
40 | expect(token).toBeDefined()
41 | const url = buildUrl({
42 | model: 'claude-3-5-sonnet@20240620',
43 | projectId: 'development-334207',
44 | region: 'us-east5',
45 | })
46 | const response = await fetch(url, {
47 | method: 'POST',
48 | headers: {
49 | 'Content-Type': 'application/json',
50 | Authorization: `Bearer ${token.access_token}`,
51 | },
52 | body: JSON.stringify({
53 | anthropic_version: 'vertex-2023-10-16',
54 | messages: [{ role: 'user', content: '你是?' }],
55 | max_tokens: 100,
56 | stream: false,
57 | }),
58 | })
59 | console.log(await response.text())
60 | })
61 |
--------------------------------------------------------------------------------
/src/claude/__tests__/web.test.ts:
--------------------------------------------------------------------------------
1 | import { expect, it } from 'vitest'
2 | import { AnthropicVertexWeb } from '../web'
3 | import { AnthropicVertex } from '@anthropic-ai/vertex-sdk'
4 | import { authenticate } from '../authenticate'
5 | import { omit } from 'lodash-es'
6 | import { ChatAnthropic } from '@langchain/anthropic'
7 | import { GoogleAuth } from 'google-auth-library'
8 |
9 | it('should call anthropic vertex with access token', async () => {
10 | const token = await authenticate({
11 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
12 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
13 | })
14 | const client = new AnthropicVertexWeb({
15 | region: 'us-east5',
16 | projectId: 'development-334207',
17 | accessToken: token.access_token,
18 | })
19 | const response = await client.messages.create({
20 | messages: [{ role: 'user', content: 'Hello, world!' }],
21 | model: 'claude-3-5-sonnet@20240620',
22 | max_tokens: 1000,
23 | })
24 | console.log(response)
25 | expect(response).toBeDefined()
26 | })
27 |
28 | // 验证自定义的 anthropic vertex client 与原生的 client 一致
29 | it('should call Custom Client and Origin Client', async () => {
30 | const token = await authenticate({
31 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
32 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
33 | })
34 | const custom = new AnthropicVertexWeb({
35 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
36 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
37 | accessToken: token.access_token,
38 | })
39 | const origin = new AnthropicVertex({
40 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
41 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
42 | accessToken: token.access_token,
43 | })
44 | function call(client: AnthropicVertexWeb | AnthropicVertex) {
45 | return client.messages.create({
46 | messages: [{ role: 'user', content: 'Hello!' }],
47 | model: 'claude-3-5-sonnet@20240620',
48 | max_tokens: 1000,
49 | temperature: 0,
50 | })
51 | }
52 | const [r1, r2] = await Promise.all([call(custom), call(origin)])
53 | expect(r1).not.undefined
54 | expect(r2).not.undefined
55 | expect(omit(r1, 'id')).deep.equal(omit(r2, 'id'))
56 | }, 20_000)
57 |
58 | it('Call Anthropic Vertex on nodejs', async () => {
59 | const client = new AnthropicVertex({
60 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
61 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
62 | googleAuth: new GoogleAuth({
63 | credentials: {
64 | client_email: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
65 | private_key: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
66 | },
67 | scopes: ['https://www.googleapis.com/auth/cloud-platform'],
68 | }),
69 | })
70 | const chat = new ChatAnthropic({
71 | apiKey: 'test',
72 | model: 'claude-3-5-sonnet@20240620',
73 | createClient: (() => client) as any,
74 | })
75 | const response = await chat.invoke([['human', 'Hello!']])
76 | console.log(response)
77 | expect(response).not.undefined
78 | })
79 | it('Call Anthropic Vertex on edge runtime', async () => {
80 | const token = await authenticate({
81 | clientEmail: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL!,
82 | privateKey: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY!,
83 | })
84 | const client = new AnthropicVertexWeb({
85 | region: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
86 | projectId: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
87 | accessToken: token.access_token,
88 | })
89 | const chat = new ChatAnthropic({
90 | apiKey: 'test',
91 | model: 'claude-3-5-sonnet@20240620',
92 | createClient: (() => client) as any,
93 | })
94 | const response = await chat.invoke([['human', 'Hello!']])
95 | console.log(response)
96 | expect(response).not.undefined
97 | }, 10_000)
98 |
--------------------------------------------------------------------------------
/src/claude/authenticate.ts:
--------------------------------------------------------------------------------
1 | import { SignJWT, importPKCS8 } from 'jose'
2 |
3 | type Token = {
4 | access_token: string
5 | expires_in: number
6 | token_type: string
7 | }
8 |
9 | type TokenWithExpiration = Token & {
10 | expires_at: number
11 | }
12 |
13 | let token: TokenWithExpiration | null = null
14 |
15 | async function createToken(options: { clientEmail: string; privateKey: string }) {
16 | const rawPrivateKey = options.privateKey.replace(/\\n/g, '\n')
17 | const privateKey = await importPKCS8(rawPrivateKey, 'RS256')
18 |
19 | const payload = {
20 | iss: options.clientEmail,
21 | scope: 'https://www.googleapis.com/auth/cloud-platform',
22 | aud: 'https://www.googleapis.com/oauth2/v4/token',
23 | exp: Math.floor(Date.now() / 1000) + 60 * 60,
24 | iat: Math.floor(Date.now() / 1000),
25 | }
26 | const token = await new SignJWT(payload)
27 | .setProtectedHeader({ alg: 'RS256' })
28 | .setIssuedAt()
29 | .setIssuer(options.clientEmail)
30 | .setAudience('https://www.googleapis.com/oauth2/v4/token')
31 | .setExpirationTime('1h')
32 | .sign(privateKey)
33 |
34 | // Form data for the token request
35 | const form = {
36 | grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
37 | assertion: token,
38 | }
39 |
40 | // Make the token request
41 | const tokenResponse = await fetch('https://www.googleapis.com/oauth2/v4/token', {
42 | method: 'POST',
43 | body: JSON.stringify(form),
44 | headers: { 'Content-Type': 'application/json' },
45 | })
46 |
47 | const json = (await tokenResponse.json()) as Token
48 |
49 | return {
50 | ...json,
51 | expires_at: Math.floor(Date.now() / 1000) + json.expires_in,
52 | }
53 | }
54 |
55 | export async function authenticate(options: { clientEmail: string; privateKey: string }): Promise {
56 | if (!options.clientEmail || !options.privateKey) {
57 | throw new Error('clientEmail and privateKey are required')
58 | }
59 | if (token === null) {
60 | token = await createToken(options)
61 | } else if (token.expires_at < Math.floor(Date.now() / 1000)) {
62 | token = await createToken(options)
63 | }
64 | return token
65 | }
66 |
--------------------------------------------------------------------------------
/src/claude/web.ts:
--------------------------------------------------------------------------------
1 | import * as Core from '@anthropic-ai/sdk/core'
2 | import * as Resources from '@anthropic-ai/sdk/resources/index'
3 | import * as API from '@anthropic-ai/sdk/index'
4 | import { type RequestInit } from '@anthropic-ai/sdk/_shims/index'
5 | import { authenticate } from './authenticate'
6 |
7 | const DEFAULT_VERSION = 'vertex-2023-10-16'
8 |
9 | export type ClientOptions = Omit & {
10 | region?: string | null | undefined
11 | projectId?: string | null | undefined
12 | accessToken?: string | null | undefined
13 | clientEmail?: string | null | undefined
14 | privateKey?: string | null | undefined
15 | }
16 |
17 | export class AnthropicVertexWeb extends Core.APIClient {
18 | region: string
19 | projectId: string | null
20 | accessToken: string | null
21 |
22 | private _options: ClientOptions
23 |
24 | constructor({
25 | baseURL = Core.readEnv('ANTHROPIC_VERTEX_BASE_URL'),
26 | region = Core.readEnv('CLOUD_ML_REGION') ?? null,
27 | projectId = Core.readEnv('ANTHROPIC_VERTEX_PROJECT_ID') ?? null,
28 | accessToken = Core.readEnv('ANTHROPIC_VERTEX_ACCESS_TOKEN') ?? null,
29 | clientEmail = Core.readEnv('ANTHROPIC_VERTEX_CLIENT_EMAIL') ?? null,
30 | privateKey = Core.readEnv('ANTHROPIC_VERTEX_PRIVATE_KEY') ?? null,
31 | ...opts
32 | }: ClientOptions = {}) {
33 | if (!region) {
34 | throw new Error(
35 | 'No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.',
36 | )
37 | }
38 |
39 | const options: ClientOptions = {
40 | ...opts,
41 | baseURL: baseURL || `https://${region}-aiplatform.googleapis.com/v1`,
42 | clientEmail,
43 | privateKey,
44 | }
45 |
46 | super({
47 | baseURL: options.baseURL!,
48 | timeout: options.timeout ?? 600000 /* 10 minutes */,
49 | httpAgent: options.httpAgent,
50 | maxRetries: options.maxRetries,
51 | fetch: options.fetch,
52 | })
53 | this._options = options
54 |
55 | this.region = region
56 | this.projectId = projectId
57 | this.accessToken = accessToken
58 | }
59 |
60 | messages: Resources.Messages = new Resources.Messages(this)
61 |
62 | protected override defaultQuery(): Core.DefaultQuery | undefined {
63 | return this._options.defaultQuery
64 | }
65 |
66 | protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
67 | return {
68 | ...super.defaultHeaders(opts),
69 | ...this._options.defaultHeaders,
70 | }
71 | }
72 |
73 | protected override async prepareOptions(options: Core.FinalRequestOptions): Promise {
74 | if (!this.accessToken) {
75 | if (!this._options.clientEmail || !this._options.privateKey) {
76 | throw new Error(
77 | 'No clientEmail or privateKey was provided. Set it in the constructor or use the ANTHROPIC_VERTEX_CLIENT_EMAIL and ANTHROPIC_VERTEX_PRIVATE_KEY environment variables.',
78 | )
79 | }
80 | this.accessToken = (
81 | await authenticate({
82 | clientEmail: this._options.clientEmail,
83 | privateKey: this._options.privateKey,
84 | })
85 | ).access_token
86 | }
87 |
88 | options.headers = {
89 | ...options.headers,
90 | Authorization: `Bearer ${this.accessToken}`,
91 | 'x-goog-user-project': this.projectId,
92 | }
93 | }
94 |
95 | override buildRequest(options: Core.FinalRequestOptions): {
96 | req: RequestInit
97 | url: string
98 | timeout: number
99 | } {
100 | if (Core.isObj(options.body)) {
101 | if (!options.body['anthropic_version']) {
102 | options.body['anthropic_version'] = DEFAULT_VERSION
103 | }
104 | }
105 |
106 | if (options.path === '/v1/messages' && options.method === 'post') {
107 | if (!this.projectId) {
108 | throw new Error(
109 | 'No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.',
110 | )
111 | }
112 |
113 | if (!Core.isObj(options.body)) {
114 | throw new Error('Expected request body to be an object for post /v1/messages')
115 | }
116 |
117 | const model = options.body['model']
118 | options.body['model'] = undefined
119 |
120 | const stream = options.body['stream'] ?? false
121 |
122 | const specifier = stream ? 'streamRawPredict' : 'rawPredict'
123 |
124 | options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`
125 | }
126 |
127 | return super.buildRequest(options)
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { Hono } from 'hono'
2 | import { serializeError } from 'serialize-error'
3 | import { HTTPException } from 'hono/http-exception'
4 | import { cors } from 'hono/cors'
5 | import { openAiRouter } from './api/openai'
6 | import { ollamaRouter } from './api/ollama'
7 |
8 | export interface Bindings {
9 | API_KEY: string
10 | OPENAI_API_KEY: string
11 | }
12 |
13 | const app = new Hono<{
14 | Bindings: Bindings
15 | }>()
16 | /*
17 | curl https://api.openai.com/v1/chat/completions \
18 | -H "Content-Type: application/json" \
19 | -H "Authorization: Bearer $OPENAI_API_KEY" \
20 | -d '{
21 | "model": "gpt-4o-mini",
22 | "messages": [{"role": "user", "content": "Say this is a test!"}],
23 | "temperature": 0.7
24 | }'
25 | */
26 | .use(
27 | cors({
28 | origin: (_origin, c) => {
29 | return c.env.CORS_ORIGIN
30 | },
31 | }),
32 | )
33 | .use(async (c, next) => {
34 | await next()
35 | if (c.error) {
36 | throw new HTTPException((c.error as any)?.status ?? 500, {
37 | message: serializeError(c.error).message,
38 | })
39 | }
40 | })
41 |
42 | // 生成 openai chat 的代理,https://api.openai.com/v1/chat/completions
43 | app.route('v1', openAiRouter())
44 |
45 | // 生成 ollama chat 的代理
46 | app.route('/ollama', ollamaRouter())
47 |
48 | export default app
49 |
--------------------------------------------------------------------------------
/src/llm/anthropic.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeAll, expect, it } from 'vitest'
2 | import { anthropicVertex, getImageAsBase64, IAnthropicVertex } from './anthropic'
3 |
4 | let client: IAnthropicVertex
5 | beforeAll(() => {
6 | client = anthropicVertex({
7 | VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL,
8 | VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY: import.meta.env.VITE_VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY,
9 | VERTEX_ANTROPIC_REGION: import.meta.env.VITE_VERTEX_ANTROPIC_REGION,
10 | VERTEX_ANTROPIC_PROJECTID: import.meta.env.VITE_VERTEX_ANTROPIC_PROJECTID,
11 | })
12 | })
13 |
14 | it('image input', async () => {
15 | const res = await client.invoke({
16 | model: 'claude-3-5-sonnet@20240620',
17 | messages: [
18 | {
19 | role: 'user',
20 | content: [
21 | {
22 | type: 'text',
23 | text: 'Describe the image',
24 | },
25 | {
26 | type: 'image_url',
27 | image_url: {
28 | url: 'https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg',
29 | },
30 | },
31 | ],
32 | },
33 | ],
34 | })
35 | expect(res.choices[0].message.content).include('ant')
36 | }, 10_000)
37 |
38 | it('data url image input', async () => {
39 | const image = await getImageAsBase64(
40 | 'https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg',
41 | )
42 | const dataUri = `data:${image.media_type};base64,${image.data}`
43 | const res = await client.invoke({
44 | model: 'claude-3-5-sonnet@20240620',
45 | messages: [
46 | {
47 | role: 'user',
48 | content: [
49 | {
50 | type: 'text',
51 | text: 'Describe the image',
52 | },
53 | {
54 | type: 'image_url',
55 | image_url: { url: dataUri },
56 | },
57 | ],
58 | },
59 | ],
60 | })
61 | expect(res.choices[0].message.content).include('ant')
62 | }, 10_000)
63 |
--------------------------------------------------------------------------------
/src/llm/anthropic.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import type AnthropicTypes from '@anthropic-ai/sdk'
3 | import { AnthropicVertexWeb } from '../claude/web'
4 | import { IChat } from './base'
5 | import Anthropic from '@anthropic-ai/sdk'
6 | import { HTTPException } from 'hono/http-exception'
7 |
8 | export interface IAnthropicVertex extends IChat {
9 | parseRequest(req: OpenAI.ChatCompletionCreateParams): Promise
10 | parseResponse(resp: AnthropicTypes.Messages.Message): OpenAI.ChatCompletion
11 | }
12 |
13 | function convertToolChoice(
14 | tool_choice?: OpenAI.ChatCompletionToolChoiceOption,
15 | ): AnthropicTypes.MessageCreateParams['tool_choice'] | undefined {
16 | if (!tool_choice) {
17 | return
18 | }
19 | if (tool_choice === 'auto') {
20 | return {
21 | type: 'auto',
22 | }
23 | }
24 | if (tool_choice === 'required') {
25 | return {
26 | type: 'any',
27 | }
28 | }
29 | if (tool_choice === 'none') {
30 | return
31 | }
32 | return {
33 | type: 'tool',
34 | name: tool_choice.function.name,
35 | }
36 | }
37 |
38 | function arrayBufferToBase64(buffer: ArrayBuffer): string {
39 | let binary = ''
40 | const bytes = new Uint8Array(buffer)
41 | for (let i = 0; i < bytes.byteLength; i++) {
42 | binary += String.fromCharCode(bytes[i])
43 | }
44 | return btoa(binary)
45 | }
46 |
47 | export async function getImageAsBase64(imageUrl: string): Promise<{
48 | media_type: string
49 | data: string
50 | }> {
51 | // 检查是否已经是 data URL
52 | if (imageUrl.startsWith('data:')) {
53 | const [header, data] = imageUrl.split(',')
54 | const media_type = header.split(':')[1].split(';')[0]
55 | return { media_type, data }
56 | }
57 | // 如果不是 data URL,则按原方法处理
58 | const response = await fetch(imageUrl)
59 | const arrayBuffer = await response.arrayBuffer()
60 | // 将 ArrayBuffer 转换为 base64
61 | const base64 = arrayBufferToBase64(arrayBuffer)
62 | return {
63 | media_type: response.headers.get('content-type') || 'image/jpeg',
64 | data: base64,
65 | }
66 | }
67 |
68 | async function convertMessages(
69 | messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
70 | ): Promise {
71 | return Promise.all(
72 | messages.map(async (it) => {
73 | if (!it.content) {
74 | throw new HTTPException(400, {
75 | message: 'content is required',
76 | })
77 | }
78 | if (typeof it.content === 'string') {
79 | return it as AnthropicTypes.MessageParam
80 | }
81 | return {
82 | role: it.role,
83 | content: await Promise.all(
84 | it.content.map(async (it) => {
85 | if (it.type === 'text') {
86 | return {
87 | type: 'text',
88 | text: it.text,
89 | } as AnthropicTypes.TextBlockParam
90 | }
91 | if (it.type === 'image_url') {
92 | return {
93 | type: 'image',
94 | source: {
95 | type: 'base64',
96 | ...(await getImageAsBase64(it.image_url.url)),
97 | },
98 | } as AnthropicTypes.ImageBlockParam
99 | }
100 | throw new HTTPException(400, {
101 | message: 'Unsupported message content type ' + it.type,
102 | })
103 | }),
104 | ),
105 | } as AnthropicTypes.MessageParam
106 | }),
107 | )
108 | }
109 |
110 | function getModelMaxTokens(model: string): number {
111 | if (model.startsWith('claude-3-')) {
112 | return 4096
113 | }
114 | return 8192
115 | }
116 |
117 | export function anthropicBase(
118 | createClient: () => AnthropicTypes,
119 | ): Omit {
120 | return {
121 | name: 'vertex-anthropic',
122 | async parseRequest(req) {
123 | let r: AnthropicTypes.MessageCreateParamsNonStreaming = {
124 | stream: false,
125 | stop_sequences: typeof req.stop === 'string' ? [req.stop] : Array.isArray(req.stop) ? req.stop : undefined,
126 | system: req.messages.find((it) => it.role === 'system')?.content,
127 | model: req.model,
128 | messages: await convertMessages(
129 | req.messages.filter((it) =>
130 | (['user', 'assistant'] as OpenAI.ChatCompletionMessageParam['role'][]).includes(it.role),
131 | ),
132 | ),
133 | max_tokens: req.max_completion_tokens ?? getModelMaxTokens(req.model),
134 | temperature: req.temperature!,
135 | metadata: {
136 | user_id: req.user,
137 | },
138 | tools: req.tools?.map(
139 | (it) =>
140 | ({
141 | name: it.function.name,
142 | description: it.function.description,
143 | input_schema: it.function.parameters,
144 | }) as AnthropicTypes.Tool,
145 | ),
146 | tool_choice: convertToolChoice(req.tool_choice),
147 | }
148 | if (!req.stream) {
149 | return r
150 | }
151 | return {
152 | ...r,
153 | stream: true,
154 | } as AnthropicTypes.MessageCreateParamsStreaming
155 | },
156 | parseResponse(resp) {
157 | return {
158 | id: resp.id,
159 | object: 'chat.completion',
160 | created: Math.floor(Date.now() / 1000),
161 | model: resp.model,
162 | usage: {
163 | prompt_tokens: resp.usage.input_tokens,
164 | completion_tokens: resp.usage.output_tokens,
165 | total_tokens: resp.usage.input_tokens + resp.usage.output_tokens,
166 | },
167 | choices: resp.content.map((it: AnthropicTypes.ContentBlock) => {
168 | return {
169 | index: 0,
170 | message: {
171 | role: 'assistant',
172 | content: it.type === 'text' ? it.text : undefined,
173 | refusal: null,
174 | tool_calls:
175 | it.type === 'text'
176 | ? undefined
177 | : [
178 | {
179 | id: it.id,
180 | type: 'function',
181 | function: {
182 | name: it.name,
183 | arguments: it.input,
184 | },
185 | },
186 | ],
187 | },
188 | finish_reason: 'stop',
189 | logprobs: null,
190 | }
191 | }),
192 | } as OpenAI.ChatCompletion
193 | },
194 | async invoke(req) {
195 | const client = createClient()
196 | return this.parseResponse(
197 | await client.messages.create((await this.parseRequest(req)) as AnthropicTypes.MessageCreateParamsNonStreaming),
198 | )
199 | },
200 | async *stream(req, signal) {
201 | const client = createClient()
202 | const stream = await client.messages.create({
203 | ...(await this.parseRequest(req)),
204 | stream: true,
205 | })
206 | signal.onabort = () => stream.controller.abort()
207 | const chunks: AnthropicTypes.Messages.RawMessageStreamEvent[] = []
208 | let start: AnthropicTypes.Messages.Message | undefined
209 | for await (const it of stream) {
210 | chunks.push(it)
211 | const fileds = () => ({
212 | id: start!.id,
213 | model: start!.model,
214 | object: 'chat.completion.chunk',
215 | created: Math.floor(Date.now() / 1000),
216 | })
217 | if (it.type === 'message_start') {
218 | start = it.message
219 | } else if (it.type === 'content_block_delta') {
220 | if (it.delta.type !== 'text_delta') {
221 | throw new Error('Unsupported delta type')
222 | }
223 | yield {
224 | ...fileds(),
225 | choices: [
226 | {
227 | index: it.index,
228 | delta: {
229 | content: it.delta.text,
230 | },
231 | },
232 | ],
233 | } as OpenAI.ChatCompletionChunk
234 | } else if (it.type === 'message_delta') {
235 | if (req.stream_options?.include_usage) {
236 | yield {
237 | ...fileds(),
238 | choices: [],
239 | usage: {
240 | prompt_tokens: start!.usage.input_tokens,
241 | completion_tokens: it!.usage.output_tokens,
242 | total_tokens: start!.usage.input_tokens + it!.usage.output_tokens,
243 | },
244 | } as OpenAI.ChatCompletionChunk
245 | } else {
246 | yield {
247 | ...fileds(),
248 | choices: [
249 | {
250 | index: 0,
251 | delta: {},
252 | finish_reason: 'stop',
253 | },
254 | ],
255 | } as OpenAI.ChatCompletionChunk
256 | }
257 | }
258 | }
259 | },
260 | }
261 | }
262 |
263 | export function anthropicVertex(env: Record): IAnthropicVertex {
264 | const createClient = () =>
265 | new AnthropicVertexWeb({
266 | clientEmail: env.VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL,
267 | privateKey: env.VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY,
268 | region: env.VERTEX_ANTROPIC_REGION,
269 | projectId: env.VERTEX_ANTROPIC_PROJECTID,
270 | })
271 | const r = anthropicBase(createClient as any) as IAnthropicVertex
272 | r.name = 'vertex-anthropic'
273 | r.requiredEnv = [
274 | 'VERTEX_ANTROPIC_GOOGLE_SA_CLIENT_EMAIL',
275 | 'VERTEX_ANTROPIC_GOOGLE_SA_PRIVATE_KEY',
276 | 'VERTEX_ANTROPIC_REGION',
277 | 'VERTEX_ANTROPIC_PROJECTID',
278 | ]
279 | r.supportModels = [
280 | 'claude-opus-4@20250514',
281 | 'claude-sonnet-4@20250514',
282 | 'claude-3-7-sonnet@20250219',
283 | 'claude-3-5-sonnet-v2@20241022',
284 | 'claude-3-5-haiku@20241022',
285 | 'claude-3-5-sonnet@20240620',
286 | 'claude-3-haiku@20240307',
287 | 'claude-3-opus@20240229',
288 | 'claude-3-sonnet@20240229',
289 | ]
290 | return r
291 | }
292 |
293 | export function anthropic(env: Record): IAnthropicVertex {
294 | const createClient = () => new Anthropic({ apiKey: env.ANTROPIC_API_KEY })
295 | const r = anthropicBase(createClient as any) as IAnthropicVertex
296 | r.name = 'anthropic'
297 | r.requiredEnv = ['ANTROPIC_API_KEY']
298 | r.supportModels = [
299 | 'claude-opus-4-20250514',
300 | 'claude-sonnet-4-20250514',
301 | 'claude-3-7-sonnet-20250219',
302 | 'claude-3-5-sonnet-20241022',
303 | 'claude-3-5-haiku-20241022',
304 | 'claude-3-5-sonnet-20240620',
305 | 'claude-3-opus-20240229',
306 | 'claude-3-sonnet-20240229',
307 | 'claude-3-haiku-20240307',
308 | ]
309 | return r
310 | }
311 |
--------------------------------------------------------------------------------
/src/llm/azure.test.ts:
--------------------------------------------------------------------------------
1 | import { expect, it } from 'vitest'
2 | import { auzreOpenAI } from './azure'
3 |
4 | it('azure', async () => {
5 | const llm = auzreOpenAI({
6 | AZURE_OPENAI_API_KEY: import.meta.env.VITE_AZURE_OPENAI_API_KEY,
7 | AZURE_OPENAI_ENDPOINT: import.meta.env.VITE_AZURE_OPENAI_ENDPOINT,
8 | AZURE_API_VERSION: import.meta.env.VITE_AZURE_API_VERSION,
9 | AZURE_DEPLOYMENT_MODELS: import.meta.env.VITE_AZURE_DEPLOYMENT_MODELS,
10 | })
11 | const res = await llm.invoke({
12 | model: 'azure/gpt-35-turbo',
13 | messages: [{ role: 'user', content: 'Hello!' }],
14 | temperature: 0,
15 | })
16 | expect(res.choices[0].message.content).not.undefined
17 | })
18 |
--------------------------------------------------------------------------------
/src/llm/azure.ts:
--------------------------------------------------------------------------------
1 | import { AzureOpenAI } from 'openai'
2 | import { openaiBase } from './openai'
3 |
4 | export function auzreOpenAI(env: Record) {
5 | // model -> deployment
6 | const map: Record = {}
7 | const r = openaiBase({
8 | createClient: (req) => {
9 | return new AzureOpenAI({
10 | apiKey: env.AZURE_OPENAI_API_KEY,
11 | endpoint: env.AZURE_OPENAI_ENDPOINT,
12 | apiVersion: env.AZURE_API_VERSION,
13 | deployment: map[req.model],
14 | })
15 | },
16 | pre: (req) => ({
17 | ...req,
18 | model: req.model.split('/')[1],
19 | stream: false,
20 | }),
21 | })
22 | r.name = 'azure-openai'
23 | r.requiredEnv = ['AZURE_OPENAI_API_KEY', 'AZURE_OPENAI_ENDPOINT', 'AZURE_API_VERSION', 'AZURE_DEPLOYMENT_MODELS']
24 | r.supportModels = (env.AZURE_DEPLOYMENT_MODELS ?? '').split(',').map((it) => {
25 | if (it.includes(':')) {
26 | const [model, deployment] = it.split(':')
27 | map[model] = deployment
28 | return `azure/${model}`
29 | }
30 | return `azure/${it}`
31 | })
32 | return r
33 | }
34 |
--------------------------------------------------------------------------------
/src/llm/bailian.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeEach, expect, it } from 'vitest'
2 | import { bailian } from './bailian'
3 | import OpenAI from 'openai'
4 | import { IChat } from './base'
5 | import { last } from 'lodash-es'
6 |
7 | let client: IChat
8 | beforeEach(() => {
9 | client = bailian({
10 | ALIYUN_BAILIAN_API_KEY: import.meta.env.VITE_ALIYUN_BAILIAN_API_KEY,
11 | })
12 | })
13 | it('invoke', async () => {
14 | const res = await client.invoke({
15 | model: 'qwen-max',
16 | messages: [{ role: 'user', content: '你是?' }],
17 | temperature: 0,
18 | })
19 | expect(res.choices[0].message.content).not.undefined
20 | })
21 | it('stream usage', async () => {
22 | const res = client.stream(
23 | {
24 | model: 'qwen-max',
25 | messages: [{ role: 'user', content: '你是?' }],
26 | temperature: 0,
27 | stream: true,
28 | },
29 | new AbortController().signal,
30 | )
31 | const r: OpenAI.Chat.Completions.ChatCompletionChunk[] = []
32 | for await (const chunk of res) {
33 | r.push(chunk)
34 | }
35 | const content = r.map((it) => it.choices[0]?.delta.content).join('')
36 | expect(last(r)!.usage).not.undefined
37 | expect(content).not.undefined
38 | })
39 |
--------------------------------------------------------------------------------
/src/llm/bailian.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { IChat } from './base'
3 | import { openaiBase } from './openai'
4 |
5 | export function bailian(env: Record): IChat {
6 | const r = openaiBase({
7 | createClient: () => {
8 | return new OpenAI({
9 | baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
10 | apiKey: env.ALIYUN_BAILIAN_API_KEY,
11 | })
12 | },
13 | })
14 | r.name = 'Bailian'
15 | r.supportModels = env.ALIYUN_BAILIAN_MODELS?.split(',').map((it) => it.trim()) ?? ['qwen-max']
16 | r.requiredEnv = ['ALIYUN_BAILIAN_API_KEY']
17 | return r
18 | }
19 |
--------------------------------------------------------------------------------
/src/llm/base.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ChatCompletionCreateParamsNonStreaming,
3 | ChatCompletion,
4 | ChatCompletionCreateParamsStreaming,
5 | ChatCompletionChunk,
6 | } from 'openai/resources/index.mjs'
7 |
8 | export interface IChat {
9 | name: string
10 | supportModels: string[]
11 | requiredEnv: string[]
12 | invoke(req: ChatCompletionCreateParamsNonStreaming): Promise
13 | stream(req: ChatCompletionCreateParamsStreaming, signal: AbortSignal): AsyncGenerator
14 | }
15 |
16 | export interface ChatEnv {
17 | [key: string]: string | undefined
18 | }
19 |
--------------------------------------------------------------------------------
/src/llm/cerebras.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { openaiBase } from './openai'
3 |
4 | export function cerebras(env: Record) {
5 | const map = {
6 | 'cerebras/llama-3.1-70b': 'llama-3-70b',
7 | 'cerebras/llama-3.1-8b': 'llama-3-8b',
8 | }
9 | const r = openaiBase({
10 | createClient: () =>
11 | new OpenAI({
12 | apiKey: env.CEREBRAS_API_KEY,
13 | baseURL: 'https://api.cerebras.ai/v1',
14 | }),
15 | pre(req) {
16 | req.model = map[req.model as keyof typeof map]
17 | return req
18 | },
19 | })
20 | r.name = 'cerebras'
21 | r.requiredEnv = ['CEREBRAS_API_KEY']
22 | r.supportModels = Object.keys(map)
23 | return r
24 | }
25 |
--------------------------------------------------------------------------------
/src/llm/cohere.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeEach, it, expect } from 'vitest'
2 | import { IChat } from './base'
3 | import { cohere } from './cohere'
4 | import OpenAI from 'openai'
5 | import { last } from 'lodash-es'
6 |
7 | let client: IChat
8 | beforeEach(() => {
9 | client = cohere({
10 | COHERE_API_KEY: import.meta.env.VITE_COHERE_API_KEY,
11 | })
12 | })
13 | it('invoke', async () => {
14 | const res = await client.invoke({
15 | model: 'command-r-plus',
16 | messages: [{ role: 'user', content: '你是?' }],
17 | temperature: 0,
18 | })
19 | console.log('converted: ', res)
20 | expect(res.choices[0].message.content).not.undefined
21 | })
22 |
23 | it('stream', async () => {
24 | const stream = client.stream(
25 | {
26 | model: 'command-r-plus',
27 | messages: [{ role: 'user', content: '你是?' }],
28 | temperature: 0,
29 | stream: true,
30 | },
31 | new AbortController().signal,
32 | )
33 | const chunks: OpenAI.ChatCompletionChunk[] = []
34 | for await (const chunk of stream) {
35 | chunks.push(chunk)
36 | }
37 | expect(chunks).not.empty
38 | const content = chunks.map((it) => it.choices[0]?.delta.content).join('')
39 | expect(content).not.empty
40 | expect(last(chunks)!.usage).not.undefined
41 | })
42 |
--------------------------------------------------------------------------------
/src/llm/cohere.ts:
--------------------------------------------------------------------------------
1 | import { last } from 'lodash-es'
2 | import { ChatEnv, IChat } from './base'
3 | import { Cohere, CohereClient } from 'cohere-ai'
4 | import OpenAI from 'openai'
5 |
6 | function roleOpenaiToCohere(role: OpenAI.Chat.Completions.ChatCompletionMessageParam['role']): Cohere.Message['role'] {
7 | switch (role) {
8 | case 'user':
9 | return 'USER'
10 | case 'assistant':
11 | return 'CHATBOT'
12 | case 'system':
13 | return 'SYSTEM'
14 | case 'tool':
15 | return 'TOOL'
16 | case 'function':
17 | default:
18 | throw new Error(`Unsupported role: ${role}`)
19 | }
20 | }
21 |
22 | function finishReasonCohereToOpenAI(
23 | reason: Cohere.NonStreamedChatResponse['finishReason'],
24 | ): OpenAI.ChatCompletion['choices'][number]['finish_reason'] {
25 | switch (reason) {
26 | case 'COMPLETE':
27 | return 'stop'
28 | case 'ERROR_LIMIT':
29 | return 'stop'
30 | case 'STOP_SEQUENCE':
31 | return 'stop'
32 | case 'USER_CANCEL':
33 | return 'stop'
34 | case 'MAX_TOKENS':
35 | return 'length'
36 | case 'ERROR_TOXIC':
37 | return 'content_filter'
38 | case 'ERROR':
39 | default:
40 | return 'stop'
41 | }
42 | }
43 |
44 | export function cohere(env: ChatEnv): IChat {
45 | const createClient = () =>
46 | new CohereClient({
47 | token: env.COHERE_API_KEY,
48 | })
49 |
50 | function parseRequest(req: OpenAI.ChatCompletionCreateParams): Cohere.ChatRequest {
51 | return {
52 | model: req.model,
53 | chatHistory: req.messages.slice(0, -1).map(
54 | (it) =>
55 | ({
56 | role: roleOpenaiToCohere(it.role),
57 | message: it.content as string,
58 | }) satisfies Cohere.Message,
59 | ),
60 | message: last(req.messages)?.content as string,
61 | temperature: req.temperature!,
62 | maxTokens: req.max_completion_tokens!,
63 | }
64 | }
65 |
66 | function parseResponse(
67 | resp: Cohere.NonStreamedChatResponse,
68 | req: OpenAI.ChatCompletionCreateParams,
69 | ): OpenAI.ChatCompletion {
70 | return {
71 | id: resp.generationId ?? 'chatcmpl-' + crypto.randomUUID(),
72 | object: 'chat.completion',
73 | created: Math.floor(Date.now() / 1000),
74 | model: req.model,
75 | choices: [
76 | {
77 | message: {
78 | role: 'assistant',
79 | content: resp.text,
80 | refusal: null,
81 | },
82 | finish_reason: finishReasonCohereToOpenAI(resp.finishReason),
83 | index: 0,
84 | logprobs: null,
85 | },
86 | ],
87 | usage:
88 | resp.meta?.billedUnits?.inputTokens && resp.meta?.billedUnits?.outputTokens
89 | ? {
90 | prompt_tokens: resp.meta.billedUnits.inputTokens,
91 | completion_tokens: resp.meta.billedUnits.outputTokens,
92 | total_tokens: resp.meta.billedUnits.inputTokens + resp.meta.billedUnits.outputTokens,
93 | }
94 | : undefined,
95 | }
96 | }
97 |
98 | return {
99 | name: 'cohere',
100 | supportModels: [
101 | 'command-r',
102 | 'command-r-plus',
103 | 'command-nightly',
104 | 'command-light-nightly',
105 | 'command',
106 | 'command-r-08-2024',
107 | 'command-r-plus-08-2024',
108 | 'command-light',
109 | ],
110 | requiredEnv: ['COHERE_API_KEY'],
111 | async invoke(req) {
112 | const client = createClient()
113 | const resp = await client.chat(parseRequest(req))
114 | return parseResponse(resp, req)
115 | },
116 | async *stream(req, signal) {
117 | const client = createClient()
118 | const stream = await client.chatStream(parseRequest(req), {
119 | abortSignal: signal,
120 | })
121 | let id: string = 'chatcmpl-' + crypto.randomUUID()
122 | const fileds = () =>
123 | ({
124 | id: id,
125 | model: req.model,
126 | object: 'chat.completion.chunk',
127 | created: Math.floor(Date.now() / 1000),
128 | }) as const
129 | for await (const chunk of stream) {
130 | if (chunk.eventType === 'stream-start') {
131 | id = chunk.generationId
132 | yield {
133 | ...fileds(),
134 | choices: [{ delta: { content: '' }, index: 0, finish_reason: null }],
135 | } satisfies OpenAI.ChatCompletionChunk
136 | } else if (chunk.eventType === 'text-generation') {
137 | yield {
138 | ...fileds(),
139 | choices: [
140 | {
141 | delta: { content: chunk.text },
142 | index: 0,
143 | finish_reason: null,
144 | },
145 | ],
146 | } satisfies OpenAI.ChatCompletionChunk
147 | } else if (chunk.eventType === 'stream-end') {
148 | if (!chunk.response.meta?.billedUnits?.inputTokens || !chunk.response.meta?.billedUnits?.outputTokens) {
149 | throw new Error('Billed units not found')
150 | }
151 | yield {
152 | ...fileds(),
153 | choices: [
154 | {
155 | delta: { content: '' },
156 | index: 0,
157 | finish_reason: finishReasonCohereToOpenAI(chunk.finishReason),
158 | },
159 | ],
160 | usage: {
161 | prompt_tokens: chunk.response.meta.billedUnits.inputTokens,
162 | completion_tokens: chunk.response.meta.billedUnits.outputTokens,
163 | total_tokens: chunk.response.meta.billedUnits.inputTokens + chunk.response.meta.billedUnits.outputTokens,
164 | },
165 | } satisfies OpenAI.ChatCompletionChunk
166 | }
167 | }
168 | },
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/src/llm/deepseek.test.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { expect, it } from 'vitest'
3 | import { deepseek } from './deepseek'
4 | import { omit } from 'lodash-es'
5 |
6 | it('deepseek', async () => {
7 | const client = new OpenAI({
8 | baseURL: 'https://api.deepseek.com',
9 | apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY,
10 | })
11 | const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = {
12 | model: 'deepseek-chat',
13 | messages: [{ role: 'user', content: 'Hello, world!' }],
14 | temperature: 0,
15 | }
16 | const r1 = await client.chat.completions.create(params)
17 | const r2 = await deepseek({
18 | DEEPSEEK_API_KEY: import.meta.env.VITE_DEEPSEEK_API_KEY,
19 | }).invoke(params)
20 | expect(omit(r1, ['id', 'created'])).toEqual(omit(r2, ['id', 'created']))
21 | })
22 |
--------------------------------------------------------------------------------
/src/llm/deepseek.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { IChat } from './base'
3 | import { openaiBase } from './openai'
4 |
5 | export function deepseek(env: Record): IChat {
6 | const r = openaiBase({
7 | createClient: () =>
8 | new OpenAI({
9 | apiKey: env.DEEPSEEK_API_KEY,
10 | baseURL: 'https://api.deepseek.com',
11 | }),
12 | })
13 | r.name = 'deepseek'
14 | r.requiredEnv = ['DEEPSEEK_API_KEY']
15 | r.supportModels = ['deepseek-reasoner', 'deepseek-chat', 'deepseek-coder']
16 | return r
17 | }
18 |
--------------------------------------------------------------------------------
/src/llm/google.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeAll, describe, expect, it } from 'vitest'
2 | import { google } from './google'
3 | import { GenerativeModel, GoogleGenerativeAI } from '@google/generative-ai'
4 | import { IChat } from './base'
5 | import OpenAI from 'openai'
6 | import { last } from 'lodash-es'
7 |
8 | let llm: IChat
9 | let model: GenerativeModel
10 | beforeAll(() => {
11 | const genAI = new GoogleGenerativeAI(import.meta.env.GOOGLE_GEN_AI_API_KEY)
12 | model = genAI.getGenerativeModel({
13 | model: 'gemini-1.5-flash',
14 | generationConfig: { temperature: 0! },
15 | })
16 | llm = google({
17 | GOOGLE_GEN_AI_API_KEY: import.meta.env.GOOGLE_GEN_AI_API_KEY,
18 | })
19 | })
20 |
21 | it('google', async () => {
22 | const [r1, { response: r2 }] = await Promise.all([
23 | llm.invoke({
24 | model: 'gemini-1.5-flash',
25 | messages: [{ role: 'user', content: 'Hello!' }],
26 | temperature: 0,
27 | }),
28 | model.generateContent('Hello!'),
29 | ])
30 | expect(r1.choices[0].message.content).eq(r2.text())
31 | expect(r1.usage).deep.eq({
32 | prompt_tokens: r2.usageMetadata!.promptTokenCount,
33 | completion_tokens: r2.usageMetadata!.candidatesTokenCount,
34 | total_tokens: r2.usageMetadata!.totalTokenCount,
35 | })
36 | })
37 |
38 | it('google chat with function', async () => {
39 | const [r1] = await Promise.all([
40 | llm.invoke({
41 | model: 'gemini-2.0-flash',
42 | messages: [
43 | { role: 'user', content: 'Hello!' },
44 | {
45 | role: 'assistant',
46 | content: 'hello!can I help you?',
47 | },
48 | { role: 'user', content: 'What is the weather today in Paris? need celsius' },
49 | ],
50 | temperature: 0,
51 | tools: [
52 | {
53 | type: 'function',
54 | function: {
55 | name: 'get_current_weather',
56 | description: 'Get the current weather for a location',
57 | parameters: {
58 | type: 'object',
59 | properties: {
60 | location: {
61 | type: 'string',
62 | description: 'The location to get the weather for, e.g. San Francisco, CA',
63 | },
64 | format: {
65 | type: 'string',
66 | description: "The format to return the weather in, e.g. 'celsius' or 'fahrenheit'",
67 | enum: ['celsius', 'fahrenheit'],
68 | },
69 | },
70 | required: ['location', 'format'],
71 | },
72 | },
73 | },
74 | ],
75 | }),
76 | ])
77 |
78 | // @ts-ignore
79 | expect(r1.choices[0].message.tool_calls[0].function.name).eq('get_current_weather')
80 | })
81 |
82 | describe('stream', () => {
83 | async function streamByUsage(include_usage: boolean) {
84 | const s1 = await model.generateContentStream('Hello!')
85 | const r1 = []
86 | for await (const chunk of s1.stream) {
87 | r1.push(chunk)
88 | }
89 | const s2 = llm.stream(
90 | {
91 | model: 'gemini-1.5-flash',
92 | messages: [{ role: 'user', content: 'Hello!' }],
93 | temperature: 0,
94 | stream: true,
95 | stream_options: {
96 | include_usage: include_usage,
97 | },
98 | },
99 | new AbortController().signal,
100 | )
101 | const r2: OpenAI.ChatCompletionChunk[] = []
102 | for await (const chunk of s2) {
103 | r2.push(chunk)
104 | }
105 | return { r1, r2 }
106 | }
107 | it('basic stream', async () => {
108 | const { r1, r2 } = await streamByUsage(false)
109 | // console.log(r1, r2)
110 | expect(r1.map((it) => it.text()).join('')).eq(r2.map((it) => it.choices[0].delta.content).join(''))
111 | expect(last(r2)!.usage).undefined
112 | expect(last(r1)!.usageMetadata).not.undefined
113 | })
114 | it('usage stream', async () => {
115 | const { r1, r2 } = await streamByUsage(true)
116 | console.log(r1, r2)
117 | expect(r1.map((it) => it.text()).join('')).eq(r2.map((it) => it.choices[0]?.delta.content ?? '').join(''))
118 | expect(r2.length - r1.length).eq(1)
119 | expect(last(r2)!.usage).deep.eq({
120 | prompt_tokens: last(r1)!.usageMetadata!.promptTokenCount,
121 | completion_tokens: last(r1)!.usageMetadata!.candidatesTokenCount,
122 | total_tokens: last(r1)!.usageMetadata!.totalTokenCount,
123 | })
124 | })
125 | })
126 |
--------------------------------------------------------------------------------
/src/llm/google.ts:
--------------------------------------------------------------------------------
1 | import { IChat } from './base'
2 | import GoogleAI, { FileDataPart, FunctionDeclarationsTool, GoogleGenerativeAI, TextPart } from '@google/generative-ai'
3 | import OpenAI from 'openai'
4 | import { toString } from 'lodash-es'
5 | import mime from 'mime/lite'
6 |
7 | export function google(env: Record): IChat {
8 | function createClient(req: OpenAI.ChatCompletionCreateParams) {
9 | const genAI = new GoogleGenerativeAI(env.GOOGLE_GEN_AI_API_KEY)
10 | if (req.response_format && req.response_format.type !== 'json_schema') {
11 | throw new Error('Unsupported response format, only json_schema is supported')
12 | }
13 | const model = genAI.getGenerativeModel({
14 | model: req.model,
15 | generationConfig: {
16 | temperature: req.temperature!,
17 | maxOutputTokens: req.max_completion_tokens!,
18 | responseSchema: req.response_format?.type === 'json_schema' ? req.response_format.json_schema : undefined,
19 | topP: req.top_p!,
20 | },
21 | })
22 | return model
23 | }
24 | function parseRequest(req: OpenAI.ChatCompletionCreateParams): GoogleAI.GenerateContentRequest {
25 | const systemInstruction = () => {
26 | const system = req.messages.find((m) => m.role === 'system')?.content
27 | if (!system) {
28 | return undefined
29 | }
30 | return typeof system === 'string' ? system : system.map((s) => s.text).join('')
31 | }
32 |
33 | const tools = () => {
34 | if (!req.tools) {
35 | return undefined
36 | }
37 | return [
38 | {
39 | functionDeclarations: req.tools?.map(
40 | (tool) =>
41 | ({
42 | name: tool.function.name,
43 | description: tool.function.description,
44 | parameters: tool.function.parameters,
45 | }) as GoogleAI.Tool,
46 | ),
47 | } as FunctionDeclarationsTool,
48 | ]
49 | }
50 |
51 | return {
52 | systemInstruction: systemInstruction(),
53 | contents: req.messages.map(
54 | (m) =>
55 | ({
56 | role: m.role === 'assistant' ? 'model' : 'user',
57 | parts:
58 | typeof m.content === 'string'
59 | ? [{ text: m.content }]
60 | : m.content!.map((c) => {
61 | if (c.type === 'text') {
62 | return { text: c.text } satisfies TextPart
63 | }
64 | if (c.type === 'image_url') {
65 | return {
66 | fileData: {
67 | fileUri: c.image_url.url,
68 | mimeType: 'image/png',
69 | },
70 | } satisfies FileDataPart
71 | }
72 | if (c.type === 'file') {
73 | return {
74 | fileData: {
75 | fileUri: c.file.file_data!,
76 | mimeType: mime.getType(c.file.filename!)!,
77 | },
78 | } satisfies FileDataPart
79 | }
80 | throw new Error('Unsupported content type: ' + c.type)
81 | }),
82 | }) as GoogleAI.Content,
83 | ),
84 | tools: tools(),
85 | }
86 | }
87 | function parseResponse(
88 | response: GoogleAI.EnhancedGenerateContentResponse,
89 | req: OpenAI.ChatCompletionCreateParams,
90 | ): OpenAI.ChatCompletion {
91 | let index = 0
92 | return {
93 | id: 'chatcmpl-' + crypto.randomUUID(),
94 | object: 'chat.completion',
95 | created: Math.floor(Date.now() / 1000),
96 | model: req.model,
97 | choices: [
98 | {
99 | index: 0,
100 | message: {
101 | role: 'assistant',
102 | content: response.text(),
103 | refusal: null,
104 | tool_calls: response.functionCalls()?.map(
105 | (it) =>
106 | ({
107 | id: toString(index++),
108 | function: {
109 | arguments: it.args as any,
110 | name: it.name,
111 | } as OpenAI.ChatCompletionMessageToolCall.Function,
112 | type: 'function',
113 | }) as OpenAI.ChatCompletionMessageToolCall,
114 | ),
115 | },
116 | logprobs: null,
117 | finish_reason: 'stop',
118 | },
119 | ],
120 | usage: {
121 | prompt_tokens: response.usageMetadata!.promptTokenCount,
122 | completion_tokens: response.usageMetadata!.candidatesTokenCount,
123 | total_tokens: response.usageMetadata!.totalTokenCount,
124 | },
125 | }
126 | }
127 | return {
128 | name: 'google',
129 | supportModels: [
130 | 'gemini-2.5-flash-preview-05-20',
131 | 'gemini-2.5-flash-preview-native-audio-dialog',
132 | 'gemini-2.5-flash-exp-native-audio-thinking-dialog',
133 | 'gemini-2.5-flash-preview-tts',
134 | 'gemini-2.5-pro-preview-06-05',
135 | 'gemini-2.5-pro-preview-05-06',
136 | 'gemini-2.5-pro-preview-tts',
137 | 'gemini-2.0-flash',
138 | 'gemini-2.0-flash-preview-image-generation',
139 | 'gemini-2.0-flash-lite',
140 | 'gemini-1.5-flash',
141 | 'gemini-1.5-flash-8b',
142 | 'gemini-1.5-pro',
143 | 'gemini-embedding-exp',
144 | 'gemini-2.0-flash-live-001',
145 | ],
146 | requiredEnv: ['GOOGLE_GEN_AI_API_KEY'],
147 | async invoke(req) {
148 | const { response } = await createClient(req).generateContent(parseRequest(req))
149 | return parseResponse(response, req)
150 | },
151 | async *stream(req) {
152 | const client = createClient(req)
153 | const stream = await client.generateContentStream(parseRequest(req))
154 | const id = 'chatcmpl-' + crypto.randomUUID()
155 | let last: GoogleAI.EnhancedGenerateContentResponse | undefined
156 | const fields = () => ({
157 | id,
158 | object: 'chat.completion.chunk',
159 | created: Math.floor(Date.now() / 1000),
160 | model: req.model,
161 | })
162 | for await (const chunk of stream.stream) {
163 | last = chunk
164 | yield {
165 | ...fields(),
166 | choices: [
167 | {
168 | index: 0,
169 | delta: {
170 | content: chunk.text(),
171 | tool_calls: chunk.functionCalls(),
172 | },
173 | finish_reason: null,
174 | },
175 | ],
176 | } as OpenAI.ChatCompletionChunk
177 | }
178 | if (!last) {
179 | throw new Error('No response from google')
180 | }
181 |
182 | if (req.stream_options?.include_usage) {
183 | yield {
184 | ...fields(),
185 | choices: [],
186 | usage: {
187 | prompt_tokens: last.usageMetadata!.promptTokenCount,
188 | completion_tokens: last.usageMetadata!.candidatesTokenCount,
189 | total_tokens: last.usageMetadata!.totalTokenCount,
190 | },
191 | } as OpenAI.ChatCompletionChunk
192 | } else {
193 | yield {
194 | ...fields(),
195 | choices: [
196 | {
197 | index: 0,
198 | delta: {},
199 | finish_reason: 'stop',
200 | },
201 | ],
202 | } as OpenAI.ChatCompletionChunk
203 | }
204 | },
205 | }
206 | }
207 |
--------------------------------------------------------------------------------
/src/llm/grok.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeEach, expect, it } from 'vitest'
2 | import { bailian } from '../bailian'
3 | import OpenAI from 'openai'
4 | import { IChat } from '../base'
5 | import { last } from 'lodash-es'
6 | import { grok } from '../grok'
7 |
8 | let client: IChat
9 | beforeEach(() => {
10 | client = grok({
11 | GROK_API_KEY: import.meta.env.VITE_GROK_API_KEY,
12 | })
13 | })
14 | it('invoke', async () => {
15 | const res = await client.invoke({
16 | model: 'grok-3-latest',
17 | messages: [{ role: 'user', content: '你是?' }],
18 | temperature: 0,
19 | })
20 | expect(res.choices[0].message.content).not.undefined
21 | })
22 | it('stream usage', async () => {
23 | const res = client.stream(
24 | {
25 | model: 'grok-3-mini-latest',
26 | messages: [{ role: 'user', content: '你是?' }],
27 | temperature: 0,
28 | stream: true,
29 | },
30 | new AbortController().signal,
31 | )
32 | const r: OpenAI.Chat.Completions.ChatCompletionChunk[] = []
33 | for await (const chunk of res) {
34 | r.push(chunk)
35 | }
36 | const content = r.map((it) => it.choices[0]?.delta.content).join('')
37 | expect(content).not.undefined
38 | // grok不会返回usage信息
39 | })
40 |
--------------------------------------------------------------------------------
/src/llm/grok.ts:
--------------------------------------------------------------------------------
1 | import { IChat } from './base'
2 | import OpenAI from 'openai'
3 | import { openaiBase } from './openai'
4 |
5 | export function grok(env: Record): IChat {
6 | const r = openaiBase({
7 | createClient: () =>
8 | new OpenAI({
9 | apiKey: env.GROK_API_KEY,
10 | baseURL: 'https://api.x.ai/v1',
11 | }),
12 | })
13 | r.name = 'grok'
14 | r.requiredEnv = ['GROK_API_KEY']
15 | r.supportModels = ['grok-3-latest', 'grok-3-fast-latest', 'grok-3-mini-latest', 'grok-3-mini-fast-latest']
16 | return r
17 | }
18 |
--------------------------------------------------------------------------------
/src/llm/groq.test.ts:
--------------------------------------------------------------------------------
1 | import { expect, it } from 'vitest'
2 | import { groq } from './groq'
3 |
4 | it('groq', async () => {
5 | const client = groq({
6 | GROQ_API_KEY: import.meta.env.VITE_GROQ_API_KEY,
7 | })
8 | const res = await client.invoke({
9 | messages: [{ role: 'user', content: 'Hello?' }],
10 | model: 'groq/llama3-8b-8192',
11 | temperature: 0.5,
12 | presence_penalty: 0,
13 | frequency_penalty: 0,
14 | top_p: 1,
15 | })
16 | expect(res.choices[0].message.content).not.undefined
17 | })
18 |
19 | it('stream', async () => {
20 | const client = groq({
21 | GROQ_API_KEY: import.meta.env.VITE_GROQ_API_KEY,
22 | })
23 | const res = client.stream(
24 | {
25 | messages: [{ role: 'user', content: 'Hello?' }],
26 | model: 'groq/llama3-8b-8192',
27 | temperature: 0.5,
28 | presence_penalty: 0,
29 | frequency_penalty: 0,
30 | top_p: 1,
31 | stream: true,
32 | },
33 | new AbortController().signal,
34 | )
35 | const chunks: string[] = []
36 | for await (const chunk of res) {
37 | chunks.push(chunk.choices[0].delta?.content ?? '')
38 | }
39 | expect(chunks.join('')).not.undefined
40 | })
41 |
--------------------------------------------------------------------------------
/src/llm/groq.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { IChat } from './base'
3 | import { openaiBase } from './openai'
4 |
5 | export function groq(env: Record): IChat {
6 | const map = {
7 | 'groq/distil-whisper-large-v3-en': 'distil-whisper-large-v3-en',
8 | 'groq/gemma2-9b-it': 'gemma2-9b-it',
9 | 'groq/gemma-7b-it': 'gemma-7b-it',
10 | 'groq/llama-3.1-70b-versatile': 'llama-3.1-70b-versatile',
11 | 'groq/llama-3.1-8b-instant': 'llama-3.1-8b-instant',
12 | 'groq/llama3-70b-8192': 'llama3-70b-8192',
13 | 'groq/llama3-8b-8192': 'llama3-8b-8192',
14 | 'groq/llama3-groq-70b-8192-tool-use-preview': 'llama3-groq-70b-8192-tool-use-preview',
15 | 'groq/llama3-groq-8b-8192-tool-use-preview': 'llama3-groq-8b-8192-tool-use-preview',
16 | 'groq/llama-guard-3-8b': 'llama-guard-3-8b',
17 | 'groq/mixtral-8x7b-32768': 'mixtral-8x7b-32768',
18 | 'groq/whisper-large-v3': 'whisper-large-v3',
19 | }
20 | const r = openaiBase({
21 | createClient: () =>
22 | new OpenAI({
23 | apiKey: env.GROQ_API_KEY,
24 | baseURL: 'https://api.groq.com/openai/v1',
25 | }),
26 | pre(req) {
27 | req.model = map[req.model as keyof typeof map]
28 | return req
29 | },
30 | })
31 | r.name = 'groq'
32 | r.requiredEnv = ['GROQ_API_KEY']
33 | r.supportModels = Object.keys(map)
34 | return r
35 | }
36 |
--------------------------------------------------------------------------------
/src/llm/lingyiwanwu.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { openaiBase } from './openai'
3 |
4 | export function lingyiwanwu(env: Record) {
5 | const r = openaiBase({
6 | createClient: () =>
7 | new OpenAI({
8 | apiKey: env.LINGYIWANWU_API_KEY,
9 | baseURL: 'https://api.lingyiwanwu.com/v1',
10 | }),
11 | })
12 | r.name = 'lingyiwanwu'
13 | r.requiredEnv = ['LINGYIWANWU_API_KEY']
14 | r.supportModels = [
15 | 'yi-large',
16 | 'yi-medium',
17 | 'yi-vision',
18 | 'yi-medium-200k',
19 | 'yi-spark',
20 | 'yi-large-rag',
21 | 'yi-large-fc',
22 | 'yi-large-turbo',
23 | 'yi-large-preview',
24 | ]
25 | return r
26 | }
27 |
--------------------------------------------------------------------------------
/src/llm/moonshot.test.ts:
--------------------------------------------------------------------------------
1 | import { expect, it } from 'vitest'
2 | import { moonshot } from './moonshot'
3 |
4 | it('moonshot', async () => {
5 | const client = moonshot({
6 | MOONSHOT_API_KEY: import.meta.env.VITE_MOONSHOT_API_KEY,
7 | })
8 | const res = await client.invoke({
9 | model: 'moonshot-v1-8k',
10 | messages: [{ role: 'user', content: 'Hello!' }],
11 | temperature: 0,
12 | })
13 | expect(res.model).eq('moonshot-v1-8k')
14 | expect(res.choices[0].message.content).not.undefined
15 | })
16 |
--------------------------------------------------------------------------------
/src/llm/moonshot.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { openaiBase } from './openai'
3 |
4 | export function moonshot(env: Record) {
5 | const r = openaiBase({
6 | createClient: () =>
7 | new OpenAI({
8 | apiKey: env.MOONSHOT_API_KEY,
9 | baseURL: 'https://api.moonshot.cn/v1',
10 | }),
11 | })
12 | r.name = 'moonshot'
13 | r.requiredEnv = ['MOONSHOT_API_KEY']
14 | r.supportModels = ['moonshot-v1-128k', 'moonshot-v1-8k', 'moonshot-v1-32k']
15 | return r
16 | }
17 |
--------------------------------------------------------------------------------
/src/llm/ollama.test.ts:
--------------------------------------------------------------------------------
1 | import { expect, it } from 'vitest'
2 | import { ollama } from './ollama'
3 |
4 | it('ollama', async () => {
5 | const client = ollama({
6 | OLLAMA_BASE_URL: import.meta.env.VITE_OLLAMA_BASE_URL,
7 | })
8 | const res = await client.invoke({
9 | messages: [{ role: 'user', content: 'Hello?' }],
10 | model: 'ollama/qwen2.5:0.5b',
11 | temperature: 0.5,
12 | presence_penalty: 0,
13 | frequency_penalty: 0,
14 | top_p: 1,
15 | })
16 | expect(res.choices[0].message.content).not.undefined
17 | })
18 |
19 | it('stream', async () => {
20 | const client = ollama({
21 | OLLAMA_BASE_URL: import.meta.env.VITE_OLLAMA_BASE_URL,
22 | })
23 | const res = client.stream(
24 | {
25 | messages: [{ role: 'user', content: 'Hello?' }],
26 | model: 'ollama/qwen2.5:0.5b',
27 | temperature: 0.5,
28 | presence_penalty: 0,
29 | frequency_penalty: 0,
30 | top_p: 1,
31 | stream: true,
32 | },
33 | new AbortController().signal,
34 | )
35 | const chunks: string[] = []
36 | for await (const chunk of res) {
37 | chunks.push(chunk.choices[0].delta?.content ?? '')
38 | }
39 | expect(chunks.join('')).not.undefined
40 | })
41 |
--------------------------------------------------------------------------------
/src/llm/ollama.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { IChat } from './base'
3 | import { openaiBase } from './openai'
4 |
5 | export function ollama(env: Record): IChat {
6 | const client = new OpenAI({
7 | apiKey: 'openai-api-proxy',
8 | baseURL: env.OLLAMA_BASE_URL,
9 | })
10 | const r = openaiBase({
11 | createClient: () => client,
12 | pre: (req) => ({
13 | ...req,
14 | model: req.model.split('/')[1],
15 | stream: false,
16 | }),
17 | })
18 | r.name = 'ollama'
19 | r.requiredEnv = ['OLLAMA_BASE_URL']
20 | r.supportModels = (env.OLLAMA_MODELS ?? '').split(',').map((it) => {
21 | return `ollama/${it}`
22 | })
23 | return r
24 | }
25 |
--------------------------------------------------------------------------------
/src/llm/openai.test.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { describe, expect, it } from 'vitest'
3 | import { openai } from './openai'
4 |
5 | describe('OpenAI', () => {
6 | const client = openai({
7 | OPENAI_API_KEY: import.meta.env.OPENAI_API_KEY,
8 | })
9 | describe('invoke basic', () => {
10 | it('should invoke chat completion', async () => {
11 | const resp = await client.invoke({
12 | messages: [{ role: 'user', content: 'hello' }],
13 | model: 'gpt-4o-mini',
14 | })
15 | expect(resp.choices[0].message.content).toBeTypeOf('string')
16 | })
17 | it('should invoke response', async () => {
18 | const resp = await client.invoke({
19 | messages: [{ role: 'user', content: 'hello' }],
20 | model: 'o1',
21 | })
22 | expect(resp.choices[0].message.content).toBeTypeOf('string')
23 | })
24 | })
25 | describe('streaming basic', () => {
26 | it('should streaming chat completion', async () => {
27 | const stream = client.stream(
28 | {
29 | messages: [{ role: 'user', content: 'hello' }],
30 | model: 'gpt-4o-mini',
31 | stream: true,
32 | },
33 | new AbortController().signal,
34 | )
35 | const chunks = await Array.fromAsync(stream)
36 | const r = chunks.map((it) => it.choices[0].delta.content).join('')
37 | expect(r).toBeTypeOf('string')
38 | expect(chunks[0].model.includes('gpt-4o-mini')).true
39 | })
40 | it('should streaming chat completion', async () => {
41 | const stream = client.stream(
42 | {
43 | messages: [{ role: 'user', content: 'hello' }],
44 | model: 'o1',
45 | stream: true,
46 | },
47 | new AbortController().signal,
48 | )
49 | const chunks = await Array.fromAsync(stream)
50 | const r = chunks.map((it) => it.choices[0].delta.content).join('')
51 | expect(r).toBeTypeOf('string')
52 | expect(chunks[0].model.includes('o1')).true
53 | })
54 | })
55 | describe('include image', () => {
56 | it('should invoke chat completion', async () => {
57 | const resp = await client.invoke({
58 | messages: [
59 | { role: 'user', content: 'Describe this image' },
60 | {
61 | role: 'user',
62 | content: 'https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg',
63 | },
64 | ],
65 | model: 'gpt-4o',
66 | })
67 | expect(resp.choices[0].message.content).includes('ant')
68 | expect(resp.model).includes('gpt-4o')
69 | })
70 | it('should invoke chat completion', async () => {
71 | const resp = await client.invoke({
72 | messages: [
73 | { role: 'user', content: 'Describe this image' },
74 | {
75 | role: 'user',
76 | content: 'https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg',
77 | },
78 | ],
79 | model: 'o1',
80 | })
81 | expect(resp.choices[0].message.content).includes('ant')
82 | expect(resp.model).includes('o1')
83 | })
84 | })
85 | }, 15_000)
86 |
--------------------------------------------------------------------------------
/src/llm/openai.ts:
--------------------------------------------------------------------------------
1 | import OpenAI, { AzureOpenAI } from 'openai'
2 | import { IChat } from './base'
3 | import { ChatCompletionCreateParams } from 'openai/resources/index.mjs'
4 | import { ChatCompletion, ChatCompletionChunk } from 'openai/resources.js'
5 | import {
6 | ResponseInputFile,
7 | ResponseInputImage,
8 | ResponseInputText,
9 | ResponseOutputMessage,
10 | ResponseOutputText,
11 | } from 'openai/resources/responses/responses.mjs'
12 | import { Response } from 'openai/resources/responses/responses.js'
13 | import { HTTPException } from 'hono/http-exception'
14 |
15 | export function openaiBase(options: {
16 | createClient: (req: ChatCompletionCreateParams) => OpenAI | AzureOpenAI
17 | pre?: (req: ChatCompletionCreateParams) => ChatCompletionCreateParams
18 | }): IChat {
19 | const pre = options.pre ?? ((req) => req)
20 | return {
21 | name: 'openai',
22 | supportModels: [],
23 | requiredEnv: ['OPENAI_API_KEY'],
24 | invoke(req) {
25 | const _req = pre(req)
26 | const client = options.createClient(_req)
27 | return client.chat.completions.create({
28 | ..._req,
29 | stream: false,
30 | })
31 | },
32 | async *stream(req, signal) {
33 | const _req = pre(req)
34 | const client = options.createClient(_req)
35 | const stream = await client.chat.completions.create({
36 | ..._req,
37 | stream: true,
38 | })
39 | for await (const it of stream) {
40 | if (signal?.aborted) {
41 | throw new Error('Aborted')
42 | }
43 | yield it
44 | }
45 | },
46 | }
47 | }
48 |
49 | function openaiResponse(options: { createClient: (req: ChatCompletionCreateParams) => OpenAI | AzureOpenAI }): IChat {
50 | function pre(
51 | req: OpenAI.Chat.Completions.ChatCompletionCreateParams,
52 | ): OpenAI.Responses.ResponseCreateParamsNonStreaming {
53 | return {
54 | input: req.messages.map((it) => ({
55 | role: it.role as any,
56 | content:
57 | typeof it.content === 'string'
58 | ? it.content
59 | : it.content!.map((c) => {
60 | if (c.type === 'text') {
61 | return {
62 | type: 'input_text',
63 | text: c.text,
64 | } satisfies ResponseInputText
65 | }
66 | if (c.type === 'image_url') {
67 | return {
68 | type: 'input_image',
69 | image_url: c.image_url.url,
70 | detail: c.image_url.detail ?? 'auto',
71 | } satisfies ResponseInputImage
72 | }
73 | if (c.type === 'file') {
74 | return {
75 | type: 'input_file',
76 | file_id: c.file.file_id,
77 | filename: c.file.filename,
78 | file_data: c.file.file_data,
79 | } satisfies ResponseInputFile
80 | }
81 | throw new Error('Unsupported content type: ' + c.type)
82 | }),
83 | })),
84 | model: req.model,
85 | temperature: req.temperature,
86 | max_output_tokens: req.max_completion_tokens,
87 | top_p: req.top_p,
88 | } satisfies OpenAI.Responses.ResponseCreateParamsNonStreaming
89 | }
90 | return {
91 | name: 'openai',
92 | supportModels: [],
93 | requiredEnv: ['OPENAI_API_KEY'],
94 | async invoke(req) {
95 | const client = options.createClient(req)
96 | const resp = await client.responses.create(pre(req))
97 | return {
98 | id: resp.id,
99 | object: 'chat.completion',
100 | created: resp.created_at,
101 | model: resp.model,
102 | choices: [
103 | {
104 | index: 0,
105 | finish_reason: 'stop',
106 | message: {
107 | role: 'assistant',
108 | content: resp.output_text,
109 | },
110 | logprobs: null,
111 | } as ChatCompletion.Choice,
112 | ],
113 | } as ChatCompletion
114 | },
115 | async *stream(req, signal) {
116 | const client = options.createClient(req)
117 | const stream = await client.responses.create({
118 | ...pre(req),
119 | stream: true,
120 | })
121 | let response: Response
122 | for await (const it of stream) {
123 | if (signal?.aborted) {
124 | throw new Error('Aborted')
125 | }
126 | if (it.type === 'response.created') {
127 | response = it.response
128 | yield {
129 | id: it.response.id,
130 | choices: [
131 | {
132 | index: it.sequence_number,
133 | finish_reason: null,
134 | delta: {
135 | role: 'assistant',
136 | content: it.response.output_text ?? '',
137 | },
138 | },
139 | ],
140 | created: it.response.created_at,
141 | model: it.response.model,
142 | object: 'chat.completion.chunk',
143 | } satisfies ChatCompletionChunk
144 | } else if (it.type === 'response.output_text.delta') {
145 | yield {
146 | id: it.item_id,
147 | choices: [
148 | {
149 | index: it.sequence_number,
150 | delta: {
151 | role: 'assistant',
152 | content: it.delta,
153 | },
154 | logprobs: null,
155 | finish_reason: null,
156 | },
157 | ],
158 | created: response!.created_at,
159 | model: response!.model,
160 | object: 'chat.completion.chunk',
161 | } satisfies ChatCompletionChunk
162 | } else if (it.type === 'response.completed') {
163 | yield {
164 | id: it.response.id,
165 | choices: [
166 | {
167 | index: it.sequence_number,
168 | finish_reason: 'stop',
169 | delta: {
170 | role: 'assistant',
171 | content: it.response.output_text ?? '',
172 | },
173 | },
174 | ],
175 | usage: {
176 | prompt_tokens: it.response.usage!.input_tokens,
177 | completion_tokens: it.response.usage!.output_tokens,
178 | total_tokens: it.response.usage!.total_tokens,
179 | },
180 | created: it.response.created_at,
181 | model: it.response.model,
182 | object: 'chat.completion.chunk',
183 | } satisfies ChatCompletionChunk
184 | } else if (it.type === 'error') {
185 | throw new HTTPException(it.code as any, { message: it.message })
186 | }
187 | }
188 | },
189 | }
190 | }
191 |
192 | export function openai(env: Record): IChat {
193 | const oldModels = [
194 | 'chatgpt-4o-latest',
195 | 'codex-mini-latest',
196 | 'computer-use-preview',
197 | 'computer-use-preview-2025-03-11',
198 | 'gpt-3.5-turbo',
199 | 'gpt-3.5-turbo-0125',
200 | 'gpt-3.5-turbo-1106',
201 | 'gpt-3.5-turbo-16k',
202 | 'gpt-3.5-turbo-instruct',
203 | 'gpt-3.5-turbo-instruct-0914',
204 | 'gpt-4',
205 | 'gpt-4-0125-preview',
206 | 'gpt-4-0613',
207 | 'gpt-4-1106-preview',
208 | 'gpt-4-turbo',
209 | 'gpt-4-turbo-2024-04-09',
210 | 'gpt-4-turbo-preview',
211 | 'gpt-4o',
212 | 'gpt-4o-2024-05-13',
213 | 'gpt-4o-2024-08-06',
214 | 'gpt-4o-2024-11-20',
215 | 'gpt-4o-audio-preview',
216 | 'gpt-4o-audio-preview-2024-10-01',
217 | 'gpt-4o-audio-preview-2024-12-17',
218 | 'gpt-4o-mini',
219 | 'gpt-4o-mini-2024-07-18',
220 | 'gpt-4o-mini-audio-preview',
221 | 'gpt-4o-mini-audio-preview-2024-12-17',
222 | 'gpt-4o-mini-realtime-preview',
223 | 'gpt-4o-mini-realtime-preview-2024-12-17',
224 | 'gpt-4o-mini-search-preview',
225 | 'gpt-4o-mini-search-preview-2025-03-11',
226 | 'gpt-4o-mini-transcribe',
227 | 'gpt-4o-mini-tts',
228 | 'gpt-4o-realtime-preview',
229 | 'gpt-4o-realtime-preview-2024-10-01',
230 | 'gpt-4o-realtime-preview-2024-12-17',
231 | 'gpt-4o-search-preview',
232 | 'gpt-4o-search-preview-2025-03-11',
233 | 'gpt-4o-transcribe',
234 | 'gpt-image-1',
235 | 'o1-mini',
236 | 'o1-mini-2024-09-12',
237 |
238 | 'omni-moderation-2024-09-26',
239 | 'omni-moderation-latest',
240 | ]
241 | const newModels = [
242 | 'gpt-4.1',
243 | 'gpt-4.1-2025-04-14',
244 | 'gpt-4.1-mini',
245 | 'gpt-4.1-mini-2025-04-14',
246 | 'gpt-4.1-nano',
247 | 'gpt-4.1-nano-2025-04-14',
248 | 'gpt-4.5-preview',
249 | 'gpt-4.5-preview-2025-02-27',
250 | 'o1',
251 | 'o1-2024-12-17',
252 | 'o1-preview',
253 | 'o1-preview-2024-09-12',
254 | 'o1-pro',
255 | 'o1-pro-2025-03-19',
256 | 'o3',
257 | 'o3-2025-04-16',
258 | 'o3-mini',
259 | 'o3-mini-2025-01-31',
260 | 'o4-mini',
261 | 'o4-mini-2025-04-16',
262 | ]
263 | // 将 client 从一个值换成函数来惰性求值,这样只会在实际请求时(而不是创建列表时)创建 OpenAI 对象
264 | const client_builder = (model: string): IChat => {
265 | let base_client = new OpenAI({
266 | apiKey: env.OPENAI_API_KEY,
267 | })
268 | if (oldModels.includes(model)) {
269 | return openaiBase({ createClient: () => base_client })
270 | } else {
271 | return openaiResponse({ createClient: () => base_client })
272 | }
273 | }
274 | return {
275 | name: 'openai',
276 | supportModels: [...oldModels, ...newModels],
277 | requiredEnv: ['OPENAI_API_KEY'],
278 | invoke: (req) => client_builder(req.model).invoke(req),
279 | stream: (req, signal) => client_builder(req.model).stream(req, signal),
280 | }
281 | }
282 |
--------------------------------------------------------------------------------
/src/llm/openrouter.test.ts:
--------------------------------------------------------------------------------
1 | import { beforeEach, expect, it } from 'vitest'
2 | import OpenAI from 'openai'
3 | import { last } from 'lodash-es'
4 | import { IChat } from './base'
5 | import { openrouter } from './openrouter'
6 |
7 | let client: IChat
8 | beforeEach(() => {
9 | client = openrouter(import.meta.env)
10 | })
11 | it('invoke', async () => {
12 | const res = await client.invoke({
13 | model: 'openai/gpt-4o-mini',
14 | messages: [{ role: 'user', content: 'hello' }],
15 | temperature: 0,
16 | })
17 | expect(res.choices[0].message.content).not.undefined
18 | })
19 | it('stream usage', async () => {
20 | const res = client.stream(
21 | {
22 | model: 'openai/gpt-4o-mini',
23 | messages: [{ role: 'user', content: 'hello' }],
24 | temperature: 0,
25 | stream: true,
26 | },
27 | new AbortController().signal,
28 | )
29 | const r: OpenAI.Chat.Completions.ChatCompletionChunk[] = []
30 | for await (const chunk of res) {
31 | r.push(chunk)
32 | }
33 | const content = r.map((it) => it.choices[0]?.delta.content).join('')
34 | expect(last(r)!.usage).not.undefined
35 | expect(content).not.undefined
36 | })
37 |
--------------------------------------------------------------------------------
/src/llm/openrouter.ts:
--------------------------------------------------------------------------------
1 | import OpenAI from 'openai'
2 | import { IChat } from './base'
3 | import { openaiBase } from './openai'
4 |
5 | export function openrouter(env: Record): IChat {
6 | const r = openaiBase({
7 | createClient: () => {
8 | return new OpenAI({
9 | baseURL: 'https://openrouter.ai/api/v1',
10 | apiKey: env.OPENROUTER_API_KEY,
11 | })
12 | },
13 | })
14 | r.name = 'OpenRouter'
15 | r.supportModels = env.OPENROUTER_MODELS?.split(',').map((it) => it.trim()) ?? ['qwen-max']
16 | r.requiredEnv = ['OPENROUTER_API_KEY']
17 | return r
18 | }
19 |
--------------------------------------------------------------------------------
/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ESNext",
4 | "module": "ESNext",
5 | "moduleResolution": "Bundler",
6 | "strict": true,
7 | "skipLibCheck": true,
8 | "lib": [
9 | "ESNext"
10 | ],
11 | "types": [
12 | "@cloudflare/workers-types/2023-07-01"
13 | ],
14 | "jsx": "react-jsx",
15 | "jsxImportSource": "hono/jsx"
16 | },
17 | }
--------------------------------------------------------------------------------
/vitest.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vitest/config'
2 | import { config } from 'dotenv'
3 |
4 | config({ path: '.dev.vars' })
5 |
6 | export default defineConfig({
7 | test: {
8 | env: {
9 | ...process.env,
10 | },
11 | },
12 | })
13 |
--------------------------------------------------------------------------------
/wrangler.jsonc:
--------------------------------------------------------------------------------
1 | {
2 | "name": "openai-api-proxy",
3 | "main": "src/index.ts",
4 | "compatibility_date": "2024-08-22",
5 | "observability": {
6 | "enabled": true
7 | }
8 | }
9 |
--------------------------------------------------------------------------------