cruxx4 commited on
Commit
ae6975d
·
verified ·
1 Parent(s): 7bb0efb

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ logs
2
+ dist
3
+ doc
4
+ node_modules
5
+ .vscode
6
+ .git
7
+ .gitignore
8
+ README.md
9
+ *.tar.gz
.github/workflows/docker-image.yml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build and Push Docker Image
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+ workflow_dispatch:
7
+ inputs:
8
+ tag:
9
+ description: 'Tag Name'
10
+ required: true
11
+
12
+ jobs:
13
+ build-and-push:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v2
17
+
18
+ - name: Set up Docker Buildx
19
+ uses: docker/setup-buildx-action@v1
20
+
21
+ - name: Login to Docker Hub
22
+ uses: docker/login-action@v1
23
+ with:
24
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
25
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
26
+
27
+ - name: Set tag name
28
+ id: tag_name
29
+ run: |
30
+ if [ "${{ github.event_name }}" = "release" ]; then
31
+ echo "::set-output name=tag::${GITHUB_REF#refs/tags/}"
32
+ elif [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
33
+ echo "::set-output name=tag::${{ github.event.inputs.tag }}"
34
+ fi
35
+
36
+ - name: Build and push Docker image with Release tag
37
+ uses: docker/build-push-action@v2
38
+ with:
39
+ context: .
40
+ file: ./Dockerfile
41
+ push: true
42
+ tags: |
43
+ vinlic/kimi-free-api:${{ steps.tag_name.outputs.tag }}
44
+ vinlic/kimi-free-api:latest
45
+ platforms: linux/amd64,linux/arm64
46
+ build-args: TARGETPLATFORM=${{ matrix.platform }}
.github/workflows/sync.yml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upstream Sync
2
+
3
+ permissions:
4
+ contents: write
5
+ issues: write
6
+ actions: write
7
+
8
+ on:
9
+ schedule:
10
+ - cron: '0 * * * *' # every hour
11
+ workflow_dispatch:
12
+
13
+ jobs:
14
+ sync_latest_from_upstream:
15
+ name: Sync latest commits from upstream repo
16
+ runs-on: ubuntu-latest
17
+ if: ${{ github.event.repository.fork }}
18
+
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - name: Clean issue notice
23
+ uses: actions-cool/issues-helper@v3
24
+ with:
25
+ actions: 'close-issues'
26
+ labels: '🚨 Sync Fail'
27
+
28
+ - name: Sync upstream changes
29
+ id: sync
30
+ uses: aormsby/[email protected]
31
+ with:
32
+ upstream_sync_repo: LLM-Red-Team/kimi-free-api
33
+ upstream_sync_branch: master
34
+ target_sync_branch: master
35
+ target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
36
+ test_mode: false
37
+
38
+ - name: Sync check
39
+ if: failure()
40
+ uses: actions-cool/issues-helper@v3
41
+ with:
42
+ actions: 'create-issue'
43
+ title: '🚨 同步失败 | Sync Fail'
44
+ labels: '🚨 Sync Fail'
45
+ body: |
46
+ Due to a change in the workflow file of the LLM-Red-Team/kimi-free-api upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork. Please refer to the detailed [Tutorial][tutorial-en-US] for instructions.
47
+
48
+ 由于 LLM-Red-Team/kimi-free-api 上游仓库的 workflow 文件变更,导致 GitHub 自动暂停了本次自动更新,你需要手动 Sync Fork 一次,
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ dist/
2
+ node_modules/
3
+ logs/
4
+ .vercel
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:lts AS BUILD_IMAGE
2
+
3
+ WORKDIR /app
4
+
5
+ COPY . /app
6
+
7
+ RUN yarn install --registry https://registry.npmmirror.com/ && yarn run build
8
+
9
+ FROM node:lts-alpine
10
+
11
+ COPY --from=BUILD_IMAGE /app/public /app/public
12
+ COPY --from=BUILD_IMAGE /app/configs /app/configs
13
+ COPY --from=BUILD_IMAGE /app/package.json /app/package.json
14
+ COPY --from=BUILD_IMAGE /app/dist /app/dist
15
+ COPY --from=BUILD_IMAGE /app/node_modules /app/node_modules
16
+
17
+ RUN chmod -R 777 /app
18
+
19
+ WORKDIR /app
20
+
21
+ EXPOSE 7860
22
+
23
+ CMD ["npm", "start"]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md CHANGED
@@ -1,12 +1,530 @@
1
  ---
2
- title: Kimi
3
- emoji:
4
- colorFrom: purple
 
 
5
  colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.13.2
8
- app_file: app.py
9
- pinned: false
10
  ---
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: mit
3
+ title: KimiAI
4
+ sdk: docker
5
+ emoji: 🧪
6
+ colorFrom: blue
7
  colorTo: purple
 
 
 
 
8
  ---
9
+ # KIMI AI Free 服务
10
 
11
+
12
+ <hr>
13
+
14
+ <span>[ 中文 | <a href="README_EN.md">English</a> ]</span>
15
+
16
+
17
+ [![](https://img.shields.io/github/license/llm-red-team/kimi-free-api.svg)](LICENSE)
18
+ ![](https://img.shields.io/github/stars/llm-red-team/kimi-free-api.svg)
19
+ ![](https://img.shields.io/github/forks/llm-red-team/kimi-free-api.svg)
20
+ ![](https://img.shields.io/docker/pulls/vinlic/kimi-free-api.svg)
21
+
22
+ 支持高速流式输出、支持多轮对话、支持联网搜索、支持智能体对话、支持探索版、支持K1思考模型、支持长文档解读、支持图像解析,零配置部署,多路token支持,自动清理会话痕迹。
23
+
24
+ 与ChatGPT接口完全兼容。
25
+
26
+ 还有以下十个free-api欢迎关注:
27
+
28
+ 阶跃星辰 (跃问StepChat) 接口转API [step-free-api](https://github.com/LLM-Red-Team/step-free-api)
29
+
30
+ 阿里通义 (Qwen) 接口转API [qwen-free-api](https://github.com/LLM-Red-Team/qwen-free-api)
31
+
32
+ 智谱AI (智谱清言) 接口转API [glm-free-api](https://github.com/LLM-Red-Team/glm-free-api)
33
+
34
+ 秘塔AI (Metaso) 接口转API [metaso-free-api](https://github.com/LLM-Red-Team/metaso-free-api)
35
+
36
+ 字节跳动(豆包)接口转API [doubao-free-api](https://github.com/LLM-Red-Team/doubao-free-api)
37
+
38
+ 字节跳动(即梦AI)接口转API [jimeng-free-api](https://github.com/LLM-Red-Team/jimeng-free-api)
39
+
40
+ 讯飞星火(Spark)接口转API [spark-free-api](https://github.com/LLM-Red-Team/spark-free-api)
41
+
42
+ MiniMax(海螺AI)接口转API [hailuo-free-api](https://github.com/LLM-Red-Team/hailuo-free-api)
43
+
44
+ 深度求索(DeepSeek)接口转API [deepseek-free-api](https://github.com/LLM-Red-Team/deepseek-free-api)
45
+
46
+ 聆心智能 (Emohaa) 接口转API [emohaa-free-api](https://github.com/LLM-Red-Team/emohaa-free-api)(当前不可用)
47
+
48
+ ## 目录
49
+
50
+ * [免责声明](#免责声明)
51
+ * [效果示例](#效果示例)
52
+ * [接入准备](#接入准备)
53
+ * [多账号接入](#多账号接入)
54
+ * [Docker部署](#Docker部署)
55
+ * [Docker-compose部署](#Docker-compose部署)
56
+ * [Render部署](#Render部署)
57
+ * [Vercel部署](#Vercel部署)
58
+ * [Zeabur部署](#Zeabur部署)
59
+ * [原生部署](#原生部署)
60
+ * [推荐使用客户端](#推荐使用客户端)
61
+ * [接口列表](#接口列表)
62
+ * [对话补全](#对话补全)
63
+ * [文档解读](#文档解读)
64
+ * [图像解析](#图像解析)
65
+ * [refresh_token存活检测](#refresh_token存活检测)
66
+ * [注意事项](#注意事项)
67
+ * [Nginx反代优化](#Nginx反代优化)
68
+ * [Token统计](#Token统计)
69
+ * [Star History](#star-history)
70
+
71
+ ## 免责声明
72
+
73
+ **逆向API是不稳定的,建议前往MoonshotAI官方 https://platform.moonshot.cn/ 付费使用API,避免封禁的风险。**
74
+
75
+ **本组织和个人不接受任何资金捐助和交易,此项目是纯粹研究交流学习性质!**
76
+
77
+ **仅限自用,禁止对外提供服务或商用,避免对官方造成服务压力,否则风险自担!**
78
+
79
+ **仅限自用,禁止对外提供服务或商用,避免对官方造成服务压力,否则风险自担!**
80
+
81
+ **仅限自用,禁止对外提供服务或商用,避免对官方造成服务压力,否则风险自担!**
82
+
83
+ ## 效果示例
84
+
85
+ ### 验明正身Demo
86
+
87
+ ![验明正身](./doc/example-1.png)
88
+
89
+ ### 多轮对话Demo
90
+
91
+ ![多轮对话](./doc/example-6.png)
92
+
93
+ ### 联网搜索Demo
94
+
95
+ ![联网搜索](./doc/example-2.png)
96
+
97
+ ### 智能体对话Demo
98
+
99
+ 此处使用 [翻译通](https://kimi.moonshot.cn/chat/coo6l3pkqq4ri39f36bg) 智能体。
100
+
101
+ ![智能体对话](./doc/example-7.png)
102
+
103
+ ### 长文档解读Demo
104
+
105
+ ![长文档解读](./doc/example-5.png)
106
+
107
+ ### 图像OCR Demo
108
+
109
+ ![图像解析](./doc/example-3.png)
110
+
111
+ ### 响应流畅度一致
112
+
113
+ ![响应流畅度一致](https://github.com/LLM-Red-Team/kimi-free-api/assets/20235341/48c7ec00-2b03-46c4-95d0-452d3075219b)
114
+
115
+ ## 接入准备
116
+
117
+ 从 [kimi.moonshot.cn](https://kimi.moonshot.cn) 获取refresh_token
118
+
119
+ 进入kimi随便发起一个对话,然后F12打开开发者工具,从Application > Local Storage中找到`refresh_token`的值,这将作为Authorization的Bearer Token值:`Authorization: Bearer TOKEN`
120
+
121
+ ![example0](./doc/example-0.png)
122
+
123
+ 如果你看到的`refresh_token`是一个数组,请使用`.`拼接起来再使用。
124
+
125
+ ![example8](./doc/example-8.jpg)
126
+
127
+ ### 多账号接入
128
+
129
+ 目前kimi限制普通账号每3小时内只能进行30轮长文本的问答(短文本不限),你可以通过提供多个账号的refresh_token并使用`,`拼接提供:
130
+
131
+ `Authorization: Bearer TOKEN1,TOKEN2,TOKEN3`
132
+
133
+ 每次请求服务会从中挑选一个。
134
+
135
+ ## Docker部署
136
+
137
+ 请准备能够部署Docker镜像且能够访问网络的设备或服务器,并将8000端口开放。
138
+
139
+ 拉取镜像并启动服务
140
+
141
+ ```shell
142
+ docker run -it -d --init --name kimi-free-api -p 8000:8000 -e TZ=Asia/Shanghai vinlic/kimi-free-api:latest
143
+ ```
144
+
145
+ 查看服务实时日志
146
+
147
+ ```shell
148
+ docker logs -f kimi-free-api
149
+ ```
150
+
151
+ 重启服务
152
+
153
+ ```shell
154
+ docker restart kimi-free-api
155
+ ```
156
+
157
+ 停止服务
158
+
159
+ ```shell
160
+ docker stop kimi-free-api
161
+ ```
162
+
163
+ ### Docker-compose部署
164
+
165
+ ```yaml
166
+ version: '3'
167
+
168
+ services:
169
+ kimi-free-api:
170
+ container_name: kimi-free-api
171
+ image: vinlic/kimi-free-api:latest
172
+ restart: always
173
+ ports:
174
+ - "8000:8000"
175
+ environment:
176
+ - TZ=Asia/Shanghai
177
+ ```
178
+
179
+ ### Render部署
180
+
181
+ **注意:部分部署区域可能无法连接kimi,如容器日志出现请求超时或无法连接(新加坡实测不可用)请切换其他区域部署!**
182
+ **注意:免费账户的容器实例将在一段时间不活动时自动停止运行,这会导致下次请求时遇到50秒或更长的延迟,建议查看[Render容器保活](https://github.com/LLM-Red-Team/free-api-hub/#Render%E5%AE%B9%E5%99%A8%E4%BF%9D%E6%B4%BB)**
183
+
184
+ 1. fork本项目到你的github账号下。
185
+
186
+ 2. 访问 [Render](https://dashboard.render.com/) 并登录你的github账号。
187
+
188
+ 3. 构建你的 Web Service(New+ -> Build and deploy from a Git repository -> Connect你fork的项目 -> 选择部署区域 -> 选择实例类型为Free -> Create Web Service)。
189
+
190
+ 4. 等待构建完成后,复制分配的域名并拼接URL访问即可。
191
+
192
+ ### Vercel部署
193
+
194
+ **注意:Vercel免费账户的请求响应超时时间为10秒,但接口响应通常较久,可能会遇到Vercel返回的504超时错误!**
195
+
196
+ 请先确保安装了Node.js环境。
197
+
198
+ ```shell
199
+ npm i -g vercel --registry http://registry.npmmirror.com
200
+ vercel login
201
+ git clone https://github.com/LLM-Red-Team/kimi-free-api
202
+ cd kimi-free-api
203
+ vercel --prod
204
+ ```
205
+
206
+ ### Zeabur部署
207
+
208
+ **注意:免费账户的容器实例可能无法稳定运行**
209
+
210
+ [![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/GRFYBP)
211
+
212
+ ## 原生部署
213
+
214
+ 请准备一台具有公网IP的服务器并将8000端口开放。
215
+
216
+ 请先安装好Node.js环境并且配置好环境变量,确认node命令可用。
217
+
218
+ 安装依赖
219
+
220
+ ```shell
221
+ npm i
222
+ ```
223
+
224
+ 安装PM2进行进程守护
225
+
226
+ ```shell
227
+ npm i -g pm2
228
+ ```
229
+
230
+ 编译构建,看到dist目录就是构建完成
231
+
232
+ ```shell
233
+ npm run build
234
+ ```
235
+
236
+ 启动服务
237
+
238
+ ```shell
239
+ pm2 start dist/index.js --name "kimi-free-api"
240
+ ```
241
+
242
+ 查看服务实时日志
243
+
244
+ ```shell
245
+ pm2 logs kimi-free-api
246
+ ```
247
+
248
+ 重启服务
249
+
250
+ ```shell
251
+ pm2 reload kimi-free-api
252
+ ```
253
+
254
+ 停止服务
255
+
256
+ ```shell
257
+ pm2 stop kimi-free-api
258
+ ```
259
+
260
+ ## 推荐使用客户端
261
+
262
+ 使用以下二次开发客户端接入free-api系列项目更快更简单,支持文档/图像上传!
263
+
264
+ 由 [Clivia](https://github.com/Yanyutin753/lobe-chat) 二次开发的LobeChat [https://github.com/Yanyutin753/lobe-chat](https://github.com/Yanyutin753/lobe-chat)
265
+
266
+ 由 [时光@](https://github.com/SuYxh) 二次开发的ChatGPT Web [https://github.com/SuYxh/chatgpt-web-sea](https://github.com/SuYxh/chatgpt-web-sea)
267
+
268
+ ## 接口列表
269
+
270
+ 目前支持与openai兼容的 `/v1/chat/completions` 接口,可自行使用与openai或其他兼容的客户端接入接口,或者使用 [dify](https://dify.ai/) 等线上服务接入使用。
271
+
272
+ ### 对话补全
273
+
274
+ 对话补全接口,与openai的 [chat-completions-api](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) 兼容。
275
+
276
+ **POST /v1/chat/completions**
277
+
278
+ header 需要设置 Authorization 头部:
279
+
280
+ ```
281
+ Authorization: Bearer [refresh_token]
282
+ ```
283
+
284
+ 请求数据:
285
+ ```json
286
+ {
287
+ // 模型名称
288
+ // kimi:默认模型
289
+ // kimi-search:联网检索模型
290
+ // kimi-research:探索版模型
291
+ // kimi-k1:K1模型
292
+ // kimi-math:数学模型
293
+ // kimi-silent:不输出检索过程模型
294
+ // search/research/k1/math/silent:可自由组合使用
295
+ // 如果使用kimi+智能体,model请填写智能体ID,就是浏览器地址栏上尾部的一串英文+数字20个字符的ID
296
+ "model": "kimi",
297
+ // 目前多轮对话基于消息合并实现,某些场景可能导致能力下降且受单轮最大Token数限制
298
+ // 如果您想获得原生的多轮对话体验,可以传入首轮消息获得的id,来接续上下文,注意如果使用这个,首轮必须传none,否则第二轮会空响应!
299
+ // "conversation_id": "cnndivilnl96vah411dg",
300
+ "messages": [
301
+ {
302
+ "role": "user",
303
+ "content": "测试"
304
+ }
305
+ ],
306
+ // 是否开启联网搜索,默认false
307
+ "use_search": true,
308
+ // 如果使用SSE流请设置为true,默认false
309
+ "stream": false
310
+ }
311
+ ```
312
+
313
+ 响应数据:
314
+ ```json
315
+ {
316
+ // 如果想获得原生多轮对话体验,此id,你可以传入到下一轮对话的conversation_id来接续上下文
317
+ "id": "cnndivilnl96vah411dg",
318
+ "model": "kimi",
319
+ "object": "chat.completion",
320
+ "choices": [
321
+ {
322
+ "index": 0,
323
+ "message": {
324
+ "role": "assistant",
325
+ "content": "你好!我是Kimi,由月之暗面科技有限公司开发的人工智能助手。我擅长中英文对话,可以帮助你获取信息、解答疑问,还能阅读和理解你提供的文件和网页内容。如果你有任何问题或需要帮助,随时告诉我!"
326
+ },
327
+ "finish_reason": "stop"
328
+ }
329
+ ],
330
+ "usage": {
331
+ "prompt_tokens": 1,
332
+ "completion_tokens": 1,
333
+ "total_tokens": 2
334
+ },
335
+ "created": 1710152062
336
+ }
337
+ ```
338
+
339
+ ### 文档解读
340
+
341
+ 提供一个可访问的文件URL或者BASE64_URL进行解析。
342
+
343
+ **POST /v1/chat/completions**
344
+
345
+ header 需要设置 Authorization 头部:
346
+
347
+ ```
348
+ Authorization: Bearer [refresh_token]
349
+ ```
350
+
351
+ 请求数据:
352
+ ```json
353
+ {
354
+ // 模型名称
355
+ // kimi:默认模型
356
+ // kimi-search:联网检索模型
357
+ // kimi-research:探索版模型
358
+ // kimi-k1:K1模型
359
+ // kimi-math:数学模型
360
+ // kimi-silent:不输出检索过程模型
361
+ // search/research/k1/math/silent:可自由组合使用
362
+ // 如果使用kimi+智能体,model请填写智能体ID,就是浏览器地址栏上尾部的一串英文+数字20个字符的ID
363
+ "model": "kimi",
364
+ "messages": [
365
+ {
366
+ "role": "user",
367
+ "content": [
368
+ {
369
+ "type": "file",
370
+ "file_url": {
371
+ "url": "https://mj101-1317487292.cos.ap-shanghai.myqcloud.com/ai/test.pdf"
372
+ }
373
+ },
374
+ {
375
+ "type": "text",
376
+ "text": "文档里说了什么?"
377
+ }
378
+ ]
379
+ }
380
+ ],
381
+ // 建议关闭联网搜索,防止干扰解读结果
382
+ "use_search": false
383
+ }
384
+ ```
385
+
386
+ 响应数据:
387
+ ```json
388
+ {
389
+ "id": "cnmuo7mcp7f9hjcmihn0",
390
+ "model": "kimi",
391
+ "object": "chat.completion",
392
+ "choices": [
393
+ {
394
+ "index": 0,
395
+ "message": {
396
+ "role": "assistant",
397
+ "content": "文档中包含了几个古代魔法咒语的例子,这些咒语来自古希腊和罗马时期的魔法文本,被称为PGM(Papyri Graecae Magicae)。以下是文档中提到的几个咒语的内容:\n\n1. 第一个咒语(PMG 4.1390 – 1495)描述了一个仪式,要求留下一些你吃剩的面包,将其分成七块小片,然后去到英雄、角斗士和那些死于非命的人被杀的地方。对面包片念咒并扔出去,然后从仪式地点捡起一些被污染的泥土扔进你心仪的女人的家中,之后去睡觉。咒语的内容是向命运女神(Moirai)、罗马的命运女神(Fates)和自然力量(Daemons)祈求,希望他们帮助实现愿望。\n\n2. 第二个咒语(PMG 4.1342 – 57)是一个召唤咒语,通过念出一系列神秘的名字和词语来召唤一个名为Daemon的存在,以使一个名为Tereous的人(由Apia所生)受到精神和情感上的折磨,直到她来到施法者Didymos(由Taipiam所生)的身边。\n\n3. 第三个咒语(PGM 4.1265 – 74)提到了一个名为NEPHERIĒRI的神秘名字,这个名字与爱神阿佛洛狄忒(Aphrodite)有关。为了赢得一个美丽女人的心,需要保持三天的纯洁,献上乳香,并在献祭时念出这个名字。然后,在接近那位女士时,心中默念这个名字七次,连续七天这样做,以期成功。\n\n4. 第四个咒语(PGM 4.1496 – 1)描述了在燃烧没药(myrrh)时念诵的咒语。这个咒语是向没药祈祷,希望它能够像“肉食者”和“心灵点燃者”一样,吸引一个名为[名字]的女人(她的母亲名为[名字]),让她无法安坐、饮食、注视或亲吻其他人,而是让她的心中只有施法者,直到她来到施法者身边。\n\n这些咒语反映了古代人们对魔法和超自然力量的信仰,以及他们试图通过这些咒语来影响他人情感和行为的方式。"
398
+ },
399
+ "finish_reason": "stop"
400
+ }
401
+ ],
402
+ "usage": {
403
+ "prompt_tokens": 1,
404
+ "completion_tokens": 1,
405
+ "total_tokens": 2
406
+ },
407
+ "created": 100920
408
+ }
409
+ ```
410
+
411
+ ### 图像OCR
412
+
413
+ 提供一个可访问的图像URL或者BASE64_URL进行解析。
414
+
415
+ 此格式兼容 [gpt-4-vision-preview](https://platform.openai.com/docs/guides/vision) API格式,您也可以用这个格式传送文档进行解析。
416
+
417
+ **POST /v1/chat/completions**
418
+
419
+ header 需要设置 Authorization 头部:
420
+
421
+ ```
422
+ Authorization: Bearer [refresh_token]
423
+ ```
424
+
425
+ 请求数据:
426
+ ```json
427
+ {
428
+ // 模型名称
429
+ // kimi:默认模型
430
+ // kimi-search:联网检索模型
431
+ // kimi-research:探索版模型
432
+ // kimi-k1:K1模型
433
+ // kimi-math:数学模型
434
+ // kimi-silent:不输出检索过程模型
435
+ // search/research/k1/math/silent:可自由组合使用
436
+ // 如果使用kimi+智能体,model请填写智能体ID,就是浏览器地址栏上尾部的一串英文+数字20个字符的ID
437
+ "model": "kimi",
438
+ "messages": [
439
+ {
440
+ "role": "user",
441
+ "content": [
442
+ {
443
+ "type": "image_url",
444
+ "image_url": {
445
+ "url": "https://www.moonshot.cn/assets/logo/normal-dark.png"
446
+ }
447
+ },
448
+ {
449
+ "type": "text",
450
+ "text": "图像描述了什么?"
451
+ }
452
+ ]
453
+ }
454
+ ],
455
+ // 建议关闭联网搜索,防止干扰解读结果
456
+ "use_search": false
457
+ }
458
+ ```
459
+
460
+ 响应数据:
461
+ ```json
462
+ {
463
+ "id": "cnn6l8ilnl92l36tu8ag",
464
+ "model": "kimi",
465
+ "object": "chat.completion",
466
+ "choices": [
467
+ {
468
+ "index": 0,
469
+ "message": {
470
+ "role": "assistant",
471
+ "content": "图像中展示了“Moonshot AI”的字样,这可能是月之暗面科技有限公司(Moonshot AI)的标志或者品牌标识。通常这样的图像用于代表公司或产品,传达品牌信息。由于图像是PNG格式,它可能是一个透明背景的logo,用于网站、应用程序或其他视觉材料中。"
472
+ },
473
+ "finish_reason": "stop"
474
+ }
475
+ ],
476
+ "usage": {
477
+ "prompt_tokens": 1,
478
+ "completion_tokens": 1,
479
+ "total_tokens": 2
480
+ },
481
+ "created": 1710123627
482
+ }
483
+ ```
484
+
485
+ ### refresh_token存活检测
486
+
487
+ 检测refresh_token是否存活,如果存活live为true,否则为false,请不要频繁(小于10分钟)调用此接口。
488
+
489
+ **POST /token/check**
490
+
491
+ 请求数据:
492
+ ```json
493
+ {
494
+ "token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..."
495
+ }
496
+ ```
497
+
498
+ 响应数据:
499
+ ```json
500
+ {
501
+ "live": true
502
+ }
503
+ ```
504
+
505
+ ## 注意事项
506
+
507
+ ### Nginx反代优化
508
+
509
+ 如果您正在使用Nginx反向代理kimi-free-api,请添加以下配置项优化流的输出效果,优化体验感。
510
+
511
+ ```nginx
512
+ # 关闭代理缓冲。当设置为off时,Nginx会立即将客户端请求发送到后端服务器,并立即将从后端服务器接收到的响应发送回客户端。
513
+ proxy_buffering off;
514
+ # 启用分块传输编码。分块传输编码允许服务器为动态生成的内容分块发送数据,而不需要预先知道内容的大小。
515
+ chunked_transfer_encoding on;
516
+ # 开启TCP_NOPUSH,这告诉Nginx在数据包发送到客户端之前,尽可能地发送数据。这通常在sendfile使用时配合使用,可以提高网络效率。
517
+ tcp_nopush on;
518
+ # 开启TCP_NODELAY,这告诉Nginx不延迟发送数据,立即发送小数据包。在某些情况下,这可以减少网络的延迟。
519
+ tcp_nodelay on;
520
+ # 设置保持连接的超时时间,这里设置为120秒。如果在这段时间内,客户端和服务器之间没有进一步的通信,连接将被关闭。
521
+ keepalive_timeout 120;
522
+ ```
523
+
524
+ ### Token统计
525
+
526
+ 由于推理侧不在kimi-free-api,因此token不可统计,将以固定数字返回!!!!!
527
+
528
+ ## Star History
529
+
530
+ [![Star History Chart](https://api.star-history.com/svg?repos=LLM-Red-Team/kimi-free-api&type=Date)](https://star-history.com/#LLM-Red-Team/kimi-free-api&Date)
README_EN.md ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KIMI AI Free Service
2
+
3
+
4
+ <hr>
5
+
6
+ [![](https://img.shields.io/github/license/llm-red-team/kimi-free-api.svg)](LICENSE)
7
+ ![](https://img.shields.io/github/stars/llm-red-team/kimi-free-api.svg)
8
+ ![](https://img.shields.io/github/forks/llm-red-team/kimi-free-api.svg)
9
+ ![](https://img.shields.io/docker/pulls/vinlic/kimi-free-api.svg)
10
+
11
+ Supports high-speed streaming output, multi-turn dialogues, internet search, long document reading, image analysis, zero-configuration deployment, multi-token support, and automatic session trace cleanup.
12
+
13
+ Fully compatible with the ChatGPT interface.
14
+
15
+ Also, the following free APIs are available for your attention:
16
+
17
+ StepFun (StepChat) API to API [step-free-api](https://github.com/LLM-Red-Team/step-free-api)
18
+
19
+ Ali Tongyi (Qwen) API to API [qwen-free-api](https://github.com/LLM-Red-Team/qwen-free-api)
20
+
21
+ ZhipuAI (ChatGLM) API to API [glm-free-api](https://github.com/LLM-Red-Team/glm-free-api)
22
+
23
+ Meta Sota (metaso) API to API [metaso-free-api](https://github.com/LLM-Red-Team/metaso-free-api)
24
+
25
+ Iflytek Spark (Spark) API to API [spark-free-api](https://github.com/LLM-Red-Team/spark-free-api)
26
+
27
+ Lingxin Intelligence (Emohaa) API to API [emohaa-free-api](https://github.com/LLM-Red-Team/emohaa-free-api) (OUT OF ORDER)
28
+
29
+ ## Table of Contents
30
+
31
+ * [Announcement](#Announcement)
32
+ * [Online experience](#Online-Experience)
33
+ * [Effect Examples](#Effect-Examples)
34
+ * [Access preparation](#Access-Preparation)
35
+ * [Multiple account access](#Multi-Account-Access)
36
+ * [Docker Deployment](#Docker-Deployment)
37
+ * [Docker-compose Deployment](#Docker-compose-Deployment)
38
+ * [Render Deployment](Render-Deployment)
39
+ * [Vercel Deployment](#Vercel-Deployment)
40
+ * [Zeabur Deployment](#Zeabur-Deployment)
41
+ * [Native Deployment](#Native-Deployment)
42
+ * [Interface List](#Interface-List)
43
+ * [Conversation completion](#conversation-completion)
44
+ * [Document Interpretation](#document-interpretation)
45
+ * [Image analysis](#image-analysis)
46
+ * [refresh_token survival detection](#refresh_token-survival-detection)
47
+ * [Precautions](#Precautions)
48
+ * [Nginx anti-generation optimization](#Nginx-anti-generation-optimization)
49
+ * [Token statistics](#Token-statistics)
50
+ * [Star History](#star-history)
51
+
52
+ ## Announcement
53
+
54
+ **This API is unstable. So we highly recommend you go to the [MoonshotAI](https://platform.moonshot.cn/) use the offical API, avoiding banned.**
55
+
56
+ **This organization and individuals do not accept any financial donations and transactions. This project is purely for research, communication, and learning purposes!**
57
+
58
+ **For personal use only, it is forbidden to provide services or commercial use externally to avoid causing service pressure on the official, otherwise, bear the risk yourself!**
59
+
60
+ **For personal use only, it is forbidden to provide services or commercial use externally to avoid causing service pressure on the official, otherwise, bear the risk yourself!**
61
+
62
+ **For personal use only, it is forbidden to provide services or commercial use externally to avoid causing service pressure on the official, otherwise, bear the risk yourself!**
63
+
64
+ ## Online Experience
65
+
66
+ This link is only for temporary testing of functions and cannot be used for a long time. For long-term use, please deploy by yourself.
67
+
68
+ https://udify.app/chat/Po0F6BMJ15q5vu2P
69
+
70
+ ## Effect Examples
71
+
72
+ ### Identity Verification
73
+
74
+ ![Identity Verification](./doc/example-1.png)
75
+
76
+ ### Multi-turn Dialogue
77
+
78
+ ![Multi-turn Dialogue](./doc/example-6.png)
79
+
80
+ ### Internet Search
81
+
82
+ ![Internet Search](./doc/example-2.png)
83
+
84
+ ### Long Document Reading
85
+
86
+ ![Long Document Reading](./doc/example-5.png)
87
+
88
+ ### Image Analysis
89
+
90
+ ![Image Analysis](./doc/example-3.png)
91
+
92
+ ### Consistent Responsiveness
93
+
94
+ ![Consistent Responsiveness](https://github.com/LLM-Red-Team/kimi-free-api/assets/20235341/48c7ec00-2b03-46c4-95d0-452d3075219b)
95
+
96
+ ## Access Preparation
97
+
98
+ Get the `refresh_token` from [kimi.moonshot.cn](https://kimi.moonshot.cn)
99
+
100
+ Start a conversation with kimi at will, then open the developer tool with F12, and find the value of `refresh_token` from Application > Local Storage, which will be used as the value of the Bearer Token in Authorization: `Authorization: Bearer TOKEN`
101
+
102
+ ![example0](./doc/example-0.png)
103
+
104
+ If you see `refresh_token` as an array, please use `.` to join it before using.
105
+
106
+ ![example8](./doc/example-8.jpg)
107
+
108
+ ### Multi-Account Access
109
+
110
+ Currently, kimi limits ordinary accounts to only 30 rounds of long-text Q&A within every 3 hours (short text is unlimited). You can provide multiple account refresh_tokens and use `,` to join them:
111
+
112
+ `Authorization: Bearer TOKEN1,TOKEN2,TOKEN3`
113
+
114
+ The service will pick one each time a request is made.
115
+
116
+ ## Docker Deployment
117
+
118
+ Please prepare a server with a public IP and open port 8000.
119
+
120
+ Pull the image and start the service
121
+
122
+ ```shell
123
+ docker run -it -d --init --name kimi-free-api -p 8000:8000 -e TZ=Asia/Shanghai vinlic/kimi-free-api:latest
124
+ ```
125
+
126
+ check real-time service logs
127
+
128
+ ```shell
129
+ docker logs -f kimi-free-api
130
+ ```
131
+
132
+ Restart service
133
+
134
+ ```shell
135
+ docker restart kimi-free-api
136
+ ```
137
+
138
+ Shut down service
139
+
140
+ ```shell
141
+ docker stop kimi-free-api
142
+ ```
143
+
144
+ ### Docker-compose Deployment
145
+
146
+ ```yaml
147
+ version: '3'
148
+
149
+ services:
150
+ kimi-free-api:
151
+ container_name: kimi-free-api
152
+ image: vinlic/kimi-free-api:latest
153
+ restart: always
154
+ ports:
155
+ - "8000:8000"
156
+ environment:
157
+ - TZ=Asia/Shanghai
158
+ ```
159
+
160
+ ### Render Deployment
161
+
162
+ **Attention: Some deployment regions may not be able to connect to Kimi. If container logs show request timeouts or connection failures (Singapore has been tested and found unavailable), please switch to another deployment region!**
163
+
164
+ **Attention Container instances for free accounts will automatically stop after a period of inactivity, which may result in a 50-second or longer delay during the next request. It is recommended to check [Render Container Keepalive](https://github.com/LLM-Red-Team/free-api-hub/#Render%E5%AE%B9%E5%99%A8%E4%BF%9D%E6%B4%BB)**
165
+
166
+ 1. Fork this project to your GitHub account.
167
+
168
+ 2. Visit [Render](https://dashboard.render.com/) and log in with your GitHub account.
169
+
170
+ 3. Build your Web Service (New+ -> Build and deploy from a Git repository -> Connect your forked project -> Select deployment region -> Choose instance type as Free -> Create Web Service).
171
+
172
+ 4. After the build is complete, copy the assigned domain and append the URL to access it.
173
+
174
+ ### Vercel Deployment
175
+ **Note: Vercel free accounts have a request response timeout of 10 seconds, but interface responses are usually longer, which may result in a 504 timeout error from Vercel!**
176
+
177
+ Please ensure that Node.js environment is installed first.
178
+ ```shell
179
+ npm i -g vercel --registry http://registry.npmmirror.com
180
+ vercel login
181
+ git clone https://github.com/LLM-Red-Team/kimi-free-api
182
+ cd kimi-free-api
183
+ vercel --prod
184
+ ```
185
+
186
+ ### Zeabur Deployment
187
+
188
+ [![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/GRFYBP)
189
+
190
+ ## Native Deployment
191
+
192
+ Please prepare a server with a public IP and open port 8000.
193
+
194
+ Please install the Node.js environment and configure the environment variables first, and confirm that the node command is available.
195
+
196
+ Install dependencies
197
+
198
+ ```shell
199
+ npm i
200
+ ```
201
+
202
+ Install PM2 for process guarding
203
+
204
+ ```shell
205
+ npm i -g pm2
206
+ ```
207
+
208
+ Compile and build. When you see the dist directory, the build is complete.
209
+
210
+ ```shell
211
+ npm run build
212
+ ```
213
+
214
+ Start service
215
+
216
+ ```shell
217
+ pm2 start dist/index.js --name "kimi-free-api"
218
+ ```
219
+
220
+ View real-time service logs
221
+
222
+ ```shell
223
+ pm2 logs kimi-free-api
224
+ ```
225
+
226
+ Restart service
227
+
228
+ ```shell
229
+ pm2 reload kimi-free-api
230
+ ```
231
+
232
+ Shut down service
233
+
234
+ ```shell
235
+ pm2 stop kimi-free-api
236
+ ```
237
+
238
+ ## Recommended Clients
239
+
240
+ Using the following second-developed clients for free-api series projects is faster and easier, and supports document/image uploads!
241
+
242
+ [Clivia](https://github.com/Yanyutin753/lobe-chat)'s modified LobeChat [https://github.com/Yanyutin753/lobe-chat](https://github.com/Yanyutin753/lobe-chat)
243
+
244
+ [Time@](https://github.com/SuYxh)'s modified ChatGPT Web [https://github.com/SuYxh/chatgpt-web-sea](https://github.com/SuYxh/chatgpt-web-sea)
245
+
246
+ ## interface list
247
+
248
+ Currently, the `/v1/chat/completions` interface compatible with openai is supported. You can use the client access interface compatible with openai or other clients, or use online services such as [dify](https://dify.ai/) Access and use.
249
+
250
+ ### Conversation completion
251
+
252
+ Conversation completion interface, compatible with openai's [chat-completions-api](https://platform.openai.com/docs/guides/text-generation/chat-completions-api).
253
+
254
+ **POST /v1/chat/completions**
255
+
256
+ The header needs to set the Authorization header:
257
+ ```
258
+ Authorization: Bearer [refresh_token]
259
+ ```
260
+
261
+ Request data:
262
+ ```json
263
+ {
264
+ // Model name
265
+ // kimi: default model
266
+ // kimi-search: online search model
267
+ // kimi-research: exploration version model
268
+ // kimi-k1: K1 model
269
+ // kimi-math: math model
270
+ // kimi-silent: model without search process output
271
+ // search/research/k1/math/silent: can be freely combined
272
+ // If using kimi+agent, fill in the agent ID for model, which is the 20-character ID of letters and numbers at the end of the browser address bar
273
+ "model": "kimi",
274
+ "messages": [
275
+ {
276
+ "role": "user",
277
+ "content": "test"
278
+ }
279
+ ],
280
+ // Whether to enable online search, default false
281
+ "use_search": true,
282
+ // If using SSE stream, please set it to true, the default is false
283
+ "stream": false
284
+ }
285
+ ```
286
+
287
+ Response data:
288
+
289
+ ```json
290
+ {
291
+ "id": "cnndivilnl96vah411dg",
292
+ "model": "kimi",
293
+ "object": "chat.completion",
294
+ "choices": [
295
+ {
296
+ "index": 0,
297
+ "message": {
298
+ "role": "assistant",
299
+ "content": "Hello! I am Kimi, an artificial intelligence assistant developed by Dark Side of the Moon Technology Co., Ltd. I am good at conversation in Chinese and English. I can help you obtain information, answer questions, and read and understand the documents you provide. and web content. If you have any questions or need help, feel free to let me know!"
300
+ },
301
+ "finish_reason": "stop"
302
+ }
303
+ ],
304
+ "usage": {
305
+ "prompt_tokens": 1,
306
+ "completion_tokens": 1,
307
+ "total_tokens": 2
308
+ },
309
+ "created": 1710152062
310
+ }
311
+ ```
312
+
313
+ ### Document interpretation
314
+
315
+ Provide an accessible file URL or BASE64_URL to parse.
316
+
317
+ **POST /v1/chat/completions**
318
+
319
+ The header needs to set the Authorization header:
320
+
321
+ ```
322
+ Authorization: Bearer [refresh_token]
323
+ ```
324
+
325
+ Request data:
326
+ ```json
327
+ {
328
+ // Model name
329
+ // kimi: default model
330
+ // kimi-search: online search model
331
+ // kimi-research: exploration version model
332
+ // kimi-k1: K1 model
333
+ // kimi-math: math model
334
+ // kimi-silent: model without search process output
335
+ // search/research/k1/math/silent: can be freely combined
336
+ // If using kimi+agent, fill in the agent ID for model, which is the 20-character ID of letters and numbers at the end of the browser address bar
337
+ "model": "kimi",
338
+ "messages": [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "file",
344
+ "file_url": {
345
+ "url": "https://mj101-1317487292.cos.ap-shanghai.myqcloud.com/ai/test.pdf"
346
+ }
347
+ },
348
+ {
349
+ "type": "text",
350
+ "text": "What does the document say?"
351
+ }
352
+ ]
353
+ }
354
+ ],
355
+ // It is recommended to turn off online search to prevent interference in interpreting results.
356
+ "use_search": false
357
+ }
358
+ ```
359
+
360
+ Response data:
361
+ ```json
362
+ {
363
+ "id": "cnmuo7mcp7f9hjcmihn0",
364
+ "model": "kimi",
365
+ "object": "chat.completion",
366
+ "choices": [
367
+ {
368
+ "index": 0,
369
+ "message": {
370
+ "role": "assistant",
371
+ "content": "The document contains several examples of ancient magical spells from magical texts from the ancient Greek and Roman periods known as PGM (Papyri Graecae Magicae). The following are examples of several spells mentioned in the document Contents:\n\n1. The first spell (PMG 4.1390 – 1495) describes a ritual that requires leaving some of your leftover bread, dividing it into seven small pieces, and then going to the heroes, gladiators, and those who died violent deaths The place where people were killed. Spell a spell on the piece of bread and throw it out, then pick up some contaminated soil from the ritual site and throw it into the home of the woman you like, then go to sleep. The content of the spell is to pray to the goddess of fate (Moirai), The Roman goddesses of Fates and the forces of nature (Daemons) were invoked to help make wishes come true.\n\n2. The second incantation (PMG 4.1342 – 57) was a summoning spell performed by speaking a series of mystical names and Words to summon a being called Daemon to cause a person named Tereous (born from Apia) to be mentally and emotionally tortured until she came to the spellcaster Didymos (born from Taipiam).\n \n3. The third spell (PGM 4.1265 – 74) mentions a mysterious name called NEPHERIĒRI, which is related to Aphrodite, the goddess of love. In order to win the heart of a beautiful woman, one needs to keep it for three days of purity, offer frankincense and recite the name while offering the offering. Then, as you approach the lady, recite the name silently seven times in your mind and do this for seven consecutive days with the hope of success.\n\n4. The fourth mantra ( PGM 4.1496 – 1) describes an incantation recited while burning myrrh. This incantation is a prayer to myrrh in the hope that it will attract a person named [name ] woman (her mother's name was [name]), making her unable to sit, eat, look at or kiss other people, but instead had only the caster in her mind until she came to the caster.\n\nThese Spells reflect ancient people's beliefs in magic and supernatural powers, and the ways in which they attempted to influence the emotions and behavior of others through these spells."
372
+ },
373
+ "finish_reason": "stop"
374
+ }
375
+ ],
376
+ "usage": {
377
+ "prompt_tokens": 1,
378
+ "completion_tokens": 1,
379
+ "total_tokens": 2
380
+ },
381
+ "created": 100920
382
+ }
383
+ ```
384
+
385
+ ### Image analysis
386
+
387
+ Provide an accessible image URL or BASE64_URL to parse.
388
+
389
+ This format is compatible with the [gpt-4-vision-preview](https://platform.openai.com/docs/guides/vision) API format. You can also use this format to transmit documents for parsing.
390
+
391
+ **POST /v1/chat/completions**
392
+
393
+ The header needs to set the Authorization header:
394
+
395
+ ```
396
+ Authorization: Bearer [refresh_token]
397
+ ```
398
+
399
+ Request data:
400
+ ```json
401
+ {
402
+ // Model name
403
+ // kimi: default model
404
+ // kimi-search: online search model
405
+ // kimi-research: exploration version model
406
+ // kimi-k1: K1 model
407
+ // kimi-math: math model
408
+ // kimi-silent: model without search process output
409
+ // search/research/k1/math/silent: can be freely combined
410
+ // If using kimi+agent, fill in the agent ID for model, which is the 20-character ID of letters and numbers at the end of the browser address bar
411
+ "model": "kimi",
412
+ "messages": [
413
+ {
414
+ "role": "user",
415
+ "content": [
416
+ {
417
+ "type": "image_url",
418
+ "image_url": {
419
+ "url": "https://www.moonshot.cn/assets/logo/normal-dark.png"
420
+ }
421
+ },
422
+ {
423
+ "type": "text",
424
+ "text": "What does the image describe?"
425
+ }
426
+ ]
427
+ }
428
+ ],
429
+ // It is recommended to turn off online search to prevent interference in interpreting results.
430
+ "use_search": false
431
+ }
432
+ ```
433
+
434
+ Response data:
435
+ ```json
436
+ {
437
+ "id": "cnn6l8ilnl92l36tu8ag",
438
+ "model": "kimi",
439
+ "object": "chat.completion",
440
+ "choices": [
441
+ {
442
+ "index": 0,
443
+ "message": {
444
+ "role": "assistant",
445
+ "content": "The image shows the words "Moonshot AI", which may be the logo or brand identity of Dark Side of the Moon Technology Co., Ltd. (Moonshot AI). Usually such images are used to represent a company or product and convey brand information .Since the image is in PNG format, it could be a logo with a transparent background, used on a website, app, or other visual material."
446
+ },
447
+ "finish_reason": "stop"
448
+ }
449
+ ],
450
+ "usage": {
451
+ "prompt_tokens": 1,
452
+ "completion_tokens": 1,
453
+ "total_tokens": 2
454
+ },
455
+ "created": 1710123627
456
+ }
457
+
458
+ ```
459
+ ### refresh_token survival detection
460
+
461
+ Check whether refresh_token is alive. If live is not true, otherwise it is false. Please do not call this interface frequently (less than 10 minutes).
462
+
463
+ **POST /token/check**
464
+
465
+ Request data:
466
+ ```json
467
+ {
468
+ "token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9..."
469
+ }
470
+ ```
471
+
472
+ Response data:
473
+ ```json
474
+ {
475
+ "live": true
476
+ }
477
+ ```
478
+
479
+ ## Notification
480
+
481
+ ### Nginx anti-generation optimization
482
+
483
+ If you are using Nginx reverse proxy kimi-free-api, please add the following configuration items to optimize the output effect of the stream and optimize the experience.
484
+
485
+ ```nginx
486
+ # Turn off proxy buffering. When set to off, Nginx will immediately send client requests to the backend server and immediately send responses received from the backend server back to the client.
487
+ proxy_buffering off;
488
+ # Enable chunked transfer encoding. Chunked transfer encoding allows servers to send data in chunks for dynamically generated content without knowing the size of the content in advance.
489
+ chunked_transfer_encoding on;
490
+ # Turn on TCP_NOPUSH, which tells Nginx to send as much data as possible before sending the packet to the client. This is usually used in conjunction with sendfile to improve network efficiency.
491
+ tcp_nopush on;
492
+ # Turn on TCP_NODELAY, which tells Nginx not to delay sending data and to send small data packets immediately. In some cases, this can reduce network latency.
493
+ tcp_nodelay on;
494
+ #Set the timeout to keep the connection, here it is set to 120 seconds. If there is no further communication between client and server during this time, the connection will be closed.
495
+ keepalive_timeout 120;
496
+ ```
497
+
498
+ ### Token statistics
499
+
500
+ Since the inference side is not in kimi-free-api, the token cannot be counted and will be returned as a fixed number!!!!!
501
+
502
+ ## Star History
503
+
504
+ [![Star History Chart](https://api.star-history.com/svg?repos=LLM-Red-Team/kimi-free-api&type=Date)](https://star-history.com/#LLM-Red-Team/kimi-free-api&Date)
configs/dev/service.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # 服务名称
2
+ name: kimi-free-api
3
+ # 服务绑定主机地址
4
+ host: '0.0.0.0'
5
+ # 服务绑定端口
6
+ port: 7860
configs/dev/system.yml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 是否开启请求日志
2
+ requestLog: true
3
+ # 临时目录路径
4
+ tmpDir: ./tmp
5
+ # 日志目录路径
6
+ logDir: ./logs
7
+ # 日志写入间隔(毫秒)
8
+ logWriteInterval: 200
9
+ # 日志文件有效期(毫秒)
10
+ logFileExpires: 2626560000
11
+ # 公共目录路径
12
+ publicDir: ./public
13
+ # 临时文件有效期(毫秒)
14
+ tmpFileExpires: 86400000
doc/example-0.png ADDED
doc/example-1.png ADDED
doc/example-2.png ADDED
doc/example-3.png ADDED
doc/example-5.png ADDED
doc/example-6.png ADDED
doc/example-7.png ADDED
doc/example-8.jpg ADDED
libs.d.ts ADDED
File without changes
package.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "kimi-free-api",
3
+ "version": "0.0.36",
4
+ "description": "Kimi Free API Server",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "directories": {
10
+ "dist": "dist"
11
+ },
12
+ "files": [
13
+ "dist/"
14
+ ],
15
+ "scripts": {
16
+ "dev": "tsup src/index.ts --format cjs,esm --sourcemap --dts --publicDir public --watch --onSuccess \"node --enable-source-maps --no-node-snapshot dist/index.js\"",
17
+ "start": "node --enable-source-maps --no-node-snapshot dist/index.js",
18
+ "build": "tsup src/index.ts --format cjs,esm --sourcemap --dts --clean --publicDir public"
19
+ },
20
+ "author": "Vinlic",
21
+ "license": "ISC",
22
+ "dependencies": {
23
+ "axios": "^1.6.7",
24
+ "colors": "^1.4.0",
25
+ "crc-32": "^1.2.2",
26
+ "cron": "^3.1.6",
27
+ "date-fns": "^3.3.1",
28
+ "eventsource-parser": "^1.1.2",
29
+ "fs-extra": "^11.2.0",
30
+ "koa": "^2.15.0",
31
+ "koa-body": "^5.0.0",
32
+ "koa-bodyparser": "^4.4.1",
33
+ "koa-range": "^0.3.0",
34
+ "koa-router": "^12.0.1",
35
+ "koa2-cors": "^2.0.6",
36
+ "lodash": "^4.17.21",
37
+ "mime": "^4.0.1",
38
+ "minimist": "^1.2.8",
39
+ "randomstring": "^1.3.0",
40
+ "uuid": "^9.0.1",
41
+ "yaml": "^2.3.4"
42
+ },
43
+ "devDependencies": {
44
+ "@types/lodash": "^4.14.202",
45
+ "@types/mime": "^3.0.4",
46
+ "tsup": "^8.0.2",
47
+ "typescript": "^5.3.3"
48
+ }
49
+ }
public/welcome.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <title>🚀 服务已启动</title>
6
+ </head>
7
+ <body>
8
+ <p>kimi-free-api已启动!<br>请通过LobeChat / NextChat / Dify等客户端或OpenAI SDK接入!</p>
9
+ </body>
10
+ </html>
src/api/consts/exceptions.ts ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ API_TEST: [-9999, 'API异常错误'],
3
+ API_REQUEST_PARAMS_INVALID: [-2000, '请求参数非法'],
4
+ API_REQUEST_FAILED: [-2001, '请求失败'],
5
+ API_TOKEN_EXPIRES: [-2002, 'Token已失效'],
6
+ API_FILE_URL_INVALID: [-2003, '远程文件URL非法'],
7
+ API_FILE_EXECEEDS_SIZE: [-2004, '远程文件超出大小'],
8
+ API_CHAT_STREAM_PUSHING: [-2005, '已有对话流正在输出'],
9
+ API_RESEARCH_EXCEEDS_LIMIT: [-2006, '探索版使用量已达到上限']
10
+ }
src/api/controllers/chat.ts ADDED
@@ -0,0 +1,1080 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PassThrough } from "stream";
2
+ import path from 'path';
3
+ import _ from 'lodash';
4
+ import mime from 'mime';
5
+ import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
6
+
7
+ import type IStreamMessage from "../interfaces/IStreamMessage.ts";
8
+ import APIException from "@/lib/exceptions/APIException.ts";
9
+ import EX from "@/api/consts/exceptions.ts";
10
+ import { createParser } from 'eventsource-parser'
11
+ import logger from '@/lib/logger.ts';
12
+ import util from '@/lib/util.ts';
13
+
14
+ // 模型名称
15
+ const MODEL_NAME = 'kimi';
16
+ // 设备ID
17
+ const DEVICE_ID = Math.random() * 999999999999999999 + 7000000000000000000;
18
+ // SessionID
19
+ const SESSION_ID = Math.random() * 99999999999999999 + 1700000000000000000;
20
+ // access_token有效期
21
+ const ACCESS_TOKEN_EXPIRES = 300;
22
+ // 最大重试次数
23
+ const MAX_RETRY_COUNT = 3;
24
+ // 重试延迟
25
+ const RETRY_DELAY = 5000;
26
+ // 基础URL
27
+ const BASE_URL = 'https://kimi.moonshot.cn';
28
+ // 伪装headers
29
+ const FAKE_HEADERS = {
30
+ 'Accept': '*/*',
31
+ 'Accept-Encoding': 'gzip, deflate, br, zstd',
32
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
33
+ 'Cache-Control': 'no-cache',
34
+ 'Pragma': 'no-cache',
35
+ 'Origin': BASE_URL,
36
+ 'Cookie': util.generateCookie(),
37
+ 'R-Timezone': 'Asia/Shanghai',
38
+ 'Sec-Ch-Ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
39
+ 'Sec-Ch-Ua-Mobile': '?0',
40
+ 'Sec-Ch-Ua-Platform': '"Windows"',
41
+ 'Sec-Fetch-Dest': 'empty',
42
+ 'Sec-Fetch-Mode': 'cors',
43
+ 'Sec-Fetch-Site': 'same-origin',
44
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
45
+ 'Priority': 'u=1, i',
46
+ 'X-Msh-Device-Id': `${DEVICE_ID}`,
47
+ 'X-Msh-Platform': 'web',
48
+ 'X-Msh-Session-Id': `${SESSION_ID}`
49
+ };
50
+ // 文件最大大小
51
+ const FILE_MAX_SIZE = 100 * 1024 * 1024;
52
+ // access_token映射
53
+ const accessTokenMap = new Map();
54
+ // access_token请求队列映射
55
+ const accessTokenRequestQueueMap: Record<string, Function[]> = {};
56
+
57
+ /**
58
+ * 请求access_token
59
+ *
60
+ * 使用refresh_token去刷新获得access_token
61
+ *
62
+ * @param refreshToken 用于刷新access_token的refresh_token
63
+ */
64
+ async function requestToken(refreshToken: string) {
65
+ if (accessTokenRequestQueueMap[refreshToken])
66
+ return new Promise(resolve => accessTokenRequestQueueMap[refreshToken].push(resolve));
67
+ accessTokenRequestQueueMap[refreshToken] = [];
68
+ logger.info(`Refresh token: ${refreshToken}`);
69
+ const result = await (async () => {
70
+ const result = await axios.get(`${BASE_URL}/api/auth/token/refresh`, {
71
+ headers: {
72
+ Authorization: `Bearer ${refreshToken}`,
73
+ ...FAKE_HEADERS,
74
+ },
75
+ timeout: 15000,
76
+ validateStatus: () => true
77
+ });
78
+ const {
79
+ access_token,
80
+ refresh_token
81
+ } = checkResult(result, refreshToken);
82
+ const userResult = await axios.get(`${BASE_URL}/api/user`, {
83
+ headers: {
84
+ Authorization: `Bearer ${access_token}`,
85
+ ...FAKE_HEADERS,
86
+ },
87
+ timeout: 15000,
88
+ validateStatus: () => true
89
+ });
90
+ if(!userResult.data.id)
91
+ throw new APIException(EX.API_REQUEST_FAILED, '获取用户信息失败');
92
+ return {
93
+ userId: userResult.data.id,
94
+ accessToken: access_token,
95
+ refreshToken: refresh_token,
96
+ refreshTime: util.unixTimestamp() + ACCESS_TOKEN_EXPIRES
97
+ }
98
+ })()
99
+ .then(result => {
100
+ if (accessTokenRequestQueueMap[refreshToken]) {
101
+ accessTokenRequestQueueMap[refreshToken].forEach(resolve => resolve(result));
102
+ delete accessTokenRequestQueueMap[refreshToken];
103
+ }
104
+ logger.success(`Refresh successful`);
105
+ return result;
106
+ })
107
+ .catch(err => {
108
+ logger.error(err);
109
+ if (accessTokenRequestQueueMap[refreshToken]) {
110
+ accessTokenRequestQueueMap[refreshToken].forEach(resolve => resolve(err));
111
+ delete accessTokenRequestQueueMap[refreshToken];
112
+ }
113
+ return err;
114
+ });
115
+ if (_.isError(result))
116
+ throw result;
117
+ return result;
118
+ }
119
+
120
+ /**
121
+ * 获取缓存中的access_token
122
+ *
123
+ * 避免短时间大量刷新token,未加锁,如果有并发要求还需加锁
124
+ *
125
+ * @param refreshToken 用于刷新access_token的refresh_token
126
+ */
127
+ async function acquireToken(refreshToken: string): Promise<any> {
128
+ let result = accessTokenMap.get(refreshToken);
129
+ if (!result) {
130
+ result = await requestToken(refreshToken);
131
+ accessTokenMap.set(refreshToken, result);
132
+ }
133
+ if (util.unixTimestamp() > result.refreshTime) {
134
+ result = await requestToken(refreshToken);
135
+ accessTokenMap.set(refreshToken, result);
136
+ }
137
+ return result;
138
+ }
139
+
140
+ /**
141
+ * 发送请求
142
+ */
143
+ export async function request(
144
+ method: string,
145
+ uri: string,
146
+ refreshToken: string,
147
+ options: AxiosRequestConfig = {}
148
+ ) {
149
+ const {
150
+ accessToken,
151
+ userId
152
+ } = await acquireToken(refreshToken);
153
+ logger.info(`url: ${uri}`);
154
+ const result = await axios({
155
+ method,
156
+ url: `${BASE_URL}${uri}`,
157
+ params: options.params,
158
+ data: options.data,
159
+ headers: {
160
+ Authorization: `Bearer ${accessToken}`,
161
+ 'X-Traffic-Id': userId,
162
+ ...FAKE_HEADERS,
163
+ ...(options.headers || {})
164
+ },
165
+ timeout: options.timeout || 15000,
166
+ responseType: options.responseType,
167
+ validateStatus: () => true
168
+ });
169
+ return checkResult(result, refreshToken);
170
+ }
171
+
172
+ /**
173
+ * 创建会话
174
+ *
175
+ * 创建临时的会话用于对话补全
176
+ *
177
+ * @param refreshToken 用于刷新access_token的refresh_token
178
+ */
179
+ async function createConversation(model: string, name: string, refreshToken: string) {
180
+ const {
181
+ id: convId
182
+ } = await request('POST', '/api/chat', refreshToken, {
183
+ data: {
184
+ enter_method: 'new_chat',
185
+ is_example: false,
186
+ kimiplus_id: /^[0-9a-z]{20}$/.test(model) ? model : 'kimi',
187
+ name
188
+ }
189
+ });
190
+ return convId;
191
+ }
192
+
193
+ /**
194
+ * 移除会话
195
+ *
196
+ * 在对话流传输完毕后移除会话,避免创建的会话出现在用户的对话列表中
197
+ *
198
+ * @param refreshToken 用于刷新access_token的refresh_token
199
+ */
200
+ async function removeConversation(convId: string, refreshToken: string) {
201
+ return await request('DELETE', `/api/chat/${convId}`, refreshToken);
202
+ }
203
+
204
+ /**
205
+ * 获取建议
206
+ *
207
+ * @param refreshToken 用于刷新access_token的refresh_token
208
+ */
209
+ async function getSuggestion(query: string, refreshToken: string) {
210
+ return await request('POST', '/api/suggestion', refreshToken, {
211
+ data: {
212
+ offset: 0,
213
+ page_referer: 'chat',
214
+ query: query.replace('user:', '').replace('assistant:', ''),
215
+ scene: 'first_round',
216
+ size: 10
217
+ }
218
+ });
219
+ }
220
+
221
+ /**
222
+ * 预处理N2S
223
+ *
224
+ * 预处理N2S,用于获取搜索结果
225
+ *
226
+ * @param model 模型名称
227
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
228
+ * @param refs 引用文件ID列表
229
+ * @param refreshToken 用于刷新access_token的refresh_token
230
+ * @param refConvId 引用会话ID
231
+ */
232
+ async function preN2s(model: string, messages: { role: string, content: string }[], refs: string[], refreshToken: string, refConvId?: string) {
233
+ const isSearchModel = model.indexOf('search') != -1;
234
+ return await request('POST', `/api/chat/${refConvId}/pre-n2s`, refreshToken, {
235
+ data: {
236
+ is_pro_search: false,
237
+ kimiplus_id: /^[0-9a-z]{20}$/.test(model) ? model : 'kimi',
238
+ messages,
239
+ refs,
240
+ use_search: isSearchModel
241
+ }
242
+ });
243
+ }
244
+
245
+ /**
246
+ * token计数
247
+ *
248
+ * @param query 查询内容
249
+ * @param refreshToken 用于刷新access_token的refresh_token
250
+ * @param refConvId 引用会话ID
251
+ */
252
+ async function tokenSize(query: string, refs: string[], refreshToken: string, refConvId: string) {
253
+ return await request('POST', `/api/chat/${refConvId}/token_size`, refreshToken, {
254
+ data: {
255
+ content: query,
256
+ refs: []
257
+ }
258
+ });
259
+ }
260
+
261
+ /**
262
+ * 获取探索版使用量
263
+ *
264
+ * @param refreshToken 用于刷新access_token的refresh_token
265
+ */
266
+ async function getResearchUsage(refreshToken: string): Promise<{
267
+ remain,
268
+ total,
269
+ used
270
+ }> {
271
+ return await request('GET', '/api/chat/research/usage', refreshToken);
272
+ }
273
+
274
+ /**
275
+ * 同步对话补全
276
+ *
277
+ * @param model 模型名称
278
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
279
+ * @param refreshToken 用于刷新access_token的refresh_token
280
+ * @param refConvId 引用会话ID
281
+ * @param retryCount 重试次数
282
+ */
283
+ async function createCompletion(model = MODEL_NAME, messages: any[], refreshToken: string, refConvId?: string, retryCount = 0, segmentId?: string): Promise<IStreamMessage> {
284
+ return (async () => {
285
+ logger.info(messages);
286
+
287
+ // 创建会话
288
+ const convId = /[0-9a-zA-Z]{20}/.test(refConvId) ? refConvId : await createConversation(model, "未命名会话", refreshToken);
289
+
290
+ // 提取引用文件URL并上传kimi获得引用的文件ID列表
291
+ const refFileUrls = extractRefFileUrls(messages);
292
+ const refResults = refFileUrls.length ? await Promise.all(refFileUrls.map(fileUrl => uploadFile(fileUrl, refreshToken, convId))) : [];
293
+ const refs = refResults.map(result => result.id);
294
+ const refsFile = refResults.map(result => ({
295
+ detail: result,
296
+ done: true,
297
+ file: {},
298
+ file_info: result,
299
+ id: result.id,
300
+ name: result.name,
301
+ parse_status: 'success',
302
+ size: result.size,
303
+ upload_progress: 100,
304
+ upload_status: 'success'
305
+ }));
306
+
307
+ // 伪装调用获取用户信息
308
+ fakeRequest(refreshToken)
309
+ .catch(err => logger.error(err));
310
+
311
+ // 消息预处理
312
+ const sendMessages = messagesPrepare(messages, !!refConvId);
313
+
314
+ !segmentId && preN2s(model, sendMessages, refs, refreshToken, convId)
315
+ .catch(err => logger.error(err));
316
+ getSuggestion(sendMessages[0].content, refreshToken)
317
+ .catch(err => logger.error(err));
318
+ tokenSize(sendMessages[0].content, refs, refreshToken, convId)
319
+ .catch(err => logger.error(err));
320
+
321
+ const isMath = model.indexOf('math') != -1;
322
+ const isSearchModel = model.indexOf('search') != -1;
323
+ const isResearchModel = model.indexOf('research') != -1;
324
+ const isK1Model = model.indexOf('k1') != -1;
325
+
326
+ logger.info(`使用模型: ${model},是否联网检索: ${isSearchModel},是否探索版: ${isResearchModel},是否K1模型: ${isK1Model},是否数学模型: ${isMath}`);
327
+
328
+ if(segmentId)
329
+ logger.info(`继续请求,segmentId: ${segmentId}`);
330
+
331
+ // 检查探索版使用量
332
+ if(isResearchModel) {
333
+ const {
334
+ total,
335
+ used
336
+ } = await getResearchUsage(refreshToken);
337
+ if(used >= total)
338
+ throw new APIException(EX.API_RESEARCH_EXCEEDS_LIMIT, `探索版使用量已达到上限`);
339
+ logger.info(`探索版当前额度: ${used}/${total}`);
340
+ }
341
+
342
+ const kimiplusId = isK1Model ? 'crm40ee9e5jvhsn7ptcg' : (/^[0-9a-z]{20}$/.test(model) ? model : 'kimi');
343
+
344
+ // 请求补全流
345
+ const stream = await request('POST', `/api/chat/${convId}/completion/stream`, refreshToken, {
346
+ data: segmentId ? {
347
+ segment_id: segmentId,
348
+ action: 'continue',
349
+ messages: [{ role: 'user', content: ' ' }],
350
+ kimiplus_id: kimiplusId,
351
+ extend: { sidebar: true }
352
+ } : {
353
+ kimiplus_id: kimiplusId,
354
+ messages: sendMessages,
355
+ refs,
356
+ refs_file: refsFile,
357
+ use_math: isMath,
358
+ use_research: isResearchModel,
359
+ use_search: isSearchModel,
360
+ extend: { sidebar: true }
361
+ },
362
+ headers: {
363
+ Referer: `https://kimi.moonshot.cn/chat/${convId}`
364
+ },
365
+ responseType: 'stream'
366
+ });
367
+
368
+ const streamStartTime = util.timestamp();
369
+
370
+ // 接收流为输出文本
371
+ const answer = await receiveStream(model, convId, stream);
372
+
373
+ // 如果上次请求生成长度超限,则继续请求
374
+ if(answer.choices[0].finish_reason == 'length' && answer.segment_id) {
375
+ const continueAnswer = await createCompletion(model, [], refreshToken, convId, retryCount, answer.segment_id);
376
+ answer.choices[0].message.content += continueAnswer.choices[0].message.content;
377
+ }
378
+
379
+ logger.success(`Stream has completed transfer ${util.timestamp() - streamStartTime}ms`);
380
+
381
+ // 异步移除会话,如果消息不合规,此操作可能会抛出数据库错误异常,请忽略
382
+ // 如果引用会话将不会清除,因为我们不知道什么时候你会结束会话
383
+ !refConvId && removeConversation(convId, refreshToken)
384
+ .catch(err => console.error(err));
385
+
386
+ return answer;
387
+ })()
388
+ .catch(err => {
389
+ if (retryCount < MAX_RETRY_COUNT) {
390
+ logger.error(`Stream response error: ${err.message}`);
391
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
392
+ return (async () => {
393
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
394
+ return createCompletion(model, messages, refreshToken, refConvId, retryCount + 1);
395
+ })();
396
+ }
397
+ throw err;
398
+ });
399
+ }
400
+
401
+ /**
402
+ * 流式对话补全
403
+ *
404
+ * @param model 模型名称
405
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
406
+ * @param refreshToken 用于刷新access_token的refresh_token
407
+ * @param refConvId 引用会话ID
408
+ * @param retryCount 重试次数
409
+ */
410
+ async function createCompletionStream(model = MODEL_NAME, messages: any[], refreshToken: string, refConvId?: string, retryCount = 0) {
411
+ return (async () => {
412
+ logger.info(messages);
413
+
414
+ // 创建会话
415
+ const convId = /[0-9a-zA-Z]{20}/.test(refConvId) ? refConvId : await createConversation(model, "未命名会话", refreshToken);
416
+
417
+ // 提取引用文件URL并上传kimi获得引用的文件ID列表
418
+ const refFileUrls = extractRefFileUrls(messages);
419
+ const refResults = refFileUrls.length ? await Promise.all(refFileUrls.map(fileUrl => uploadFile(fileUrl, refreshToken, convId))) : [];
420
+ const refs = refResults.map(result => result.id);
421
+ const refsFile = refResults.map(result => ({
422
+ detail: result,
423
+ done: true,
424
+ file: {},
425
+ file_info: result,
426
+ id: result.id,
427
+ name: result.name,
428
+ parse_status: 'success',
429
+ size: result.size,
430
+ upload_progress: 100,
431
+ upload_status: 'success'
432
+ }));
433
+
434
+ // 伪装调用获取用户信息
435
+ fakeRequest(refreshToken)
436
+ .catch(err => logger.error(err));
437
+
438
+ const sendMessages = messagesPrepare(messages, !!refConvId);
439
+
440
+ preN2s(model, sendMessages, refs, refreshToken, convId)
441
+ .catch(err => logger.error(err));
442
+ getSuggestion(sendMessages[0].content, refreshToken)
443
+ .catch(err => logger.error(err));
444
+ tokenSize(sendMessages[0].content, refs, refreshToken, convId)
445
+ .catch(err => logger.error(err));
446
+
447
+ const isMath = model.indexOf('math') != -1;
448
+ const isSearchModel = model.indexOf('search') != -1;
449
+ const isResearchModel = model.indexOf('research') != -1;
450
+ const isK1Model = model.indexOf('k1') != -1;
451
+
452
+ logger.info(`使用模型: ${model},是否联网检索: ${isSearchModel},是否探索版: ${isResearchModel},是否K1模型: ${isK1Model},是否数学模型: ${isMath}`);
453
+
454
+ // 检查探索版使用量
455
+ if(isResearchModel) {
456
+ const {
457
+ total,
458
+ used
459
+ } = await getResearchUsage(refreshToken);
460
+ if(used >= total)
461
+ throw new APIException(EX.API_RESEARCH_EXCEEDS_LIMIT, `探索版使用量已达到上限`);
462
+ logger.info(`探索版当前额度: ${used}/${total}`);
463
+ }
464
+
465
+ const kimiplusId = isK1Model ? 'crm40ee9e5jvhsn7ptcg' : (/^[0-9a-z]{20}$/.test(model) ? model : 'kimi');
466
+
467
+ // 请求补全流
468
+ const stream = await request('POST', `/api/chat/${convId}/completion/stream`, refreshToken, {
469
+ data: {
470
+ kimiplus_id: kimiplusId,
471
+ messages: sendMessages,
472
+ refs,
473
+ refs_file: refsFile,
474
+ use_math: isMath,
475
+ use_research: isResearchModel,
476
+ use_search: isSearchModel,
477
+ extend: { sidebar: true }
478
+ },
479
+ headers: {
480
+ Referer: `https://kimi.moonshot.cn/chat/${convId}`
481
+ },
482
+ responseType: 'stream'
483
+ });
484
+
485
+ const streamStartTime = util.timestamp();
486
+ // 创建转换流将消息格式转换为gpt兼容格式
487
+ return createTransStream(model, convId, stream, () => {
488
+ logger.success(`Stream has completed transfer ${util.timestamp() - streamStartTime}ms`);
489
+ // 流传输结束后异步移除会话,如果消息不合规,此操作可能会抛出数据库错误异常,请忽略
490
+ // 如果引用会话将不会清除,因为我们不知道什么时候你会结束会话
491
+ !refConvId && removeConversation(convId, refreshToken)
492
+ .catch(err => console.error(err));
493
+ });
494
+ })()
495
+ .catch(err => {
496
+ if (retryCount < MAX_RETRY_COUNT) {
497
+ logger.error(`Stream response error: ${err.message}`);
498
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
499
+ return (async () => {
500
+ await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
501
+ return createCompletionStream(model, messages, refreshToken, refConvId, retryCount + 1);
502
+ })();
503
+ }
504
+ throw err;
505
+ });
506
+ }
507
+
508
+ /**
509
+ * 调用一些接口伪装访问
510
+ *
511
+ * 随机挑一个
512
+ *
513
+ * @param refreshToken 用于刷新access_token的refresh_token
514
+ */
515
+ async function fakeRequest(refreshToken: string) {
516
+ await [
517
+ () => request('GET', '/api/user', refreshToken),
518
+ () => request('POST', '/api/user/usage', refreshToken, {
519
+ data: {
520
+ usage: ['kimiv', 'math']
521
+ }
522
+ }),
523
+ () => request('GET', '/api/chat_1m/user/status', refreshToken),
524
+ () => request('GET', '/api/kimi_mv/user/status', refreshToken),
525
+ () => request('POST', '/api/kimiplus/history', refreshToken),
526
+ () => request('POST', '/api/kimiplus/search', refreshToken, {
527
+ data: {
528
+ offset: 0,
529
+ size: 20
530
+ }
531
+ }),
532
+ () => request('POST', '/api/chat/list', refreshToken, {
533
+ data: {
534
+ offset: 0,
535
+ size: 50
536
+ }
537
+ }),
538
+ ][Math.floor(Math.random() * 7)]();
539
+ }
540
+
541
+ /**
542
+ * 提取消息中引用的文件URL
543
+ *
544
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
545
+ */
546
+ function extractRefFileUrls(messages: any[]) {
547
+ const urls = [];
548
+ // 如果没有消息,则返回[]
549
+ if (!messages.length) {
550
+ return urls;
551
+ }
552
+ // 只获取最新的消息
553
+ const lastMessage = messages[messages.length - 1];
554
+ if (_.isArray(lastMessage.content)) {
555
+ lastMessage.content.forEach(v => {
556
+ if (!_.isObject(v) || !['file', 'image_url'].includes(v['type']))
557
+ return;
558
+ // kimi-free-api支持格式
559
+ if (v['type'] == 'file' && _.isObject(v['file_url']) && _.isString(v['file_url']['url']))
560
+ urls.push(v['file_url']['url']);
561
+ // 兼容gpt-4-vision-preview API格式
562
+ else if (v['type'] == 'image_url' && _.isObject(v['image_url']) && _.isString(v['image_url']['url']))
563
+ urls.push(v['image_url']['url']);
564
+ });
565
+ }
566
+ logger.info("本次请求上传:" + urls.length + "个文件");
567
+ return urls;
568
+ }
569
+
570
+ /**
571
+ * 消息预处理
572
+ *
573
+ * 由于接口只取第一条消息,此处会将多条消息合并为一条,实现多轮对话效果
574
+ * user:旧消息1
575
+ * assistant:旧消息2
576
+ * user:新消息
577
+ *
578
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
579
+ * @param isRefConv 是否为引用会话
580
+ */
581
+ function messagesPrepare(messages: any[], isRefConv = false) {
582
+ let content;
583
+ if (isRefConv || messages.length < 2) {
584
+ content = messages.reduce((content, message) => {
585
+ if (_.isArray(message.content)) {
586
+ return message.content.reduce((_content, v) => {
587
+ if (!_.isObject(v) || v['type'] != 'text') return _content;
588
+ return _content + `${v["text"] || ""}\n`;
589
+ }, content);
590
+ }
591
+ return content += `${message.role == 'user' ? wrapUrlsToTags(message.content) : message.content}\n`;
592
+ }, '')
593
+ logger.info("\n透传内容:\n" + content);
594
+ }
595
+ else {
596
+ // 注入消息提升注意力
597
+ let latestMessage = messages[messages.length - 1];
598
+ let hasFileOrImage = Array.isArray(latestMessage.content)
599
+ && latestMessage.content.some(v => (typeof v === 'object' && ['file', 'image_url'].includes(v['type'])));
600
+ // 第二轮开始注入system prompt
601
+ if (hasFileOrImage) {
602
+ let newFileMessage = {
603
+ "content": "关注用户最新发送文件和消息",
604
+ "role": "system"
605
+ };
606
+ messages.splice(messages.length - 1, 0, newFileMessage);
607
+ logger.info("注入提升尾部文件注意力system prompt");
608
+ } else {
609
+ let newTextMessage = {
610
+ "content": "关注用户最新的消息",
611
+ "role": "system"
612
+ };
613
+ messages.splice(messages.length - 1, 0, newTextMessage);
614
+ logger.info("注入提升尾部消息注意力system prompt");
615
+ }
616
+ content = messages.reduce((content, message) => {
617
+ if (_.isArray(message.content)) {
618
+ return message.content.reduce((_content, v) => {
619
+ if (!_.isObject(v) || v['type'] != 'text') return _content;
620
+ return _content + `${message.role || "user"}:${v["text"] || ""}\n`;
621
+ }, content);
622
+ }
623
+ return content += `${message.role || "user"}:${message.role == 'user' ? wrapUrlsToTags(message.content) : message.content}\n`;
624
+ }, '')
625
+ logger.info("\n对话合并:\n" + content);
626
+ }
627
+
628
+ return [
629
+ { role: 'user', content }
630
+ ]
631
+ }
632
+
633
+ /**
634
+ * 将消息中的URL包装为HTML标签
635
+ *
636
+ * kimi网页版中会自动将url包装为url标签用于处理状态,此处也得模仿处理,否则无法成功解析
637
+ *
638
+ * @param content 消息内容
639
+ */
640
+ function wrapUrlsToTags(content: string) {
641
+ return content.replace(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/gi, url => `<url id="" type="url" status="" title="" wc="">${url}</url>`);
642
+ }
643
+
644
+ /**
645
+ * 获取预签名的文件URL
646
+ *
647
+ * @param filename 文件名称
648
+ * @param refreshToken 用于刷新access_token的refresh_token
649
+ */
650
+ async function preSignUrl(action: string, filename: string, refreshToken: string) {
651
+ const {
652
+ accessToken,
653
+ userId
654
+ } = await acquireToken(refreshToken);
655
+ const result = await axios.post('https://kimi.moonshot.cn/api/pre-sign-url', {
656
+ action,
657
+ name: filename
658
+ }, {
659
+ timeout: 15000,
660
+ headers: {
661
+ Authorization: `Bearer ${accessToken}`,
662
+ Referer: `https://kimi.moonshot.cn/`,
663
+ 'X-Traffic-Id': userId,
664
+ ...FAKE_HEADERS
665
+ },
666
+ validateStatus: () => true
667
+ });
668
+ return checkResult(result, refreshToken);
669
+ }
670
+
671
+ /**
672
+ * 预检查文件URL有效性
673
+ *
674
+ * @param fileUrl 文件URL
675
+ */
676
+ async function checkFileUrl(fileUrl: string) {
677
+ if (util.isBASE64Data(fileUrl))
678
+ return;
679
+ const result = await axios.head(fileUrl, {
680
+ timeout: 15000,
681
+ validateStatus: () => true
682
+ });
683
+ if (result.status >= 400)
684
+ throw new APIException(EX.API_FILE_URL_INVALID, `File ${fileUrl} is not valid: [${result.status}] ${result.statusText}`);
685
+ // 检查文件大小
686
+ if (result.headers && result.headers['content-length']) {
687
+ const fileSize = parseInt(result.headers['content-length'], 10);
688
+ if (fileSize > FILE_MAX_SIZE)
689
+ throw new APIException(EX.API_FILE_EXECEEDS_SIZE, `File ${fileUrl} is not valid`);
690
+ }
691
+ }
692
+
693
+ /**
694
+ * 上传文件
695
+ *
696
+ * @param fileUrl 文件URL
697
+ * @param refreshToken 用于刷新access_token的refresh_token
698
+ * @param refConvId 引用会话ID
699
+ */
700
+ async function uploadFile(fileUrl: string, refreshToken: string, refConvId?: string) {
701
+ // 预检查远程文件URL可用性
702
+ await checkFileUrl(fileUrl);
703
+
704
+ let filename, fileData, mimeType;
705
+ // 如果是BASE64数据则直接转换为Buffer
706
+ if (util.isBASE64Data(fileUrl)) {
707
+ mimeType = util.extractBASE64DataFormat(fileUrl);
708
+ const ext = mime.getExtension(mimeType);
709
+ filename = `${util.uuid()}.${ext}`;
710
+ fileData = Buffer.from(util.removeBASE64DataHeader(fileUrl), 'base64');
711
+ }
712
+ // 下载文件到内存,如果您的服务器内存很小,建议考虑改造为流直传到下一个接口上,避免停留占用内存
713
+ else {
714
+ filename = path.basename(fileUrl);
715
+ ({ data: fileData } = await axios.get(fileUrl, {
716
+ responseType: 'arraybuffer',
717
+ // 100M限制
718
+ maxContentLength: FILE_MAX_SIZE,
719
+ // 60秒超时
720
+ timeout: 60000
721
+ }));
722
+ }
723
+
724
+ const fileType = (mimeType || '').includes('image') ? 'image' : 'file';
725
+
726
+ // 获取预签名文件URL
727
+ let {
728
+ url: uploadUrl,
729
+ object_name: objectName,
730
+ file_id: fileId
731
+ } = await preSignUrl(fileType, filename, refreshToken);
732
+
733
+ // 获取文件的MIME类型
734
+ mimeType = mimeType || mime.getType(filename);
735
+ // 上传文件到目标OSS
736
+ const {
737
+ accessToken,
738
+ userId
739
+ } = await acquireToken(refreshToken);
740
+ let result = await axios.request({
741
+ method: 'PUT',
742
+ url: uploadUrl,
743
+ data: fileData,
744
+ // 100M限制
745
+ maxBodyLength: FILE_MAX_SIZE,
746
+ // 120秒超时
747
+ timeout: 120000,
748
+ headers: {
749
+ 'Content-Type': mimeType,
750
+ Authorization: `Bearer ${accessToken}`,
751
+ Referer: `https://kimi.moonshot.cn/`,
752
+ 'X-Traffic-Id': userId,
753
+ ...FAKE_HEADERS
754
+ },
755
+ validateStatus: () => true
756
+ });
757
+ checkResult(result, refreshToken);
758
+
759
+ let status, startTime = Date.now();
760
+ let fileDetail;
761
+ while (status != 'initialized' && status != 'parsed') {
762
+ if (Date.now() - startTime > 30000)
763
+ throw new Error('文件等待处理超时');
764
+ // 获取文件上传结果
765
+ result = await axios.post('https://kimi.moonshot.cn/api/file', fileType == 'image' ? {
766
+ type: 'image',
767
+ file_id: fileId,
768
+ name: filename
769
+ } : {
770
+ type: 'file',
771
+ name: filename,
772
+ object_name: objectName,
773
+ file_id: '',
774
+ chat_id: refConvId
775
+ }, {
776
+ headers: {
777
+ Authorization: `Bearer ${accessToken}`,
778
+ Referer: `https://kimi.moonshot.cn/`,
779
+ 'X-Traffic-Id': userId,
780
+ ...FAKE_HEADERS
781
+ }
782
+ });
783
+ fileDetail = checkResult(result, refreshToken);
784
+ ({ id: fileId, status } = fileDetail);
785
+ }
786
+
787
+ startTime = Date.now();
788
+ let parseFinish = status == 'parsed';
789
+ while (!parseFinish) {
790
+ if (Date.now() - startTime > 30000)
791
+ throw new Error('文件等待处理超时');
792
+ // 处理文件转换
793
+ parseFinish = await new Promise(resolve => {
794
+ axios.post('https://kimi.moonshot.cn/api/file/parse_process', {
795
+ ids: [fileId],
796
+ timeout: 120000
797
+ }, {
798
+ headers: {
799
+ Authorization: `Bearer ${accessToken}`,
800
+ Referer: `https://kimi.moonshot.cn/`,
801
+ 'X-Traffic-Id': userId,
802
+ ...FAKE_HEADERS
803
+ }
804
+ })
805
+ .then(() => resolve(true))
806
+ .catch(() => resolve(false));
807
+ });
808
+ }
809
+
810
+ return fileDetail;
811
+ }
812
+
813
+ /**
814
+ * 检查请求结果
815
+ *
816
+ * @param result 结果
817
+ * @param refreshToken 用于刷新access_token的refresh_token
818
+ */
819
+ function checkResult(result: AxiosResponse, refreshToken: string) {
820
+ if (result.status == 401) {
821
+ accessTokenMap.delete(refreshToken);
822
+ throw new APIException(EX.API_REQUEST_FAILED);
823
+ }
824
+ if (!result.data)
825
+ return null;
826
+ const { error_type, message } = result.data;
827
+ if (!_.isString(error_type))
828
+ return result.data;
829
+ if (error_type == 'auth.token.invalid')
830
+ accessTokenMap.delete(refreshToken);
831
+ if (error_type == 'chat.user_stream_pushing')
832
+ throw new APIException(EX.API_CHAT_STREAM_PUSHING);
833
+ throw new APIException(EX.API_REQUEST_FAILED, `[请求kimi失败]: ${message}`);
834
+ }
835
+
836
+ /**
837
+ * 从流接收完整的消息内容
838
+ *
839
+ * @param model 模型名称
840
+ * @param convId 会话ID
841
+ * @param stream 消息流
842
+ */
843
+ async function receiveStream(model: string, convId: string, stream: any): Promise<IStreamMessage> {
844
+ let webSearchCount = 0;
845
+ let temp = Buffer.from('');
846
+ return new Promise((resolve, reject) => {
847
+ // 消息初始化
848
+ const data = {
849
+ id: convId,
850
+ model,
851
+ object: 'chat.completion',
852
+ choices: [
853
+ { index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }
854
+ ],
855
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
856
+ segment_id: '',
857
+ created: util.unixTimestamp()
858
+ };
859
+ let refContent = '';
860
+ const silentSearch = model.indexOf('silent') != -1;
861
+ const parser = createParser(event => {
862
+ try {
863
+ if (event.type !== "event") return;
864
+ // 解析JSON
865
+ const result = _.attempt(() => JSON.parse(event.data));
866
+ if (_.isError(result))
867
+ throw new Error(`Stream response invalid: ${event.data}`);
868
+ // 处理消息
869
+ if (result.event == 'cmpl' && result.text) {
870
+ data.choices[0].message.content += result.text;
871
+ }
872
+ // 处理请求ID
873
+ else if(result.event == 'req') {
874
+ data.segment_id = result.id;
875
+ }
876
+ // 处理超长文本
877
+ else if(result.event == 'length') {
878
+ logger.warn('此次生成达到max_tokens,稍候将继续请求拼接完整响应');
879
+ data.choices[0].finish_reason = 'length';
880
+ }
881
+ // 处理结束或错误
882
+ else if (result.event == 'all_done' || result.event == 'error') {
883
+ data.choices[0].message.content += (result.event == 'error' ? '\n[内容由于不合规被停止生成,我们换个话题吧]' : '') + (refContent ? `\n\n搜索结果来自:\n${refContent}` : '');
884
+ refContent = '';
885
+ resolve(data);
886
+ }
887
+ // 处理联网搜索
888
+ else if (!silentSearch && result.event == 'search_plus' && result.msg && result.msg.type == 'get_res') {
889
+ webSearchCount += 1;
890
+ refContent += `【检索 ${webSearchCount}】 [${result.msg.title}](${result.msg.url})\n\n`;
891
+ }
892
+ // else
893
+ // logger.warn(result.event, result);
894
+ }
895
+ catch (err) {
896
+ logger.error(err);
897
+ reject(err);
898
+ }
899
+ });
900
+ // 将流数据喂给SSE转换器
901
+ stream.on("data", buffer => {
902
+ // 检查buffer是否以完整UTF8字符结尾
903
+ if (buffer.toString().indexOf('�') != -1) {
904
+ // 如果不完整则累积buffer直到收到完整字符
905
+ temp = Buffer.concat([temp, buffer]);
906
+ return;
907
+ }
908
+ // 将之前累积的不完整buffer拼接
909
+ if (temp.length > 0) {
910
+ buffer = Buffer.concat([temp, buffer]);
911
+ temp = Buffer.from('');
912
+ }
913
+ parser.feed(buffer.toString());
914
+ });
915
+ stream.once("error", err => reject(err));
916
+ stream.once("close", () => resolve(data));
917
+ });
918
+ }
919
+
920
+ /**
921
+ * 创建转换流
922
+ *
923
+ * 将流格式转换为gpt兼容流格式
924
+ *
925
+ * @param model 模型名称
926
+ * @param convId 会话ID
927
+ * @param stream 消息流
928
+ * @param endCallback 传输结束回调
929
+ */
930
+ function createTransStream(model: string, convId: string, stream: any, endCallback?: Function) {
931
+ // 消息创建时间
932
+ const created = util.unixTimestamp();
933
+ // 创建转换流
934
+ const transStream = new PassThrough();
935
+ let webSearchCount = 0;
936
+ let searchFlag = false;
937
+ let lengthExceed = false;
938
+ let segmentId = '';
939
+ const silentSearch = model.indexOf('silent') != -1;
940
+ !transStream.closed && transStream.write(`data: ${JSON.stringify({
941
+ id: convId,
942
+ model,
943
+ object: 'chat.completion.chunk',
944
+ choices: [
945
+ { index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }
946
+ ],
947
+ segment_id: '',
948
+ created
949
+ })}\n\n`);
950
+ const parser = createParser(event => {
951
+ try {
952
+ if (event.type !== "event") return;
953
+ // 解析JSON
954
+ const result = _.attempt(() => JSON.parse(event.data));
955
+ if (_.isError(result))
956
+ throw new Error(`Stream response invalid: ${event.data}`);
957
+ // 处理消息
958
+ if (result.event == 'cmpl') {
959
+ const exceptCharIndex = result.text.indexOf("�");
960
+ const chunk = result.text.substring(0, exceptCharIndex == -1 ? result.text.length : exceptCharIndex);
961
+ const data = `data: ${JSON.stringify({
962
+ id: convId,
963
+ model,
964
+ object: 'chat.completion.chunk',
965
+ choices: [
966
+ { index: 0, delta: { content: (searchFlag ? '\n' : '') + chunk }, finish_reason: null }
967
+ ],
968
+ segment_id: segmentId,
969
+ created
970
+ })}\n\n`;
971
+ if (searchFlag)
972
+ searchFlag = false;
973
+ !transStream.closed && transStream.write(data);
974
+ }
975
+ // 处理请求ID
976
+ else if(result.event == 'req') {
977
+ segmentId = result.id;
978
+ }
979
+ // 处理超长文本
980
+ else if (result.event == 'length') {
981
+ lengthExceed = true;
982
+ }
983
+ // 处理结束或错误
984
+ else if (result.event == 'all_done' || result.event == 'error') {
985
+ const data = `data: ${JSON.stringify({
986
+ id: convId,
987
+ model,
988
+ object: 'chat.completion.chunk',
989
+ choices: [
990
+ {
991
+ index: 0, delta: result.event == 'error' ? {
992
+ content: '\n[内容由于不合规被停止生成,我们换个话题吧]'
993
+ } : {}, finish_reason: lengthExceed ? 'length' : 'stop'
994
+ }
995
+ ],
996
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
997
+ segment_id: segmentId,
998
+ created
999
+ })}\n\n`;
1000
+ !transStream.closed && transStream.write(data);
1001
+ !transStream.closed && transStream.end('data: [DONE]\n\n');
1002
+ endCallback && endCallback();
1003
+ }
1004
+ // 处理联网搜索
1005
+ else if (!silentSearch && result.event == 'search_plus' && result.msg && result.msg.type == 'get_res') {
1006
+ if (!searchFlag)
1007
+ searchFlag = true;
1008
+ webSearchCount += 1;
1009
+ const data = `data: ${JSON.stringify({
1010
+ id: convId,
1011
+ model,
1012
+ object: 'chat.completion.chunk',
1013
+ choices: [
1014
+ {
1015
+ index: 0, delta: {
1016
+ content: `【检索 ${webSearchCount}】 [${result.msg.title}](${result.msg.url})\n`
1017
+ }, finish_reason: null
1018
+ }
1019
+ ],
1020
+ segment_id: segmentId,
1021
+ created
1022
+ })}\n\n`;
1023
+ !transStream.closed && transStream.write(data);
1024
+ }
1025
+ // else
1026
+ // logger.warn(result.event, result);
1027
+ }
1028
+ catch (err) {
1029
+ logger.error(err);
1030
+ !transStream.closed && transStream.end('\n\n');
1031
+ }
1032
+ });
1033
+ // 将流数据喂给SSE转换器
1034
+ stream.on("data", buffer => parser.feed(buffer.toString()));
1035
+ stream.once("error", () => !transStream.closed && transStream.end('data: [DONE]\n\n'));
1036
+ stream.once("close", () => !transStream.closed && transStream.end('data: [DONE]\n\n'));
1037
+ return transStream;
1038
+ }
1039
+
1040
+ /**
1041
+ * Token切分
1042
+ *
1043
+ * @param authorization 认证字符串
1044
+ */
1045
+ function tokenSplit(authorization: string) {
1046
+ return authorization.replace('Bearer ', '').split(',');
1047
+ }
1048
+
1049
+ /**
1050
+ * 获取Token存活状态
1051
+ */
1052
+ async function getTokenLiveStatus(refreshToken: string) {
1053
+ const result = await axios.get('https://kimi.moonshot.cn/api/auth/token/refresh', {
1054
+ headers: {
1055
+ Authorization: `Bearer ${refreshToken}`,
1056
+ Referer: 'https://kimi.moonshot.cn/',
1057
+ ...FAKE_HEADERS
1058
+ },
1059
+ timeout: 15000,
1060
+ validateStatus: () => true
1061
+ });
1062
+ try {
1063
+ const {
1064
+ access_token,
1065
+ refresh_token
1066
+ } = checkResult(result, refreshToken);
1067
+ return !!(access_token && refresh_token)
1068
+ }
1069
+ catch (err) {
1070
+ return false;
1071
+ }
1072
+ }
1073
+
1074
+ export default {
1075
+ createConversation,
1076
+ createCompletion,
1077
+ createCompletionStream,
1078
+ getTokenLiveStatus,
1079
+ tokenSplit
1080
+ };
src/api/interfaces/IStreamMessage.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default interface IStreamMessage {
2
+ id: string;
3
+ model: string;
4
+ object: string;
5
+ choices: {
6
+ index: number;
7
+ message: {
8
+ role: string;
9
+ content: string;
10
+ };
11
+ finish_reason: string;
12
+ }[];
13
+ usage: {
14
+ prompt_tokens: number;
15
+ completion_tokens: number;
16
+ total_tokens: number;
17
+ };
18
+ segment_id?: string;
19
+ created: number;
20
+ }
src/api/routes/chat.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import chat from '@/api/controllers/chat.ts';
6
+ import logger from '@/lib/logger.ts';
7
+
8
+ export default {
9
+
10
+ prefix: '/v1/chat',
11
+
12
+ post: {
13
+
14
+ '/completions': async (request: Request) => {
15
+ request
16
+ .validate('body.conversation_id', v => _.isUndefined(v) || _.isString(v))
17
+ .validate('body.messages', _.isArray)
18
+ .validate('headers.authorization', _.isString)
19
+ // refresh_token切分
20
+ const tokens = chat.tokenSplit(request.headers.authorization);
21
+ // 随机挑选一个refresh_token
22
+ const token = _.sample(tokens);
23
+ let { model, conversation_id: convId, messages, stream, use_search } = request.body;
24
+
25
+ if(use_search)
26
+ model = 'kimi-search';
27
+
28
+ if (stream) {
29
+ const stream = await chat.createCompletionStream(model, messages, token, convId);
30
+ return new Response(stream, {
31
+ type: "text/event-stream"
32
+ });
33
+ }
34
+ else
35
+ return await chat.createCompletion(model, messages, token, convId);
36
+ }
37
+
38
+ }
39
+
40
+ }
src/api/routes/index.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs-extra';
2
+
3
+ import Response from '@/lib/response/Response.ts';
4
+ import chat from "./chat.ts";
5
+ import ping from "./ping.ts";
6
+ import token from './token.ts';
7
+ import models from './models.ts';
8
+
9
+ export default [
10
+ {
11
+ get: {
12
+ '/': async () => {
13
+ const content = await fs.readFile('public/welcome.html');
14
+ return new Response(content, {
15
+ type: 'html',
16
+ headers: {
17
+ Expires: '-1'
18
+ }
19
+ });
20
+ }
21
+ }
22
+ },
23
+ chat,
24
+ ping,
25
+ token,
26
+ models
27
+ ];
src/api/routes/models.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export default {
4
+
5
+ prefix: '/v1',
6
+
7
+ get: {
8
+ '/models': async () => {
9
+ return {
10
+ "data": [
11
+ {
12
+ "id": "moonshot-v1",
13
+ "object": "model",
14
+ "owned_by": "kimi-free-api"
15
+ },
16
+ {
17
+ "id": "moonshot-v1-8k",
18
+ "object": "model",
19
+ "owned_by": "kimi-free-api"
20
+ },
21
+ {
22
+ "id": "moonshot-v1-32k",
23
+ "object": "model",
24
+ "owned_by": "kimi-free-api"
25
+ },
26
+ {
27
+ "id": "moonshot-v1-128k",
28
+ "object": "model",
29
+ "owned_by": "kimi-free-api"
30
+ },
31
+ {
32
+ "id": "moonshot-v1-vision",
33
+ "object": "model",
34
+ "owned_by": "kimi-free-api"
35
+ }
36
+ ]
37
+ };
38
+ }
39
+
40
+ }
41
+ }
src/api/routes/ping.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ prefix: '/ping',
3
+ get: {
4
+ '': async () => "pong"
5
+ }
6
+ }
src/api/routes/token.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import chat from '@/api/controllers/chat.ts';
6
+ import logger from '@/lib/logger.ts';
7
+
8
+ export default {
9
+
10
+ prefix: '/token',
11
+
12
+ post: {
13
+
14
+ '/check': async (request: Request) => {
15
+ request
16
+ .validate('body.token', _.isString)
17
+ const live = await chat.getTokenLiveStatus(request.body.token);
18
+ return {
19
+ live
20
+ }
21
+ }
22
+
23
+ }
24
+
25
+ }
src/daemon.ts ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * 守护进程
3
+ */
4
+
5
+ import process from 'process';
6
+ import path from 'path';
7
+ import { spawn } from 'child_process';
8
+
9
+ import fs from 'fs-extra';
10
+ import { format as dateFormat } from 'date-fns';
11
+ import 'colors';
12
+
13
+ const CRASH_RESTART_LIMIT = 600; //进程崩溃重启次数限制
14
+ const CRASH_RESTART_DELAY = 5000; //进程崩溃重启延迟
15
+ const LOG_PATH = path.resolve("./logs/daemon.log"); //守护进程日志路径
16
+ let crashCount = 0; //进程崩溃次数
17
+ let currentProcess; //当前运行进程
18
+
19
+ /**
20
+ * 写入守护进程日志
21
+ */
22
+ function daemonLog(value, color?: string) {
23
+ try {
24
+ const head = `[daemon][${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")}] `;
25
+ value = head + value;
26
+ console.log(color ? value[color] : value);
27
+ fs.ensureDirSync(path.dirname(LOG_PATH));
28
+ fs.appendFileSync(LOG_PATH, value + "\n");
29
+ }
30
+ catch(err) {
31
+ console.error("daemon log write error:", err);
32
+ }
33
+ }
34
+
35
+ daemonLog(`daemon pid: ${process.pid}`);
36
+
37
+ function createProcess() {
38
+ const childProcess = spawn("node", ["index.js", ...process.argv.slice(2)]); //启动子进程
39
+ childProcess.stdout.pipe(process.stdout, { end: false }); //将子进程输出管道到当前进程输出
40
+ childProcess.stderr.pipe(process.stderr, { end: false }); //将子进程错误输出管道到当前进程输出
41
+ currentProcess = childProcess; //更新当前进程
42
+ daemonLog(`process(${childProcess.pid}) has started`);
43
+ childProcess.on("error", err => daemonLog(`process(${childProcess.pid}) error: ${err.stack}`, "red"));
44
+ childProcess.on("close", code => {
45
+ if(code === 0) //进程正常退出
46
+ daemonLog(`process(${childProcess.pid}) has exited`);
47
+ else if(code === 2) //进程已被杀死
48
+ daemonLog(`process(${childProcess.pid}) has been killed!`, "bgYellow");
49
+ else if(code === 3) { //进程主动重启
50
+ daemonLog(`process(${childProcess.pid}) has restart`, "yellow");
51
+ createProcess(); //重新创建进程
52
+ }
53
+ else { //进程发生崩溃
54
+ if(crashCount++ < CRASH_RESTART_LIMIT) { //进程崩溃次数未达重启次数上限前尝试重启
55
+ daemonLog(`process(${childProcess.pid}) has crashed! delay ${CRASH_RESTART_DELAY}ms try restarting...(${crashCount})`, "bgRed");
56
+ setTimeout(() => createProcess(), CRASH_RESTART_DELAY); //延迟指定时长后再重启
57
+ }
58
+ else //进程已崩溃,且无法重启
59
+ daemonLog(`process(${childProcess.pid}) has crashed! unable to restart`, "bgRed");
60
+ }
61
+ }); //子进程关闭监听
62
+ }
63
+
64
+ process.on("exit", code => {
65
+ if(code === 0)
66
+ daemonLog("daemon process exited");
67
+ else if(code === 2)
68
+ daemonLog("daemon process has been killed!");
69
+ }); //守护进程退出事件
70
+
71
+ process.on("SIGTERM", () => {
72
+ daemonLog("received kill signal", "yellow");
73
+ currentProcess && currentProcess.kill("SIGINT");
74
+ process.exit(2);
75
+ }); //kill退出守护进程
76
+
77
+ process.on("SIGINT", () => {
78
+ currentProcess && currentProcess.kill("SIGINT");
79
+ process.exit(0);
80
+ }); //主动退出守护进程
81
+
82
+ createProcess(); //创建进程
src/index.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ import environment from "@/lib/environment.ts";
4
+ import config from "@/lib/config.ts";
5
+ import "@/lib/initialize.ts";
6
+ import server from "@/lib/server.ts";
7
+ import routes from "@/api/routes/index.ts";
8
+ import logger from "@/lib/logger.ts";
9
+
10
+ const startupTime = performance.now();
11
+
12
+ (async () => {
13
+ logger.header();
14
+
15
+ logger.info("<<<< kimi free server >>>>");
16
+ logger.info("Version:", environment.package.version);
17
+ logger.info("Process id:", process.pid);
18
+ logger.info("Environment:", environment.env);
19
+ logger.info("Service name:", config.service.name);
20
+
21
+ server.attachRoutes(routes);
22
+ await server.listen();
23
+
24
+ config.service.bindAddress &&
25
+ logger.success("Service bind address:", config.service.bindAddress);
26
+ })()
27
+ .then(() =>
28
+ logger.success(
29
+ `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
30
+ )
31
+ )
32
+ .catch((err) => console.error(err));
src/lib/config.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import serviceConfig from "./configs/service-config.ts";
2
+ import systemConfig from "./configs/system-config.ts";
3
+
4
+ class Config {
5
+
6
+ /** 服务配置 */
7
+ service = serviceConfig;
8
+
9
+ /** 系统配置 */
10
+ system = systemConfig;
11
+
12
+ }
13
+
14
+ export default new Config();
src/lib/configs/service-config.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+ import util from '../util.ts';
9
+
10
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/service.yml");
11
+
12
+ /**
13
+ * 服务配置
14
+ */
15
+ export class ServiceConfig {
16
+
17
+ /** 服务名称 */
18
+ name: string;
19
+ /** @type {string} 服务绑定主机地址 */
20
+ host;
21
+ /** @type {number} 服务绑定端口 */
22
+ port;
23
+ /** @type {string} 服务路由前缀 */
24
+ urlPrefix;
25
+ /** @type {string} 服务绑定地址(外部访问地址) */
26
+ bindAddress;
27
+
28
+ constructor(options?: any) {
29
+ const { name, host, port, urlPrefix, bindAddress } = options || {};
30
+ this.name = _.defaultTo(name, 'kimi-free-api');
31
+ this.host = _.defaultTo(host, '0.0.0.0');
32
+ this.port = _.defaultTo(port, 7860);
33
+ this.urlPrefix = _.defaultTo(urlPrefix, '');
34
+ this.bindAddress = bindAddress;
35
+ }
36
+
37
+ get addressHost() {
38
+ if(this.bindAddress) return this.bindAddress;
39
+ const ipAddresses = util.getIPAddressesByIPv4();
40
+ for(let ipAddress of ipAddresses) {
41
+ if(ipAddress === this.host)
42
+ return ipAddress;
43
+ }
44
+ return ipAddresses[0] || "127.0.0.1";
45
+ }
46
+
47
+ get address() {
48
+ return `${this.addressHost}:${this.port}`;
49
+ }
50
+
51
+ get pageDirUrl() {
52
+ return `http://127.0.0.1:${this.port}/page`;
53
+ }
54
+
55
+ get publicDirUrl() {
56
+ return `http://127.0.0.1:${this.port}/public`;
57
+ }
58
+
59
+ static load() {
60
+ const external = _.pickBy(environment, (v, k) => ["name", "host", "port"].includes(k) && !_.isUndefined(v));
61
+ if(!fs.pathExistsSync(CONFIG_PATH)) return new ServiceConfig(external);
62
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
63
+ return new ServiceConfig({ ...data, ...external });
64
+ }
65
+
66
+ }
67
+
68
+ export default ServiceConfig.load();
src/lib/configs/system-config.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+
9
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/system.yml");
10
+
11
+ /**
12
+ * 系统配置
13
+ */
14
+ export class SystemConfig {
15
+
16
+ /** 是否开启请求日志 */
17
+ requestLog: boolean;
18
+ /** 临时目录路径 */
19
+ tmpDir: string;
20
+ /** 日志目录路径 */
21
+ logDir: string;
22
+ /** 日志写入间隔(毫秒) */
23
+ logWriteInterval: number;
24
+ /** 日志文件有效期(毫秒) */
25
+ logFileExpires: number;
26
+ /** 公共目录路径 */
27
+ publicDir: string;
28
+ /** 临时文件有效期(毫秒) */
29
+ tmpFileExpires: number;
30
+ /** 请求体配置 */
31
+ requestBody: any;
32
+ /** 是否调试模式 */
33
+ debug: boolean;
34
+
35
+ constructor(options?: any) {
36
+ const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {};
37
+ this.requestLog = _.defaultTo(requestLog, false);
38
+ this.tmpDir = _.defaultTo(tmpDir, './tmp');
39
+ this.logDir = _.defaultTo(logDir, './logs');
40
+ this.logWriteInterval = _.defaultTo(logWriteInterval, 200);
41
+ this.logFileExpires = _.defaultTo(logFileExpires, 2626560000);
42
+ this.publicDir = _.defaultTo(publicDir, './public');
43
+ this.tmpFileExpires = _.defaultTo(tmpFileExpires, 86400000);
44
+ this.requestBody = Object.assign(requestBody || {}, {
45
+ enableTypes: ['json', 'form', 'text', 'xml'],
46
+ encoding: 'utf-8',
47
+ formLimit: '100mb',
48
+ jsonLimit: '100mb',
49
+ textLimit: '100mb',
50
+ xmlLimit: '100mb',
51
+ formidable: {
52
+ maxFileSize: '100mb'
53
+ },
54
+ multipart: true,
55
+ parsedMethods: ['POST', 'PUT', 'PATCH']
56
+ });
57
+ this.debug = _.defaultTo(debug, true);
58
+ }
59
+
60
+ get rootDirPath() {
61
+ return path.resolve();
62
+ }
63
+
64
+ get tmpDirPath() {
65
+ return path.resolve(this.tmpDir);
66
+ }
67
+
68
+ get logDirPath() {
69
+ return path.resolve(this.logDir);
70
+ }
71
+
72
+ get publicDirPath() {
73
+ return path.resolve(this.publicDir);
74
+ }
75
+
76
+ static load() {
77
+ if (!fs.pathExistsSync(CONFIG_PATH)) return new SystemConfig();
78
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
79
+ return new SystemConfig(data);
80
+ }
81
+
82
+ }
83
+
84
+ export default SystemConfig.load();
src/lib/consts/exceptions.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export default {
2
+ SYSTEM_ERROR: [-1000, '系统异常'],
3
+ SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, '请求参数校验错误'],
4
+ SYSTEM_NOT_ROUTE_MATCHING: [-1002, '无匹配的路由']
5
+ } as Record<string, [number, string]>
src/lib/environment.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import minimist from 'minimist';
5
+ import _ from 'lodash';
6
+
7
+ const cmdArgs = minimist(process.argv.slice(2)); //获取命令行参数
8
+ const envVars = process.env; //获取环境变量
9
+
10
+ class Environment {
11
+
12
+ /** 命令行参数 */
13
+ cmdArgs: any;
14
+ /** 环境变量 */
15
+ envVars: any;
16
+ /** 环境名称 */
17
+ env?: string;
18
+ /** 服务名称 */
19
+ name?: string;
20
+ /** 服务地址 */
21
+ host?: string;
22
+ /** 服务端口 */
23
+ port?: number;
24
+ /** 包参数 */
25
+ package: any;
26
+
27
+ constructor(options: any = {}) {
28
+ const { cmdArgs, envVars, package: _package } = options;
29
+ this.cmdArgs = cmdArgs;
30
+ this.envVars = envVars;
31
+ this.env = _.defaultTo(cmdArgs.env || envVars.SERVER_ENV, 'dev');
32
+ this.name = cmdArgs.name || envVars.SERVER_NAME || undefined;
33
+ this.host = cmdArgs.host || envVars.SERVER_HOST || undefined;
34
+ this.port = Number(cmdArgs.port || envVars.SERVER_PORT) ? Number(cmdArgs.port || envVars.SERVER_PORT) : undefined;
35
+ this.package = _package;
36
+ }
37
+
38
+ }
39
+
40
+ export default new Environment({
41
+ cmdArgs,
42
+ envVars,
43
+ package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString())
44
+ });
src/lib/exceptions/APIException.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Exception from './Exception.js';
2
+
3
+ export default class APIException extends Exception {
4
+
5
+ /**
6
+ * 构造异常
7
+ *
8
+ * @param {[number, string]} exception 异常
9
+ */
10
+ constructor(exception: (string | number)[], errmsg?: string) {
11
+ super(exception, errmsg);
12
+ }
13
+
14
+ }
src/lib/exceptions/Exception.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from 'assert';
2
+
3
+ import _ from 'lodash';
4
+
5
+ export default class Exception extends Error {
6
+
7
+ /** 错误码 */
8
+ errcode: number;
9
+ /** 错误消息 */
10
+ errmsg: string;
11
+ /** 数据 */
12
+ data: any;
13
+ /** HTTP状态码 */
14
+ httpStatusCode: number;
15
+
16
+ /**
17
+ * 构造异常
18
+ *
19
+ * @param exception 异常
20
+ * @param _errmsg 异常消息
21
+ */
22
+ constructor(exception: (string | number)[], _errmsg?: string) {
23
+ assert(_.isArray(exception), 'Exception must be Array');
24
+ const [errcode, errmsg] = exception as [number, string];
25
+ assert(_.isFinite(errcode), 'Exception errcode invalid');
26
+ assert(_.isString(errmsg), 'Exception errmsg invalid');
27
+ super(_errmsg || errmsg);
28
+ this.errcode = errcode;
29
+ this.errmsg = _errmsg || errmsg;
30
+ }
31
+
32
+ compare(exception: (string | number)[]) {
33
+ const [errcode] = exception as [number, string];
34
+ return this.errcode == errcode;
35
+ }
36
+
37
+ setHTTPStatusCode(value: number) {
38
+ this.httpStatusCode = value;
39
+ return this;
40
+ }
41
+
42
+ setData(value: any) {
43
+ this.data = _.defaultTo(value, null);
44
+ return this;
45
+ }
46
+
47
+ }
src/lib/http-status-codes.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+
3
+ CONTINUE: 100, //客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
4
+ SWITCHING_PROTOCOLS: 101, //服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
5
+ PROCESSING: 102, //处理将被继续执行
6
+
7
+ OK: 200, //请求已成功,请求所希望的响应头或数据体将随此响应返回
8
+ CREATED: 201, //请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
9
+ ACCEPTED: 202, //服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
10
+ NON_AUTHORITATIVE_INFO: 203, //服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
11
+ NO_CONTENT: 204, //服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
12
+ RESET_CONTENT: 205, //服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
13
+ PARTIAL_CONTENT: 206, //服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返���的内容
14
+ MULTIPLE_STATUS: 207, //代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
15
+
16
+ MULTIPLE_CHOICES: 300, //被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
17
+ MOVED_PERMANENTLY: 301, //被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
18
+ FOUND: 302, //请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
19
+ SEE_OTHER: 303, //对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(重定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
20
+ NOT_MODIFIED: 304, //如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
21
+ USE_PROXY: 305, //被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
22
+ UNUSED: 306, //在最新版的规范中,306状态码已经不再被使用
23
+ TEMPORARY_REDIRECT: 307, //请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
24
+
25
+ BAD_REQUEST: 400, //1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参数有误
26
+ UNAUTHORIZED: 401, //当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
27
+ PAYMENT_REQUIRED: 402, //该状态码是为了将来可能的需求而预留的
28
+ FORBIDDEN: 403, //服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
29
+ NOT_FOUND: 404, //请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
30
+ METHOD_NOT_ALLOWED: 405, //请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
31
+ NO_ACCEPTABLE: 406, //请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
32
+ PROXY_AUTHENTICATION_REQUIRED: 407, //与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
33
+ REQUEST_TIMEOUT: 408, //请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
34
+ CONFLICT: 409, //由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源���修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
35
+ GONE: 410, //被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
36
+ LENGTH_REQUIRED: 411, //服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
37
+ PRECONDITION_FAILED: 412, //服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
38
+ REQUEST_ENTITY_TOO_LARGE: 413, //服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
39
+ REQUEST_URI_TOO_LONG: 414, //请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
40
+ UNSUPPORTED_MEDIA_TYPE: 415, //对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
41
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416, //如果请求中包含了Range请求头,并且Range中指定的任何数据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
42
+ EXPECTION_FAILED: 417, //在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
43
+ TOO_MANY_CONNECTIONS: 421, //从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
44
+ UNPROCESSABLE_ENTITY: 422, //请求格式正确,但是由于含有语义错误,无法响应
45
+ FAILED_DEPENDENCY: 424, //由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
46
+ UNORDERED_COLLECTION: 425, //在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
47
+ UPGRADE_REQUIRED: 426, //客户端应当切换到TLS/1.0
48
+ RETRY_WITH: 449, //由微软扩展,代表请求应当在执行完适当的操作后进行重试
49
+
50
+ INTERNAL_SERVER_ERROR: 500, //服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
51
+ NOT_IMPLEMENTED: 501, //服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
52
+ BAD_GATEWAY: 502, //作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
53
+ SERVICE_UNAVAILABLE: 503, //由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
54
+ GATEWAY_TIMEOUT: 504, //作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
55
+ HTTP_VERSION_NOT_SUPPORTED: 505, //服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
56
+ VARIANT_ALSO_NEGOTIATES: 506, //服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
57
+ INSUFFICIENT_STORAGE: 507, //服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
58
+ BANDWIDTH_LIMIT_EXCEEDED: 509, //服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
59
+ NOT_EXTENDED: 510 //获取资源所需要的策略并没有没满足
60
+
61
+ };
src/lib/initialize.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logger from './logger.js';
2
+
3
+ // 允许无限量的监听器
4
+ process.setMaxListeners(Infinity);
5
+ // 输出未捕获异常
6
+ process.on("uncaughtException", (err, origin) => {
7
+ logger.error(`An unhandled error occurred: ${origin}`, err);
8
+ });
9
+ // 输出未处理的Promise.reject
10
+ process.on("unhandledRejection", (_, promise) => {
11
+ promise.catch(err => logger.error("An unhandled rejection occurred:", err));
12
+ });
13
+ // 输出系统警告信息
14
+ process.on("warning", warning => logger.warn("System warning: ", warning));
15
+ // 进程退出监听
16
+ process.on("exit", () => {
17
+ logger.info("Service exit");
18
+ logger.footer();
19
+ });
20
+ // 进程被kill
21
+ process.on("SIGTERM", () => {
22
+ logger.warn("received kill signal");
23
+ process.exit(2);
24
+ });
25
+ // Ctrl-C进程退出
26
+ process.on("SIGINT", () => {
27
+ process.exit(0);
28
+ });
src/lib/interfaces/ICompletionMessage.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export default interface ICompletionMessage {
2
+ role: 'system' | 'assistant' | 'user' | 'function';
3
+ content: string;
4
+ }
src/lib/logger.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import _util from 'util';
3
+
4
+ import 'colors';
5
+ import _ from 'lodash';
6
+ import fs from 'fs-extra';
7
+ import { format as dateFormat } from 'date-fns';
8
+
9
+ import config from './config.ts';
10
+ import util from './util.ts';
11
+
12
+ const isVercelEnv = process.env.VERCEL;
13
+
14
+ class LogWriter {
15
+
16
+ #buffers = [];
17
+
18
+ constructor() {
19
+ !isVercelEnv && fs.ensureDirSync(config.system.logDirPath);
20
+ !isVercelEnv && this.work();
21
+ }
22
+
23
+ push(content) {
24
+ const buffer = Buffer.from(content);
25
+ this.#buffers.push(buffer);
26
+ }
27
+
28
+ writeSync(buffer) {
29
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
30
+ }
31
+
32
+ async write(buffer) {
33
+ !isVercelEnv && await fs.appendFile(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
34
+ }
35
+
36
+ flush() {
37
+ if(!this.#buffers.length) return;
38
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), Buffer.concat(this.#buffers));
39
+ }
40
+
41
+ work() {
42
+ if (!this.#buffers.length) return setTimeout(this.work.bind(this), config.system.logWriteInterval);
43
+ const buffer = Buffer.concat(this.#buffers);
44
+ this.#buffers = [];
45
+ this.write(buffer)
46
+ .finally(() => setTimeout(this.work.bind(this), config.system.logWriteInterval))
47
+ .catch(err => console.error("Log write error:", err));
48
+ }
49
+
50
+ }
51
+
52
+ class LogText {
53
+
54
+ /** @type {string} 日志级别 */
55
+ level;
56
+ /** @type {string} 日志文本 */
57
+ text;
58
+ /** @type {string} 日志来源 */
59
+ source;
60
+ /** @type {Date} 日志发生时间 */
61
+ time = new Date();
62
+
63
+ constructor(level, ...params) {
64
+ this.level = level;
65
+ this.text = _util.format.apply(null, params);
66
+ this.source = this.#getStackTopCodeInfo();
67
+ }
68
+
69
+ #getStackTopCodeInfo() {
70
+ const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
71
+ const stackArray = new Error().stack.split("\n");
72
+ const text = stackArray[4];
73
+ if (!text)
74
+ return unknownInfo;
75
+ const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
76
+ if (!match || !_.isString(match[2] || match[1]))
77
+ return unknownInfo;
78
+ const temp = match[2] || match[1];
79
+ const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
80
+ if (!_match)
81
+ return unknownInfo;
82
+ const [, scriptPath, codeLine, codeColumn] = _match as any;
83
+ return {
84
+ name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
85
+ path: scriptPath || null,
86
+ codeLine: parseInt(codeLine || 0),
87
+ codeColumn: parseInt(codeColumn || 0)
88
+ };
89
+ }
90
+
91
+ toString() {
92
+ return `[${dateFormat(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
93
+ }
94
+
95
+ }
96
+
97
+ class Logger {
98
+
99
+ /** @type {Object} 系统配置 */
100
+ config = {};
101
+ /** @type {Object} 日志级别映射 */
102
+ static Level = {
103
+ Success: "success",
104
+ Info: "info",
105
+ Log: "log",
106
+ Debug: "debug",
107
+ Warning: "warning",
108
+ Error: "error",
109
+ Fatal: "fatal"
110
+ };
111
+ /** @type {Object} 日志级别文本颜色樱色 */
112
+ static LevelColor = {
113
+ [Logger.Level.Success]: "green",
114
+ [Logger.Level.Info]: "brightCyan",
115
+ [Logger.Level.Debug]: "white",
116
+ [Logger.Level.Warning]: "brightYellow",
117
+ [Logger.Level.Error]: "brightRed",
118
+ [Logger.Level.Fatal]: "red"
119
+ };
120
+ #writer;
121
+
122
+ constructor() {
123
+ this.#writer = new LogWriter();
124
+ }
125
+
126
+ header() {
127
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG START ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
128
+ }
129
+
130
+ footer() {
131
+ this.#writer.flush(); //将未写入文件的日志缓存写入
132
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG END ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
133
+ }
134
+
135
+ success(...params) {
136
+ const content = new LogText(Logger.Level.Success, ...params).toString();
137
+ console.info(content[Logger.LevelColor[Logger.Level.Success]]);
138
+ this.#writer.push(content + "\n");
139
+ }
140
+
141
+ info(...params) {
142
+ const content = new LogText(Logger.Level.Info, ...params).toString();
143
+ console.info(content[Logger.LevelColor[Logger.Level.Info]]);
144
+ this.#writer.push(content + "\n");
145
+ }
146
+
147
+ log(...params) {
148
+ const content = new LogText(Logger.Level.Log, ...params).toString();
149
+ console.log(content[Logger.LevelColor[Logger.Level.Log]]);
150
+ this.#writer.push(content + "\n");
151
+ }
152
+
153
+ debug(...params) {
154
+ if(!config.system.debug) return; //非调试模式忽略debug
155
+ const content = new LogText(Logger.Level.Debug, ...params).toString();
156
+ console.debug(content[Logger.LevelColor[Logger.Level.Debug]]);
157
+ this.#writer.push(content + "\n");
158
+ }
159
+
160
+ warn(...params) {
161
+ const content = new LogText(Logger.Level.Warning, ...params).toString();
162
+ console.warn(content[Logger.LevelColor[Logger.Level.Warning]]);
163
+ this.#writer.push(content + "\n");
164
+ }
165
+
166
+ error(...params) {
167
+ const content = new LogText(Logger.Level.Error, ...params).toString();
168
+ console.error(content[Logger.LevelColor[Logger.Level.Error]]);
169
+ this.#writer.push(content);
170
+ }
171
+
172
+ fatal(...params) {
173
+ const content = new LogText(Logger.Level.Fatal, ...params).toString();
174
+ console.error(content[Logger.LevelColor[Logger.Level.Fatal]]);
175
+ this.#writer.push(content);
176
+ }
177
+
178
+ destory() {
179
+ this.#writer.destory();
180
+ }
181
+
182
+ }
183
+
184
+ export default new Logger();
src/lib/request/Request.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import APIException from '@/lib/exceptions/APIException.ts';
4
+ import EX from '@/api/consts/exceptions.ts';
5
+ import logger from '@/lib/logger.ts';
6
+ import util from '@/lib/util.ts';
7
+
8
+ export interface RequestOptions {
9
+ time?: number;
10
+ }
11
+
12
+ export default class Request {
13
+
14
+ /** 请求方法 */
15
+ method: string;
16
+ /** 请求URL */
17
+ url: string;
18
+ /** 请求路径 */
19
+ path: string;
20
+ /** 请求载荷类型 */
21
+ type: string;
22
+ /** 请求headers */
23
+ headers: any;
24
+ /** 请求原始查询字符串 */
25
+ search: string;
26
+ /** 请求查询参数 */
27
+ query: any;
28
+ /** 请求URL参数 */
29
+ params: any;
30
+ /** 请求载荷 */
31
+ body: any;
32
+ /** 上传的文件 */
33
+ files: any[];
34
+ /** 客户端IP地址 */
35
+ remoteIP: string | null;
36
+ /** 请求接受时间戳(毫秒) */
37
+ time: number;
38
+
39
+ constructor(ctx, options: RequestOptions = {}) {
40
+ const { time } = options;
41
+ this.method = ctx.request.method;
42
+ this.url = ctx.request.url;
43
+ this.path = ctx.request.path;
44
+ this.type = ctx.request.type;
45
+ this.headers = ctx.request.headers || {};
46
+ this.search = ctx.request.search;
47
+ this.query = ctx.query || {};
48
+ this.params = ctx.params || {};
49
+ this.body = ctx.request.body || {};
50
+ this.files = ctx.request.files || {};
51
+ this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null;
52
+ this.time = Number(_.defaultTo(time, util.timestamp()));
53
+ }
54
+
55
+ validate(key: string, fn?: Function) {
56
+ try {
57
+ const value = _.get(this, key);
58
+ if (fn) {
59
+ if (fn(value) === false)
60
+ throw `[Mismatch] -> ${fn}`;
61
+ }
62
+ else if (_.isUndefined(value))
63
+ throw '[Undefined]';
64
+ }
65
+ catch (err) {
66
+ logger.warn(`Params ${key} invalid:`, err);
67
+ throw new APIException(EX.API_REQUEST_PARAMS_INVALID, `Params ${key} invalid`);
68
+ }
69
+ return this;
70
+ }
71
+
72
+ }
src/lib/response/Body.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export interface BodyOptions {
4
+ code?: number;
5
+ message?: string;
6
+ data?: any;
7
+ statusCode?: number;
8
+ }
9
+
10
+ export default class Body {
11
+
12
+ /** 状态码 */
13
+ code: number;
14
+ /** 状态消息 */
15
+ message: string;
16
+ /** 载荷 */
17
+ data: any;
18
+ /** HTTP状态码 */
19
+ statusCode: number;
20
+
21
+ constructor(options: BodyOptions = {}) {
22
+ const { code, message, data, statusCode } = options;
23
+ this.code = Number(_.defaultTo(code, 0));
24
+ this.message = _.defaultTo(message, 'OK');
25
+ this.data = _.defaultTo(data, null);
26
+ this.statusCode = Number(_.defaultTo(statusCode, 200));
27
+ }
28
+
29
+ toObject() {
30
+ return {
31
+ code: this.code,
32
+ message: this.message,
33
+ data: this.data
34
+ };
35
+ }
36
+
37
+ static isInstance(value) {
38
+ return value instanceof Body;
39
+ }
40
+
41
+ }
src/lib/response/FailureBody.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+ import Exception from '../exceptions/Exception.ts';
5
+ import APIException from '../exceptions/APIException.ts';
6
+ import EX from '../consts/exceptions.ts';
7
+ import HTTP_STATUS_CODES from '../http-status-codes.ts';
8
+
9
+ export default class FailureBody extends Body {
10
+
11
+ constructor(error: APIException | Exception | Error, _data?: any) {
12
+ let errcode, errmsg, data = _data, httpStatusCode = HTTP_STATUS_CODES.OK;;
13
+ if(_.isString(error))
14
+ error = new Exception(EX.SYSTEM_ERROR, error);
15
+ else if(error instanceof APIException || error instanceof Exception)
16
+ ({ errcode, errmsg, data, httpStatusCode } = error);
17
+ else if(_.isError(error))
18
+ ({ errcode, errmsg, data, httpStatusCode } = new Exception(EX.SYSTEM_ERROR, error.message));
19
+ super({
20
+ code: errcode || -1,
21
+ message: errmsg || 'Internal error',
22
+ data,
23
+ statusCode: httpStatusCode
24
+ });
25
+ }
26
+
27
+ static isInstance(value) {
28
+ return value instanceof FailureBody;
29
+ }
30
+
31
+ }
src/lib/response/Response.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mime from 'mime';
2
+ import _ from 'lodash';
3
+
4
+ import Body from './Body.ts';
5
+ import util from '../util.ts';
6
+
7
+ export interface ResponseOptions {
8
+ statusCode?: number;
9
+ type?: string;
10
+ headers?: Record<string, any>;
11
+ redirect?: string;
12
+ body?: any;
13
+ size?: number;
14
+ time?: number;
15
+ }
16
+
17
+ export default class Response {
18
+
19
+ /** 响应HTTP状态码 */
20
+ statusCode: number;
21
+ /** 响应内容类型 */
22
+ type: string;
23
+ /** 响应headers */
24
+ headers: Record<string, any>;
25
+ /** 重定向目标 */
26
+ redirect: string;
27
+ /** 响应载荷 */
28
+ body: any;
29
+ /** 响应载荷大小 */
30
+ size: number;
31
+ /** 响应时间戳 */
32
+ time: number;
33
+
34
+ constructor(body: any, options: ResponseOptions = {}) {
35
+ const { statusCode, type, headers, redirect, size, time } = options;
36
+ this.statusCode = Number(_.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : undefined))
37
+ this.type = type;
38
+ this.headers = headers;
39
+ this.redirect = redirect;
40
+ this.size = size;
41
+ this.time = Number(_.defaultTo(time, util.timestamp()));
42
+ this.body = body;
43
+ }
44
+
45
+ injectTo(ctx) {
46
+ this.redirect && ctx.redirect(this.redirect);
47
+ this.statusCode && (ctx.status = this.statusCode);
48
+ this.type && (ctx.type = mime.getType(this.type) || this.type);
49
+ const headers = this.headers || {};
50
+ if(this.size && !headers["Content-Length"] && !headers["content-length"])
51
+ headers["Content-Length"] = this.size;
52
+ ctx.set(headers);
53
+ if(Body.isInstance(this.body))
54
+ ctx.body = this.body.toObject();
55
+ else
56
+ ctx.body = this.body;
57
+ }
58
+
59
+ static isInstance(value) {
60
+ return value instanceof Response;
61
+ }
62
+
63
+ }
src/lib/response/SuccessfulBody.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+
5
+ export default class SuccessfulBody extends Body {
6
+
7
+ constructor(data: any, message?: string) {
8
+ super({
9
+ code: 0,
10
+ message: _.defaultTo(message, "OK"),
11
+ data
12
+ });
13
+ }
14
+
15
+ static isInstance(value) {
16
+ return value instanceof SuccessfulBody;
17
+ }
18
+
19
+ }
src/lib/server.ts ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Koa from 'koa';
2
+ import KoaRouter from 'koa-router';
3
+ import koaRange from 'koa-range';
4
+ import koaCors from "koa2-cors";
5
+ import koaBody from 'koa-body';
6
+ import _ from 'lodash';
7
+
8
+ import Exception from './exceptions/Exception.ts';
9
+ import Request from './request/Request.ts';
10
+ import Response from './response/Response.js';
11
+ import FailureBody from './response/FailureBody.ts';
12
+ import EX from './consts/exceptions.ts';
13
+ import logger from './logger.ts';
14
+ import config from './config.ts';
15
+
16
+ class Server {
17
+
18
+ app;
19
+ router;
20
+
21
+ constructor() {
22
+ this.app = new Koa();
23
+ this.app.use(koaCors());
24
+ // 范围请求支持
25
+ this.app.use(koaRange);
26
+ this.router = new KoaRouter({ prefix: config.service.urlPrefix });
27
+ // 前置处理异常拦截
28
+ this.app.use(async (ctx: any, next: Function) => {
29
+ if(ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml")
30
+ ctx.req.headers["content-type"] = "text/xml";
31
+ try { await next() }
32
+ catch (err) {
33
+ logger.error(err);
34
+ const failureBody = new FailureBody(err);
35
+ new Response(failureBody).injectTo(ctx);
36
+ }
37
+ });
38
+ // 载荷解析器支持
39
+ this.app.use(koaBody(_.clone(config.system.requestBody)));
40
+ this.app.on("error", (err: any) => {
41
+ // 忽略连接重试、中断、管道、取消错误
42
+ if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return;
43
+ logger.error(err);
44
+ });
45
+ logger.success("Server initialized");
46
+ }
47
+
48
+ /**
49
+ * 附加路由
50
+ *
51
+ * @param routes 路由列表
52
+ */
53
+ attachRoutes(routes: any[]) {
54
+ routes.forEach((route: any) => {
55
+ const prefix = route.prefix || "";
56
+ for (let method in route) {
57
+ if(method === "prefix") continue;
58
+ if (!_.isObject(route[method])) {
59
+ logger.warn(`Router ${prefix} ${method} invalid`);
60
+ continue;
61
+ }
62
+ for (let uri in route[method]) {
63
+ this.router[method](`${prefix}${uri}`, async ctx => {
64
+ const { request, response } = await this.#requestProcessing(ctx, route[method][uri]);
65
+ if(response != null && config.system.requestLog)
66
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
67
+ });
68
+ }
69
+ }
70
+ logger.info(`Route ${config.service.urlPrefix || ""}${prefix} attached`);
71
+ });
72
+ this.app.use(this.router.routes());
73
+ this.app.use((ctx: any) => {
74
+ const request = new Request(ctx);
75
+ logger.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`);
76
+ // const failureBody = new FailureBody(new Exception(EX.SYSTEM_NOT_ROUTE_MATCHING, "Request is not supported"));
77
+ // const response = new Response(failureBody);
78
+ const message = `[请求有误]: 正确请求为 POST -> /v1/chat/completions,当前请求为 ${ctx.request.method} -> ${ctx.request.url} 请纠正`;
79
+ logger.warn(message);
80
+ const failureBody = new FailureBody(new Error(message));
81
+ const response = new Response(failureBody);
82
+ response.injectTo(ctx);
83
+ if(config.system.requestLog)
84
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
85
+ });
86
+ }
87
+
88
+ /**
89
+ * 请求处理
90
+ *
91
+ * @param ctx 上下文
92
+ * @param routeFn 路由方法
93
+ */
94
+ #requestProcessing(ctx: any, routeFn: Function): Promise<any> {
95
+ return new Promise(resolve => {
96
+ const request = new Request(ctx);
97
+ try {
98
+ if(config.system.requestLog)
99
+ logger.info(`-> ${request.method} ${request.url}`);
100
+ routeFn(request)
101
+ .then(response => {
102
+ try {
103
+ if(!Response.isInstance(response)) {
104
+ const _response = new Response(response);
105
+ _response.injectTo(ctx);
106
+ return resolve({ request, response: _response });
107
+ }
108
+ response.injectTo(ctx);
109
+ resolve({ request, response });
110
+ }
111
+ catch(err) {
112
+ logger.error(err);
113
+ const failureBody = new FailureBody(err);
114
+ const response = new Response(failureBody);
115
+ response.injectTo(ctx);
116
+ resolve({ request, response });
117
+ }
118
+ })
119
+ .catch(err => {
120
+ try {
121
+ logger.error(err);
122
+ const failureBody = new FailureBody(err);
123
+ const response = new Response(failureBody);
124
+ response.injectTo(ctx);
125
+ resolve({ request, response });
126
+ }
127
+ catch(err) {
128
+ logger.error(err);
129
+ const failureBody = new FailureBody(err);
130
+ const response = new Response(failureBody);
131
+ response.injectTo(ctx);
132
+ resolve({ request, response });
133
+ }
134
+ });
135
+ }
136
+ catch(err) {
137
+ logger.error(err);
138
+ const failureBody = new FailureBody(err);
139
+ const response = new Response(failureBody);
140
+ response.injectTo(ctx);
141
+ resolve({ request, response });
142
+ }
143
+ });
144
+ }
145
+
146
+ /**
147
+ * 监听端口
148
+ */
149
+ async listen() {
150
+ const host = config.service.host;
151
+ const port = config.service.port;
152
+ await Promise.all([
153
+ new Promise((resolve, reject) => {
154
+ if(host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1")
155
+ return resolve(null);
156
+ this.app.listen(port, "localhost", err => {
157
+ if(err) return reject(err);
158
+ resolve(null);
159
+ });
160
+ }),
161
+ new Promise((resolve, reject) => {
162
+ this.app.listen(port, host, err => {
163
+ if(err) return reject(err);
164
+ resolve(null);
165
+ });
166
+ })
167
+ ]);
168
+ logger.success(`Server listening on port ${port} (${host})`);
169
+ }
170
+
171
+ }
172
+
173
+ export default new Server();
src/lib/util.ts ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os from 'os';
2
+ import path from 'path';
3
+ import crypto from 'crypto';
4
+ import { Readable, Writable } from 'stream';
5
+
6
+ import 'colors';
7
+ import mime from 'mime';
8
+ import fs from 'fs-extra';
9
+ import { v1 as uuid } from 'uuid';
10
+ import { format as dateFormat } from 'date-fns';
11
+ import CRC32 from 'crc-32';
12
+ import randomstring from 'randomstring';
13
+ import _ from 'lodash';
14
+ import { CronJob } from 'cron';
15
+
16
+ import HTTP_STATUS_CODE from './http-status-codes.ts';
17
+
18
+ const autoIdMap = new Map();
19
+
20
+ const util = {
21
+
22
+ is2DArrays(value: any) {
23
+ return _.isArray(value) && (!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1])));
24
+ },
25
+
26
+ uuid: (separator = true) => separator ? uuid() : uuid().replace(/\-/g, ""),
27
+
28
+ autoId: (prefix = '') => {
29
+ let index = autoIdMap.get(prefix);
30
+ if(index > 999999) index = 0; //超过最大数字则重置为0
31
+ autoIdMap.set(prefix, (index || 0) + 1);
32
+ return `${prefix}${index || 1}`;
33
+ },
34
+
35
+ ignoreJSONParse(value: string) {
36
+ const result = _.attempt(() => JSON.parse(value));
37
+ if(_.isError(result))
38
+ return null;
39
+ return result;
40
+ },
41
+
42
+ generateRandomString(options: any): string {
43
+ return randomstring.generate(options);
44
+ },
45
+
46
+ getResponseContentType(value: any): string | null {
47
+ return value.headers ? (value.headers["content-type"] || value.headers["Content-Type"]) : null;
48
+ },
49
+
50
+ generateCookie() {
51
+ const timestamp = util.unixTimestamp();
52
+ const items = [
53
+ `Hm_lvt_358cae4815e85d48f7e8ab7f3680a74b=${timestamp - Math.round(Math.random() * 2592000)}`,
54
+ `_ga=GA1.1.${util.generateRandomString({ length: 10, charset: 'numeric' })}.${timestamp - Math.round(Math.random() * 2592000)}`,
55
+ `_ga_YXD8W70SZP=GS1.1.${timestamp - Math.round(Math.random() * 2592000)}.1.1.${timestamp - Math.round(Math.random() * 2592000)}.0.0.0`,
56
+ `Hm_lpvt_358cae4815e85d48f7e8ab7f3680a74b=${timestamp - Math.round(Math.random() * 2592000)}`
57
+ ];
58
+ return items.join('; ');
59
+ },
60
+
61
+ mimeToExtension(value: string) {
62
+ let extension = mime.getExtension(value);
63
+ if(extension == "mpga")
64
+ return "mp3";
65
+ return extension;
66
+ },
67
+
68
+ extractURLExtension(value: string) {
69
+ const extname = path.extname(new URL(value).pathname);
70
+ return extname.substring(1).toLowerCase();
71
+ },
72
+
73
+ createCronJob(cronPatterns: any, callback?: Function) {
74
+ if(!_.isFunction(callback)) throw new Error("callback must be an Function");
75
+ return new CronJob(cronPatterns, () => callback(), null, false, "Asia/Shanghai");
76
+ },
77
+
78
+ getDateString(format = "yyyy-MM-dd", date = new Date()) {
79
+ return dateFormat(date, format);
80
+ },
81
+
82
+ getIPAddressesByIPv4(): string[] {
83
+ const interfaces = os.networkInterfaces();
84
+ const addresses = [];
85
+ for (let name in interfaces) {
86
+ const networks = interfaces[name];
87
+ const results = networks.filter(network => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal);
88
+ if (results[0] && results[0].address)
89
+ addresses.push(results[0].address);
90
+ }
91
+ return addresses;
92
+ },
93
+
94
+ getMACAddressesByIPv4(): string[] {
95
+ const interfaces = os.networkInterfaces();
96
+ const addresses = [];
97
+ for (let name in interfaces) {
98
+ const networks = interfaces[name];
99
+ const results = networks.filter(network => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal);
100
+ if (results[0] && results[0].mac)
101
+ addresses.push(results[0].mac);
102
+ }
103
+ return addresses;
104
+ },
105
+
106
+ generateSSEData(event?: string, data?: string, retry?: number) {
107
+ return `event: ${event || "message"}\ndata: ${(data || "").replace(/\n/g, "\\n").replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`;
108
+ },
109
+
110
+ buildDataBASE64(type, ext, buffer) {
111
+ return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString("base64")}`;
112
+ },
113
+
114
+ isLinux() {
115
+ return os.platform() !== "win32";
116
+ },
117
+
118
+ isIPAddress(value) {
119
+ return _.isString(value) && (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(value) || /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(value));
120
+ },
121
+
122
+ isPort(value) {
123
+ return _.isNumber(value) && value > 0 && value < 65536;
124
+ },
125
+
126
+ isReadStream(value): boolean {
127
+ return value && (value instanceof Readable || "readable" in value || value.readable);
128
+ },
129
+
130
+ isWriteStream(value): boolean {
131
+ return value && (value instanceof Writable || "writable" in value || value.writable);
132
+ },
133
+
134
+ isHttpStatusCode(value) {
135
+ return _.isNumber(value) && Object.values(HTTP_STATUS_CODE).includes(value);
136
+ },
137
+
138
+ isURL(value) {
139
+ return !_.isUndefined(value) && /^(http|https)/.test(value);
140
+ },
141
+
142
+ isSrc(value) {
143
+ return !_.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
144
+ },
145
+
146
+ isBASE64(value) {
147
+ return !_.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
148
+ },
149
+
150
+ isBASE64Data(value) {
151
+ return /^data:/.test(value);
152
+ },
153
+
154
+ extractBASE64DataFormat(value): string | null {
155
+ const match = value.trim().match(/^data:(.+);base64,/);
156
+ if(!match) return null;
157
+ return match[1];
158
+ },
159
+
160
+ removeBASE64DataHeader(value): string {
161
+ return value.replace(/^data:(.+);base64,/, "");
162
+ },
163
+
164
+ isDataString(value): boolean {
165
+ return /^(base64|json):/.test(value);
166
+ },
167
+
168
+ isStringNumber(value) {
169
+ return _.isFinite(Number(value));
170
+ },
171
+
172
+ isUnixTimestamp(value) {
173
+ return /^[0-9]{10}$/.test(`${value}`);
174
+ },
175
+
176
+ isTimestamp(value) {
177
+ return /^[0-9]{13}$/.test(`${value}`);
178
+ },
179
+
180
+ isEmail(value) {
181
+ return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value);
182
+ },
183
+
184
+ isAsyncFunction(value) {
185
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
186
+ },
187
+
188
+ async isAPNG(filePath) {
189
+ let head;
190
+ const readStream = fs.createReadStream(filePath, { start: 37, end: 40 });
191
+ const readPromise = new Promise((resolve, reject) => {
192
+ readStream.once("end", resolve);
193
+ readStream.once("error", reject);
194
+ });
195
+ readStream.once("data", data => head = data);
196
+ await readPromise;
197
+ return head.compare(Buffer.from([0x61, 0x63, 0x54, 0x4c])) === 0;
198
+ },
199
+
200
+ unixTimestamp() {
201
+ return parseInt(`${Date.now() / 1000}`);
202
+ },
203
+
204
+ timestamp() {
205
+ return Date.now();
206
+ },
207
+
208
+ urlJoin(...values) {
209
+ let url = "";
210
+ for (let i = 0; i < values.length; i++)
211
+ url += `${i > 0 ? "/" : ""}${values[i].replace(/^\/*/, "").replace(/\/*$/, "")}`;
212
+ return url;
213
+ },
214
+
215
+ millisecondsToHmss(milliseconds) {
216
+ if (_.isString(milliseconds)) return milliseconds;
217
+ milliseconds = parseInt(milliseconds);
218
+ const sec = Math.floor(milliseconds / 1000);
219
+ const hours = Math.floor(sec / 3600);
220
+ const minutes = Math.floor((sec - hours * 3600) / 60);
221
+ const seconds = sec - hours * 3600 - minutes * 60;
222
+ const ms = milliseconds % 60000 - seconds * 1000;
223
+ return `${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
224
+ },
225
+
226
+ millisecondsToTimeString(milliseconds) {
227
+ if(milliseconds < 1000)
228
+ return `${milliseconds}ms`;
229
+ if(milliseconds < 60000)
230
+ return `${parseFloat((milliseconds / 1000).toFixed(2))}s`;
231
+ return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor(milliseconds / 1000 % 60)}s`;
232
+ },
233
+
234
+ rgbToHex(r, g, b): string {
235
+ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
236
+ },
237
+
238
+ hexToRgb(hex) {
239
+ const value = parseInt(hex.replace(/^#/, ""), 16);
240
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
241
+ },
242
+
243
+ md5(value) {
244
+ return crypto.createHash("md5").update(value).digest("hex");
245
+ },
246
+
247
+ crc32(value) {
248
+ return _.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value);
249
+ },
250
+
251
+ arrayParse(value): any[] {
252
+ return _.isArray(value) ? value : [value];
253
+ },
254
+
255
+ booleanParse(value) {
256
+ return value === "true" || value === true ? true : false
257
+ },
258
+
259
+ encodeBASE64(value) {
260
+ return Buffer.from(value).toString("base64");
261
+ },
262
+
263
+ decodeBASE64(value) {
264
+ return Buffer.from(value, "base64").toString();
265
+ },
266
+
267
+ };
268
+
269
+ export default util;
tsconfig.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "allowImportingTsExtensions": true,
7
+ "allowSyntheticDefaultImports": true,
8
+ "noEmit": true,
9
+ "paths": {
10
+ "@/*": ["src/*"]
11
+ },
12
+ "outDir": "./dist"
13
+ },
14
+ "include": ["src/**/*", "libs.d.ts"],
15
+ "exclude": ["node_modules", "dist"]
16
+ }