├── .gitignore
├── LICENSE
├── README-CN.md
├── README-EN.md
├── README.md
├── app-test.exe
├── app-test.go
├── cookies
└── 把含有cookie的txt放在这里
├── go.mod
├── go.sum
├── grok3_api_arm64
├── 一键编译.sh
├── 一键编译Mac.sh
├── 一键编译Windows.bat
├── 测试版启动器.bat
└── 稳定版
├── app-test.exe
├── app-test.go
├── app.go
├── grok3_api_stable
├── grok3_api_stable_arm64
├── 仅保存初始代码,无更多附加功能
└── 启动.bat
/.gitignore:
--------------------------------------------------------------------------------
1 | *.json
2 | grok3_api
3 | *.exe
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README-CN.md:
--------------------------------------------------------------------------------
1 | # Grok 3 Web API 封装工具
2 |
3 | [English](README.md) | [中文](README-CN.md)
4 |
5 | 这是一个基于Go语言的工具,设计用于与Grok 3 Web API交互,提供与OpenAI兼容的聊天补全端点。它使用户能够向Grok 3 Web API发送消息,并以与OpenAI聊天补全API一致的格式接收响应。
6 |
7 | ## 功能特点
8 |
9 | - **OpenAI兼容端点**:支持 `/v1/chat/completions` 和 `/v1/models` 端点。
10 | - **流式响应支持**:实现实时流式响应。
11 | - **模型选择**:可选择标准模型或推理模型。
12 | - **Cookie管理**:管理多个Cookie。
13 | - **代理支持**:兼容HTTP和SOCKS5代理进行网络请求。
14 | - **网络搜索**:新增搜索功能(3月8日),通过 `enableSearch: 1` 参数启用。
15 | - **长文本支持**:使用 `-longtxt` 参数进行文件附件上传。
16 | - **自定义Cookie目录**:通过 `-cookiesDir` 参数设置自定义Cookie目录。
17 | - **IPv4强制使用**:添加 `DualStack: false` 字段强制使用IPv4。
18 |
19 | ## 快速使用指南
20 |
21 | ### 1. 配置 Cookie
22 | - **📂 存放位置:** 将你的 Cookie 以 `.txt` 格式存放在 `cookies` 文件夹中。
23 | - **📌 命名规则:** 每个 `.txt` 文件代表一条 Cookie,文件名可自由命名。
24 | - **⚠️ 内容要求:** 仅保留 `sso=xxxxxx` 字段,删除其他内容。
25 |
26 | ### 2. 启动项目
27 | - **✏️ 写入Token:** 修改 `启动.bat` 中的 `Token` 字段。默认为:123456
28 | - **▶ 运行** `启动.bat` **一键启动**。
29 |
30 | ### 3. 解决授权错误
31 | 如果遇到 **❌ "Unauthorized: Bearer token required"** 错误,请尝试在 **SillyTavern API** 的 **自定义密钥** 中输入默认 Token:123456(或者你自己设定的Token)。
32 |
33 | ### 4. 解决\n\n格式问题
34 | - 请使用[正则表达式](https://github.com/GhostXia/grok3_api-Fix/blob/main/grok3_%E6%9B%BF%E6%8D%A2%E5%9B%9E%E8%BD%A6%E7%AC%A6%E5%8F%B7.json),作者:[orzogc](https://github.com/orzogc)
35 | - 大多数情况下,重新生成一下回复就能解决问题。
36 |
37 | ## 配置选项
38 |
39 | 你可以使用命令行标志或环境变量配置客户端。
40 |
41 | ### 命令行标志
42 |
43 | - `-token`:API认证令牌(**必需**)。
44 | - `-cookie`:用于认证的Grok cookie。接受单个cookie或JSON数组格式的多个cookie。
45 | - `-cookiesDir`:自定义cookie文件目录路径(默认:"cookies")。
46 | - `-longtxt`:启用长文本处理,可选阈值(例如,`-longtxt 60000`,默认:40000)。
47 | - `-httpProxy` 或 `-httpproxy`:指定HTTP或SOCKS5代理URL(例如,`http://127.0.0.1:1080`)。
48 | - `-port`:设置服务器端口(默认:8180)。
49 |
50 | ### 请求体参数
51 |
52 | 使用 `/v1/chat/completions` 端点时,可以在请求体中设置一些配置:
53 |
54 | ```json
55 | {
56 | "messages": [],
57 | "model": "grok-3", // "grok-3" 为标准模型,"grok-3-reasoning" 为推理模型
58 | "stream": true, // true 表示流式响应
59 | "grokCookies": ["cookie1", "cookie2"], // 单个cookie字符串或cookie数组
60 | "cookieIndex": 1, // cookie索引(从1开始),0表示自动选择
61 | "enableSearch": 1, // 1表示启用网络搜索,0表示禁用
62 | "keepChat": 1, // 1表示保留聊天对话,0表示不保留
63 | "ignoreThinking": 1 // 1表示从推理模型响应中排除思考令牌
64 | }
65 | ```
66 |
67 | ## 附加信息
68 |
69 | ❌ **不支持的文件格式:**
70 | - **不支持:** `xxxx.xxx.txt` 形式的文件名。
71 | - **请直接使用:** `xxxxx.txt` 格式。
72 |
73 | 📌 **其他说明**
74 | - 其余功能与原项目相同,参考:[grok3_api](https://github.com/orzogc/grok3_api)
75 | - 使用代理时,如果出现连接失败提示,尝试使用 `-httpproxy http://127.0.0.1:xxxx`
76 |
77 | **安卓用户提示**
78 | - 启动命令参考(后台启动):`./grok-server -token your-auth-token -cookie xxxxxxx -port 8180 &`
79 | - 已用 `DualStack: false` 强制使用IPv4。
80 | - 具体使用参考:https://grok.com/share/bGVnYWN5_7cafcf60-ca6b-4097-bdbc-ffaee19b2e2c
81 |
82 | ## 警告
83 |
84 | 本工具提供了Grok 3的非官方OpenAI兼容API,因此使用本工具可能导致您的账户被xAI**封禁**。
85 |
86 | 请勿滥用或将此工具用于商业目的。使用风险自负。
87 |
88 | ## 许可证
89 |
90 | 本项目采用GNU Affero通用公共许可证v3.0 - 详情请参阅[LICENSE](LICENSE)文件。
91 |
92 | ## 特别感谢
93 |
94 | - [mem0ai/grok3-api: 非官方Grok 3 API](https://github.com/mem0ai/grok3-api)
95 | - [RoCry/grok3-api-cf: 通过Cloudflare免费使用Grok 3 API](https://github.com/RoCry/grok3-api-cf/tree/master)
96 | - [orzogc/grok3_api: 原始项目](https://github.com/orzogc/grok3_api)
97 | - 大部分代码由Grok 3编写,感谢Grok 3。
--------------------------------------------------------------------------------
/README-EN.md:
--------------------------------------------------------------------------------
1 | # Grok 3 Web API Wrapper
2 |
3 | This is a Go-based tool designed to interact with the Grok 3 Web API, offering an OpenAI-compatible endpoint for chat completions. It enables users to send messages to the Grok 3 Web API and receive responses in a format consistent with OpenAI's chat completion API.
4 |
5 | ## Features
6 |
7 | - **OpenAI-Compatible Endpoint**: Supports `/v1/chat/completions` and `/v1/models` endpoints.
8 | - **Streaming Support**: Enables real-time streaming of responses.
9 | - **Model Selection**: Choose between standard and reasoning models.
10 | - **Cookie Management**: Manages multiple cookies.
11 | - **Proxy Support**: Compatible with HTTP and SOCKS5 proxies for network requests.
12 | - **Configurable Options**: Includes flags for retaining chat conversations, filtering thinking content, and adding custom text to prompts.
13 |
14 | ## Prerequisites
15 |
16 | Before you use this tool, ensure you have the following:
17 |
18 | - **Grok Cookie**: Obtain your account's cookie from [grok.com](https://grok.com) by your browser.
19 | - **Authentication Token**: Prepare a token to secure the API endpoint.
20 |
21 | ## Configuration
22 |
23 | You can configure the client using command-line flags or environment variables.
24 |
25 | ### Command-Line Flags
26 |
27 | - `-token`: API authentication token (**required**).
28 | - `-cookie`: Grok cookie(s) for authentication. Accepts a single cookie or a JSON array of cookies.
29 | - `-textBeforePrompt`: Text to add before the user’s message. The default text can be viewed by using the `-help` flag.
30 | - `-textAfterPrompt`: Text to add after the user’s message (default: empty string).
31 | - `-keepChat`: Retains chat conversations after each request if set.
32 | - `-ignoreThinking`: Excludes thinking tokens from responses when using the reasoning model.
33 | - `-httpProxy` or `-httpproxy`: Specifies an HTTP or SOCKS5 proxy URL. The proxy URL should be something like `http://127.0.0.1:1080` or `socks5://127.0.0.1:1080`.
34 | - `-port`: Sets the server port (default: 8180).
35 | - `-help`: Prints the help message.
36 | - `-cookiesDir`: -cookiesDir /path/to/cookies
37 |
38 | Basic usage:
39 |
40 | The API authentication token is **required** while running this tool. The Grok cookie must be set by the `-cookie` flag or the request body.
41 |
42 | ```
43 | grok3_api -token your_secret_token
44 | ```
45 |
46 | ### Environment Variables
47 |
48 | `GROK3_AUTH_TOKEN`: Alternative to the `-token` flag.
49 |
50 | `GROK3_COOKIE`: Alternative to the `-cookie` flag.
51 |
52 | `http_proxy`: Alternative to the `-httpProxy` flag.
53 |
54 | ### Request Body for Completion
55 |
56 | Some configurations can be set in the request body while using the `/v1/chat/completions` endpoint.
57 |
58 | Request body (JSON):
59 |
60 | ```json
61 | {
62 | "messages": [],
63 | "model": "grok-3", // "grok-3" for the standard Grok 3 model, "grok-3-reasoning" for the Grok 3 reasoning model.
64 | "stream": true, // true for streaming response.
65 | "grokCookies": ["cookie1", "cookie2"], // a string for a single cookie, or a list of strings for multiple cookies.
66 | "cookieIndex": 1, // the index of cookie (starting from 1) to request Grok 3 Web API. If the index is 0, auto selecting cookies in turn (defalut behaviour).
67 | "textBeforePrompt": "System: You are a helpful assistant.", // text to add before the user’s message. The default text can be viewed by using the `-help` flag.
68 | "textAfterPrompt": "End of message.", // text to add after the user’s message (default: empty string).
69 | "keepChat": 1, // 1 to retain this chat conversation, 0 to not retain it (defalut behaviour).
70 | "ignoreThinking": 1 // 1 to exclude thinking tokens from the response when using the reasoning model, 0 to retain thinking tokens (defalut behaviour).
71 | }
72 | ```
73 |
74 | ## Warnings
75 |
76 | This tool offers an unofficial OpenAI-compatible API of Grok 3, so your account may be **banned** by xAI if using this tool.
77 |
78 | Please do not abuse or use this tool for commercial purposes. Use it at your own risk.
79 |
80 | ## Special Thanks
81 |
82 | - [mem0ai/grok3-api: Unofficial Grok 3 API](https://github.com/mem0ai/grok3-api)
83 | - [RoCry/grok3-api-cf: Grok 3 via API with Cloudflare for free](https://github.com/RoCry/grok3-api-cf/tree/master)
84 | - Most code was written by Grok 3, so thanks to Grok 3.
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Grok 3 Web API Wrapper
2 |
3 | [English](README.md) | [中文](README-CN.md)
4 |
5 | This is a Go-based tool designed to interact with the Grok 3 Web API, offering an OpenAI-compatible endpoint for chat completions. It enables users to send messages to the Grok 3 Web API and receive responses in a format consistent with OpenAI's chat completion API.
6 |
7 | ## Features
8 |
9 | - **OpenAI-Compatible Endpoint**: Supports `/v1/chat/completions` and `/v1/models` endpoints.
10 | - **Streaming Support**: Enables real-time streaming of responses.
11 | - **Model Selection**: Choose between standard and reasoning models.
12 | - **Cookie Management**: Manages multiple cookies.
13 | - **Proxy Support**: Compatible with HTTP and SOCKS5 proxies for network requests.
14 | - **Web Search**: Added search functionality (March 8th), enable with `enableSearch: 1` parameter.
15 | - **Long Text Support**: Use `-longtxt` parameter for file attachments.
16 | - **Custom Cookie Directory**: Set custom cookie directory with `-cookiesDir` parameter.
17 | - **IPv4 Enforcement**: Added `DualStack: false` field to force IPv4 usage.
18 |
19 | ## Quick Start Guide
20 |
21 | ### 1. Configure Cookie
22 | - **📂 Storage Location:** Place your Cookie in `.txt` format in the `cookies` folder.
23 | - **📌 Naming Rules:** Each `.txt` file represents one Cookie, and you can name the file freely.
24 | - **⚠️ Content Requirements:** Keep only the `sso=xxxxxx` field, delete other content.
25 |
26 | ### 2. Launch the Project
27 | - **✏️ Set Token:** Modify the `Token` field in `启动.bat`. Default is: 123456
28 | - **▶ Run** `启动.bat` **for one-click startup**.
29 |
30 | ### 3. Resolve Authorization Errors
31 | If you encounter **❌ "Unauthorized: Bearer token required"** error, try entering the default Token: 123456 (or your custom Token) in the **Custom Key** of the **SillyTavern API**.
32 |
33 | ### 4. Fix \n\n Format Issues
34 | - Use the [regex](https://github.com/GhostXia/grok3_api-Fix/blob/main/grok3_%E6%9B%BF%E6%8D%A2%E5%9B%9E%E8%BD%A6%E7%AC%A6%E5%8F%B7.json) by author: [orzogc](https://github.com/orzogc)
35 | - In most cases, simply regenerating the response will fix the issue.
36 |
37 | ## Configuration
38 |
39 | You can configure the client using command-line flags or environment variables.
40 |
41 | ### Command-Line Flags
42 |
43 | - `-token`: API authentication token (**required**).
44 | - `-cookie`: Grok cookie(s) for authentication. Accepts a single cookie or a JSON array of cookies.
45 | - `-cookiesDir`: Custom directory path for cookie files (default: "cookies").
46 | - `-longtxt`: Enable long text processing with optional threshold (e.g., `-longtxt 60000`, default: 40000).
47 | - `-httpProxy` 或 `-httpproxy`: 指定HTTP或SOCKS5代理URL(例如,`http://127.0.0.1:1080`)。
48 | - `-port`: Sets the server port (default: 8180).
49 |
50 | ### Request Body Parameters
51 |
52 | Some configurations can be set in the request body while using the `/v1/chat/completions` endpoint:
53 |
54 | ```json
55 | {
56 | "messages": [],
57 | "model": "grok-3", // "grok-3" for standard model, "grok-3-reasoning" for reasoning model
58 | "stream": true, // true for streaming response
59 | "grokCookies": ["cookie1", "cookie2"], // single cookie string or array of cookies
60 | "cookieIndex": 1, // cookie index (starting from 1), 0 for auto-selection
61 | "enableSearch": 1, // 1 to enable web search, 0 to disable
62 | "keepChat": 1, // 1 to retain chat conversation, 0 to not retain
63 | "ignoreThinking": 1 // 1 to exclude thinking tokens from reasoning model response
64 | }
65 | ```
66 |
67 | ## Additional Information
68 |
69 | ❌ **Unsupported File Formats:**
70 | - **Not supported:** `xxxx.xxx.txt` filename format.
71 | - **Please use:** `xxxxx.txt` format directly.
72 |
73 | 📌 **Other Notes**
74 | - Other features are the same as the original project: [grok3_api](https://github.com/orzogc/grok3_api)
75 | - When using a proxy with connection failures, try `-httpproxy http://127.0.0.1:xxxx`
76 |
77 | **Android User Tips**
78 | - Startup command reference (background): `./grok-server -token your-auth-token -cookie xxxxxxx -port 8180 &`
79 | - IPv4 is enforced with `DualStack: false`.
80 | - For detailed usage, see: https://grok.com/share/bGVnYWN5_7cafcf60-ca6b-4097-bdbc-ffaee19b2e2c
81 |
82 | ## Warning
83 |
84 | This tool offers an unofficial OpenAI-compatible API of Grok 3, so your account may be **banned** by xAI if using this tool.
85 |
86 | Please do not abuse or use this tool for commercial purposes. Use it at your own risk.
87 |
88 | ## License
89 |
90 | This project is licensed under the GNU Affero General Public License v3.0 - see the [LICENSE](LICENSE) file for details.
91 |
92 | ## Special Thanks
93 |
94 | - [mem0ai/grok3-api: Unofficial Grok 3 API](https://github.com/mem0ai/grok3-api)
95 | - [RoCry/grok3-api-cf: Grok 3 via API with Cloudflare for free](https://github.com/RoCry/grok3-api-cf/tree/master)
96 | - [orzogc/grok3_api: Original project](https://github.com/orzogc/grok3_api)
97 | - Most code was written by Grok 3, so thanks to Grok 3.
98 |
--------------------------------------------------------------------------------
/app-test.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/app-test.exe
--------------------------------------------------------------------------------
/app-test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "compress/gzip"
6 | "encoding/base64"
7 | "encoding/json"
8 | "flag"
9 | "fmt"
10 | "io"
11 | "log"
12 | "net"
13 | "net/http"
14 | "net/url"
15 | "os"
16 | "path/filepath"
17 | "strconv"
18 | "strings"
19 | "sync"
20 | "time"
21 | "unicode/utf8"
22 |
23 | "github.com/andybalholm/brotli"
24 | "github.com/google/uuid"
25 | )
26 |
27 | // GrokClient 定义了与 Grok 3 Web API 交互的客户端。
28 | type GrokClient struct {
29 | headers map[string]string // HTTP 请求头
30 | isReasoning bool // 是否使用推理模型
31 | enableSearch bool // 是否启用网络搜索
32 | uploadMessage bool // 是否将消息上传为文件
33 | keepChat bool // 是否保留聊天历史
34 | ignoreThinking bool // 是否忽略思考令牌
35 | enableUpload bool // 是否启用文件上传
36 | }
37 |
38 | // NewGrokClient 创建一个新的 GrokClient 实例。
39 | func NewGrokClient(cookie string, isReasoning, enableSearch, uploadMessage, keepChat, ignoreThinking, enableUpload bool) *GrokClient {
40 | return &GrokClient{
41 | headers: map[string]string{
42 | "accept": "*/*",
43 | "accept-encoding": "gzip, deflate, br, zstd",
44 | "accept-language": "en-US;q=0.9,en;q=0.8",
45 | "content-type": "application/json",
46 | "host": "grok.com",
47 | "origin": "https://grok.com",
48 | "dnt": "1",
49 | "priority": "u=1, i",
50 | "referer": "https://grok.com/",
51 | "sec-ch-ua": `"Not:A-Brand";v="24", "Chromium";v="134"`,
52 | "sec-ch-ua-mobile": "?0",
53 | "sec-ch-ua-platform": `"Linux"`,
54 | "sec-fetch-dest": "empty",
55 | "sec-fetch-mode": "cors",
56 | "sec-fetch-site": "same-origin",
57 | "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
58 | "cookie": cookie,
59 | },
60 | isReasoning: isReasoning,
61 | enableSearch: enableSearch,
62 | uploadMessage: uploadMessage,
63 | keepChat: keepChat,
64 | ignoreThinking: ignoreThinking,
65 | enableUpload: enableUpload,
66 | }
67 | }
68 |
69 | // ToolOverrides 定义工具覆盖选项。
70 | type ToolOverrides struct {
71 | ImageGen bool `json:"imageGen"`
72 | TrendsSearch bool `json:"trendsSearch"`
73 | WebSearch bool `json:"webSearch"`
74 | XMediaSearch bool `json:"xMediaSearch"`
75 | XPostAnalyze bool `json:"xPostAnalyze"`
76 | XSearch bool `json:"xSearch"`
77 | }
78 |
79 | // preparePayload 构造 Grok 3 Web API 的请求负载。
80 | func (c *GrokClient) preparePayload(message string, fileId string) map[string]any {
81 | var toolOverrides any = ToolOverrides{}
82 | if c.enableSearch {
83 | toolOverrides = map[string]any{}
84 | }
85 |
86 | fileAttachments := []string{}
87 | if fileId != "" {
88 | fileAttachments = []string{fileId}
89 | }
90 |
91 | return map[string]any{
92 | "deepsearchPreset": "",
93 | "disableSearch": false,
94 | "enableImageGeneration": true,
95 | "enableImageStreaming": true,
96 | "enableSideBySide": true,
97 | "fileAttachments": fileAttachments,
98 | "forceConcise": false,
99 | "imageAttachments": []string{},
100 | "imageGenerationCount": 2,
101 | "isPreset": false,
102 | "isReasoning": c.isReasoning,
103 | "message": message,
104 | "modelName": "grok-3",
105 | "returnImageBytes": false,
106 | "returnRawGrokInXaiRequest": false,
107 | "sendFinalMetadata": true,
108 | "temporary": !c.keepChat,
109 | "toolOverrides": toolOverrides,
110 | "webpageUrls": []string{},
111 | }
112 | }
113 |
114 | // getModelName 根据 isReasoning 标志返回模型名称。
115 | func (c *GrokClient) getModelName() string {
116 | if c.isReasoning {
117 | return grok3ReasoningModelName
118 | }
119 | return grok3ModelName
120 | }
121 |
122 | // RequestBody 表示 /v1/chat/completions 的 POST 请求 JSON 结构体。
123 | type RequestBody struct {
124 | Model string `json:"model"`
125 | Messages []struct {
126 | Role string `json:"role"`
127 | Content any `json:"content"`
128 | } `json:"messages"`
129 | Stream bool `json:"stream"`
130 | GrokCookies any `json:"grokCookies,omitempty"`
131 | CookieIndex uint `json:"cookieIndex,omitempty"`
132 | EnableSearch int `json:"enableSearch,omitempty"`
133 | UploadMessage int `json:"uploadMessage,omitempty"`
134 | TextBeforePrompt string `json:"textBeforePrompt,omitempty"`
135 | TextAfterPrompt string `json:"textAfterPrompt,omitempty"`
136 | KeepChat int `json:"keepChat,omitempty"`
137 | IgnoreThinking int `json:"ignoreThinking,omitempty"`
138 | }
139 |
140 | // ResponseToken 表示 Grok 3 Web API 的单个令牌响应。
141 | type ResponseToken struct {
142 | Result struct {
143 | Response struct {
144 | Token string `json:"token"`
145 | IsThinking bool `json:"isThinking"`
146 | } `json:"response"`
147 | } `json:"result"`
148 | }
149 |
150 | // ModelData 表示 OpenAI 兼容响应的模型元数据。
151 | type ModelData struct {
152 | Id string `json:"id"`
153 | Object string `json:"object"`
154 | Owned_by string `json:"owned_by"`
155 | }
156 |
157 | // ModelList 包含 OpenAI 兼容端点的可用模型。
158 | type ModelList struct {
159 | Object string `json:"object"`
160 | Data []ModelData `json:"data"`
161 | }
162 |
163 | // UploadFileRequest 表示上传文件的请求结构体。
164 | type UploadFileRequest struct {
165 | Content string `json:"content"`
166 | FileMimeType string `json:"fileMimeType"`
167 | FileName string `json:"fileName"`
168 | }
169 |
170 | // UploadFileResponse 表示上传文件的响应结构体。
171 | type UploadFileResponse struct {
172 | FileMetadataId string `json:"fileMetadataId"`
173 | }
174 |
175 | const (
176 | newChatUrl = "https://grok.com/rest/app-chat/conversations/new"
177 | uploadFileUrl = "https://grok.com/rest/app-chat/upload-file"
178 | grok3ModelName = "grok-3"
179 | grok3ReasoningModelName = "grok-3-reasoning"
180 | completionsPath = "/v1/chat/completions"
181 | listModelsPath = "/v1/models"
182 | messageCharsLimit = 50000
183 | defaultBeforePromptText = "For the data below, entries with '[[system]]' are system information, entries with '[[assistant]]' are messages you have previously sent, entries with '[[user]]' are messages sent by the user. You need to respond to the user's last message accordingly based on the corresponding data."
184 | defaultUploadMessagePrompt = "Follow the instructions in the attached file to respond."
185 | )
186 |
187 | // 全局配置变量
188 | var (
189 | apiToken *string
190 | grokCookies []string
191 | textBeforePrompt *string
192 | textAfterPrompt *string
193 | keepChat *bool
194 | ignoreThinking *bool
195 | charsLimit *uint
196 | longTxt *bool // 控制是否启用长文本上传
197 | longTxtThreshold int // 长文本阈值(不需要指针,因为在 main 中解析后固定)
198 | httpProxy *string
199 | cookiesDir *string
200 | httpClient = &http.Client{Timeout: 30 * time.Minute}
201 | cookie *string
202 | port *uint
203 | nextCookieIndex = struct {
204 | sync.Mutex
205 | index uint
206 | }{}
207 | cookieStatus = struct {
208 | sync.Mutex
209 | status map[string]bool // true 表示有效,false 表示失效
210 | }{
211 | status: make(map[string]bool),
212 | }
213 | )
214 |
215 | // decompressBody 解压响应体。
216 | func decompressBody(resp *http.Response) (io.ReadCloser, error) {
217 | switch resp.Header.Get("content-encoding") {
218 | case "br":
219 | return io.NopCloser(brotli.NewReader(resp.Body)), nil
220 | case "gzip":
221 | return gzip.NewReader(resp.Body)
222 | case "":
223 | return resp.Body, nil
224 | default:
225 | return nil, fmt.Errorf("未知的响应编码: %s", resp.Header.Get("content-encoding"))
226 | }
227 | }
228 |
229 | // doRequest 发送 HTTP 请求并返回响应。
230 | func (c *GrokClient) doRequest(method, url string, payload any) (*http.Response, error) {
231 | jsonPayload, err := json.Marshal(payload)
232 | if err != nil {
233 | return nil, fmt.Errorf("序列化请求负载失败: %v", err)
234 | }
235 |
236 | req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonPayload))
237 | if err != nil {
238 | return nil, fmt.Errorf("创建请求失败: %v", err)
239 | }
240 |
241 | for key, value := range c.headers {
242 | req.Header.Set(key, value)
243 | }
244 |
245 | resp, err := httpClient.Do(req)
246 | if err != nil {
247 | return nil, fmt.Errorf("发送请求失败: %v", err)
248 | }
249 | if resp.StatusCode != http.StatusOK {
250 | defer resp.Body.Close()
251 | respBody, err := decompressBody(resp)
252 | if err != nil {
253 | return nil, err
254 | }
255 | defer respBody.Close()
256 | body, err := io.ReadAll(respBody)
257 | if err != nil {
258 | return nil, fmt.Errorf("Grok API 错误: %s", resp.Status)
259 | }
260 | return nil, fmt.Errorf("Grok API 错误: %s, 响应体: %s", resp.Status, string(body)[:min(len(body), 128)])
261 | }
262 | return resp, nil
263 | }
264 |
265 | // uploadMessageAsFile 将消息上传为文件并返回文件 ID。
266 | func (c *GrokClient) uploadMessageAsFile(message string) (*UploadFileResponse, error) {
267 | content := base64.StdEncoding.EncodeToString([]byte(message))
268 | payload := UploadFileRequest{
269 | Content: content,
270 | FileMimeType: "text/plain",
271 | FileName: uuid.New().String() + ".txt",
272 | }
273 | log.Println("正在将消息上传为文件")
274 | resp, err := c.doRequest(http.MethodPost, uploadFileUrl, payload)
275 | if err != nil {
276 | return nil, err
277 | }
278 | defer resp.Body.Close()
279 | respBody, err := decompressBody(resp)
280 | if err != nil {
281 | return nil, err
282 | }
283 | defer respBody.Close()
284 | body, err := io.ReadAll(respBody)
285 | if err != nil {
286 | return nil, fmt.Errorf("上传文件错误: %d %s", resp.StatusCode, resp.Status)
287 | }
288 | response := &UploadFileResponse{}
289 | err = json.Unmarshal(body, response)
290 | if err != nil {
291 | return nil, fmt.Errorf("解析 JSON 错误: %s", string(body))
292 | }
293 | if response.FileMetadataId == "" {
294 | return nil, fmt.Errorf("上传文件错误: FileMetadataId 为空")
295 | }
296 | return response, nil
297 | }
298 |
299 | // sendMessage 向 Grok 3 Web API 发送消息并返回响应体。
300 | func (c *GrokClient) sendMessage(message string, stream bool) (io.ReadCloser, error) {
301 | fileId := ""
302 | if (c.enableUpload || c.uploadMessage) && utf8.RuneCountInString(message) >= longTxtThreshold {
303 | log.Printf("启用 -longtxt,消息长度 %d 超过 %d,正在上传文件", utf8.RuneCountInString(message), longTxtThreshold)
304 | uploadResp, err := c.uploadMessageAsFile(message)
305 | if err != nil {
306 | log.Printf("文件上传失败: %v", err)
307 | return nil, err
308 | }
309 | fileId = uploadResp.FileMetadataId
310 | log.Printf("文件上传成功,文件ID: %s", fileId)
311 | message = defaultUploadMessagePrompt
312 | }
313 |
314 | payload := c.preparePayload(message, fileId)
315 | resp, err := c.doRequest(http.MethodPost, newChatUrl, payload)
316 | if err != nil {
317 | return nil, err
318 | }
319 |
320 | respBody, err := decompressBody(resp)
321 | if err != nil {
322 | resp.Body.Close()
323 | return nil, err
324 | }
325 |
326 | if stream {
327 | return respBody, nil
328 | }
329 | defer respBody.Close()
330 | body, err := io.ReadAll(respBody)
331 | if err != nil {
332 | return nil, fmt.Errorf("读取响应体失败: %v", err)
333 | }
334 | return io.NopCloser(bytes.NewReader(body)), nil
335 | }
336 |
337 | // parseGrok3StreamingJson 解析 Grok 3 的流式响应。
338 | func (c *GrokClient) parseGrok3StreamingJson(stream io.Reader, handler func(respToken string)) {
339 | isThinking := false
340 | decoder := json.NewDecoder(stream)
341 | for {
342 | var token ResponseToken
343 | err := decoder.Decode(&token)
344 | if err == io.EOF {
345 | break
346 | } else if err != nil {
347 | log.Printf("解析 JSON 错误: %v", err)
348 | break
349 | }
350 |
351 | respToken := token.Result.Response.Token
352 | if c.ignoreThinking && token.Result.Response.IsThinking {
353 | continue
354 | } else if token.Result.Response.IsThinking {
355 | if !isThinking {
356 | respToken = "\n" + respToken
357 | }
358 | isThinking = true
359 | } else if isThinking {
360 | respToken = respToken + "\n\n\n"
361 | isThinking = false
362 | }
363 |
364 | if respToken != "" {
365 | handler(respToken)
366 | }
367 | }
368 | }
369 |
370 | // OpenAIChatCompletionMessage 定义 OpenAI 响应的消息结构。
371 | type OpenAIChatCompletionMessage struct {
372 | Role string `json:"role"`
373 | Content string `json:"content"`
374 | }
375 |
376 | // OpenAIChatCompletionChunkChoice 定义流式响应中的选择结构。
377 | type OpenAIChatCompletionChunkChoice struct {
378 | Index int `json:"index"`
379 | Delta OpenAIChatCompletionMessage `json:"delta"`
380 | FinishReason string `json:"finish_reason"`
381 | }
382 |
383 | // OpenAIChatCompletionChunk 表示 OpenAI 的流式响应格式。
384 | type OpenAIChatCompletionChunk struct {
385 | ID string `json:"id"`
386 | Object string `json:"object"`
387 | Created int64 `json:"created"`
388 | Model string `json:"model"`
389 | Choices []OpenAIChatCompletionChunkChoice `json:"choices"`
390 | }
391 |
392 | // OpenAIChatCompletionChoice 定义完整响应中的选择结构。
393 | type OpenAIChatCompletionChoice struct {
394 | Index int `json:"index"`
395 | Message OpenAIChatCompletionMessage `json:"message"`
396 | FinishReason string `json:"finish_reason"`
397 | }
398 |
399 | // OpenAIChatCompletionUsage 跟踪令牌使用情况。
400 | type OpenAIChatCompletionUsage struct {
401 | PromptTokens int `json:"prompt_tokens"`
402 | CompletionTokens int `json:"completion_tokens"`
403 | TotalTokens int `json:"total_tokens"`
404 | }
405 |
406 | // OpenAIChatCompletion 表示 OpenAI 的非流式响应格式。
407 | type OpenAIChatCompletion struct {
408 | ID string `json:"id"`
409 | Object string `json:"object"`
410 | Created int64 `json:"created"`
411 | Model string `json:"model"`
412 | Choices []OpenAIChatCompletionChoice `json:"choices"`
413 | Usage OpenAIChatCompletionUsage `json:"usage"`
414 | }
415 |
416 | // createOpenAIStreamingResponse 返回流式响应处理函数。
417 | func (c *GrokClient) createOpenAIStreamingResponse(grokStream io.Reader) http.HandlerFunc {
418 | return func(w http.ResponseWriter, r *http.Request) {
419 | w.Header().Set("Content-Type", "text/event-stream")
420 | w.Header().Set("Cache-Control", "no-cache")
421 | w.Header().Set("Connection", "keep-alive")
422 |
423 | flusher, ok := w.(http.Flusher)
424 | if !ok {
425 | log.Println("流式传输不支持")
426 | http.Error(w, "流式传输不支持", http.StatusInternalServerError)
427 | return
428 | }
429 |
430 | completionID := "chatcmpl-" + uuid.New().String()
431 | startChunk := OpenAIChatCompletionChunk{
432 | ID: completionID,
433 | Object: "chat.completion.chunk",
434 | Created: time.Now().Unix(),
435 | Model: c.getModelName(),
436 | Choices: []OpenAIChatCompletionChunkChoice{
437 | {Index: 0, Delta: OpenAIChatCompletionMessage{Role: "assistant"}, FinishReason: ""},
438 | },
439 | }
440 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(startChunk))
441 | flusher.Flush()
442 |
443 | c.parseGrok3StreamingJson(grokStream, func(respToken string) {
444 | chunk := OpenAIChatCompletionChunk{
445 | ID: completionID,
446 | Object: "chat.completion.chunk",
447 | Created: time.Now().Unix(),
448 | Model: c.getModelName(),
449 | Choices: []OpenAIChatCompletionChunkChoice{
450 | {Index: 0, Delta: OpenAIChatCompletionMessage{Content: respToken}, FinishReason: ""},
451 | },
452 | }
453 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(chunk))
454 | flusher.Flush()
455 | })
456 |
457 | finalChunk := OpenAIChatCompletionChunk{
458 | ID: completionID,
459 | Object: "chat.completion.chunk",
460 | Created: time.Now().Unix(),
461 | Model: c.getModelName(),
462 | Choices: []OpenAIChatCompletionChunkChoice{
463 | {Index: 0, Delta: OpenAIChatCompletionMessage{}, FinishReason: "stop"},
464 | },
465 | }
466 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(finalChunk))
467 | flusher.Flush()
468 |
469 | fmt.Fprintf(w, "data: [DONE]\n\n")
470 | flusher.Flush()
471 | }
472 | }
473 |
474 | // createOpenAIFullResponse 返回完整响应处理函数。
475 | func (c *GrokClient) createOpenAIFullResponse(grokFull io.Reader) http.HandlerFunc {
476 | return func(w http.ResponseWriter, r *http.Request) {
477 | var fullResponse strings.Builder
478 | c.parseGrok3StreamingJson(grokFull, func(respToken string) {
479 | fullResponse.WriteString(respToken)
480 | })
481 |
482 | openAIResponse := c.createOpenAIFullResponseBody(fullResponse.String())
483 | w.Header().Set("Content-Type", "application/json")
484 | if err := json.NewEncoder(w).Encode(openAIResponse); err != nil {
485 | log.Printf("编码响应错误: %v", err)
486 | http.Error(w, fmt.Sprintf("编码响应错误: %v", err), http.StatusInternalServerError)
487 | }
488 | }
489 | }
490 |
491 | // createOpenAIFullResponseBody 创建非流式请求的 OpenAI 响应体。
492 | func (c *GrokClient) createOpenAIFullResponseBody(content string) OpenAIChatCompletion {
493 | return OpenAIChatCompletion{
494 | ID: "chatcmpl-" + uuid.New().String(),
495 | Object: "chat.completion",
496 | Created: time.Now().Unix(),
497 | Model: c.getModelName(),
498 | Choices: []OpenAIChatCompletionChoice{
499 | {
500 | Index: 0,
501 | Message: OpenAIChatCompletionMessage{Role: "assistant", Content: content},
502 | FinishReason: "stop",
503 | },
504 | },
505 | Usage: OpenAIChatCompletionUsage{PromptTokens: -1, CompletionTokens: -1, TotalTokens: -1},
506 | }
507 | }
508 |
509 | // mustMarshal 将值序列化为 JSON 字符串。
510 | func mustMarshal(v any) string {
511 | b, err := json.Marshal(v)
512 | if err != nil {
513 | panic(err)
514 | }
515 | return string(b)
516 | }
517 |
518 | // min 返回两个整数中的较小值
519 | func min(a, b int) int {
520 | if a < b {
521 | return a
522 | }
523 | return b
524 | }
525 |
526 | // getCookieIndex 返回下一个有效的 cookie 索引
527 | func getCookieIndex(cookies []string, currentIndex uint) uint {
528 | cookieStatus.Lock()
529 | defer cookieStatus.Unlock()
530 |
531 | // 检查是否所有 cookie 都失效
532 | allInvalid := true
533 | for _, ck := range cookies {
534 | if cookieStatus.status[ck] {
535 | allInvalid = false
536 | break
537 | }
538 | }
539 | if allInvalid {
540 | log.Println("所有 cookie 已失效,重置状态并重新轮询")
541 | for _, ck := range cookies {
542 | cookieStatus.status[ck] = true // 重置所有 cookie 为有效
543 | }
544 | }
545 |
546 | // 寻找下一个有效 cookie
547 | maxAttempts := len(cookies)
548 | attempts := 0
549 | index := currentIndex % uint(len(cookies))
550 | for attempts < maxAttempts {
551 | if cookieStatus.status[cookies[index]] {
552 | return index
553 | }
554 | index = (index + 1) % uint(len(cookies))
555 | attempts++
556 | }
557 | // 如果没有有效 cookie(理论上不会发生,因为上面已重置),返回 0
558 | return 0
559 | }
560 |
561 | // loadCookiesFromDir 从指定目录加载 cookies。
562 | func loadCookiesFromDir(dir string) error {
563 | if _, err := os.Stat(dir); os.IsNotExist(err) {
564 | return fmt.Errorf("cookie 目录不存在: %s", dir)
565 | }
566 |
567 | files, err := os.ReadDir(dir)
568 | if err != nil {
569 | return fmt.Errorf("读取目录 %s 失败: %v", dir, err)
570 | }
571 |
572 | grokCookies = []string{}
573 | for _, file := range files {
574 | if !file.IsDir() && strings.HasSuffix(file.Name(), ".txt") {
575 | filePath := filepath.Join(dir, file.Name())
576 | content, err := os.ReadFile(filePath)
577 | if err != nil {
578 | log.Printf("警告: 读取 cookie 文件 %s 失败: %v", filePath, err)
579 | continue
580 | }
581 | cookie := strings.TrimSpace(string(content))
582 | if cookie != "" {
583 | grokCookies = append(grokCookies, cookie)
584 | log.Printf("从 %s 加载 cookie", filePath)
585 | }
586 | }
587 | }
588 | return nil
589 | }
590 |
591 | // handleChatCompletion 处理 /v1/chat/completions 的 POST 请求。
592 | func handleChatCompletion(w http.ResponseWriter, r *http.Request) {
593 | log.Printf("来自 %s 的请求,路径: %s", r.RemoteAddr, completionsPath)
594 |
595 | if r.URL.Path != completionsPath || r.Method != http.MethodPost {
596 | log.Printf("无效请求: 方法 %s, 路径 %s", r.Method, r.URL.Path)
597 | http.Error(w, "方法不允许或路径未找到", http.StatusMethodNotAllowed)
598 | return
599 | }
600 |
601 | authHeader := r.Header.Get("Authorization")
602 | if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
603 | log.Println("未授权: 需要 Bearer 令牌")
604 | http.Error(w, "未授权: 需要 Bearer 令牌", http.StatusUnauthorized)
605 | return
606 | }
607 |
608 | token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
609 | if token != *apiToken {
610 | log.Println("未授权: 无效令牌")
611 | http.Error(w, "未授权: 无效令牌", http.StatusUnauthorized)
612 | return
613 | }
614 |
615 | var body RequestBody
616 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
617 | log.Println("错误请求: 无效 JSON")
618 | http.Error(w, "错误请求: 无效 JSON", http.StatusBadRequest)
619 | return
620 | }
621 |
622 | if len(body.Messages) == 0 {
623 | log.Println("错误请求: 未提供消息")
624 | http.Error(w, "错误请求: 未提供消息", http.StatusBadRequest)
625 | return
626 | }
627 |
628 | var cookie string
629 | var cookieIndex uint
630 | if body.GrokCookies != nil {
631 | if ck, ok := body.GrokCookies.(string); ok {
632 | cookie = ck
633 | } else if list, ok := body.GrokCookies.([]any); ok {
634 | if len(list) > 0 {
635 | // 将 []any 转换为 []string
636 | cookieList := make([]string, 0, len(list))
637 | for _, item := range list {
638 | if str, ok := item.(string); ok {
639 | cookieList = append(cookieList, str)
640 | } else {
641 | log.Printf("警告: GrokCookies 列表中包含非字符串元素: %v", item)
642 | }
643 | }
644 | if len(cookieList) > 0 {
645 | cookieIndex = getCookieIndex(cookieList, body.CookieIndex)
646 | cookie = cookieList[cookieIndex]
647 | }
648 | }
649 | }
650 | }
651 | cookie = strings.TrimSpace(cookie)
652 | if cookie == "" && len(grokCookies) > 0 {
653 | cookieIndex = getCookieIndex(grokCookies, body.CookieIndex)
654 | cookie = grokCookies[cookieIndex]
655 | }
656 | cookie = strings.TrimSpace(cookie)
657 | if cookie == "" {
658 | log.Println("错误: 无 Grok 3 cookie")
659 | http.Error(w, "错误: 无 Grok 3 cookie", http.StatusBadRequest)
660 | return
661 | }
662 |
663 | var beforePromptText, afterPromptText string
664 | if body.TextBeforePrompt != "" {
665 | beforePromptText = body.TextBeforePrompt
666 | } else {
667 | beforePromptText = *textBeforePrompt
668 | }
669 | if body.TextAfterPrompt != "" {
670 | afterPromptText = body.TextAfterPrompt
671 | } else {
672 | afterPromptText = *textAfterPrompt
673 | }
674 |
675 | var messageBuilder strings.Builder
676 | fmt.Fprintln(&messageBuilder, beforePromptText)
677 | for _, msg := range body.Messages {
678 | fmt.Fprintf(&messageBuilder, "\n[[%s]]\n", msg.Role)
679 | if content, ok := msg.Content.(string); ok {
680 | messageBuilder.WriteString(content)
681 | } else if messages, ok := msg.Content.([]any); ok && msg.Role == "user" {
682 | for _, message := range messages {
683 | if text, ok := message.(map[string]any); ok {
684 | messageType := text["type"]
685 | if ty, ok := messageType.(string); ok && ty == "text" {
686 | if t, ok := text["text"].(string); ok {
687 | fmt.Fprintln(&messageBuilder, t)
688 | } else {
689 | http.Error(w, "错误请求: 不支持的消息类型", http.StatusBadRequest)
690 | return
691 | }
692 | } else {
693 | http.Error(w, "错误请求: 不支持的消息类型", http.StatusBadRequest)
694 | return
695 | }
696 | } else {
697 | http.Error(w, "错误请求: 不支持的消息类型", http.StatusBadRequest)
698 | return
699 | }
700 | }
701 | } else {
702 | http.Error(w, "错误请求: 不支持的消息类型", http.StatusBadRequest)
703 | return
704 | }
705 | }
706 | fmt.Fprintf(&messageBuilder, "\n%s", afterPromptText)
707 |
708 | isReasoning := strings.TrimSpace(body.Model) == grok3ReasoningModelName
709 | enableSearch := body.EnableSearch > 0
710 | uploadMessage := body.UploadMessage > 0
711 | keepConversation := *keepChat
712 | if body.KeepChat > 0 {
713 | keepConversation = true
714 | } else if body.KeepChat == 0 {
715 | keepConversation = false
716 | }
717 | ignoreThink := *ignoreThinking
718 | if body.IgnoreThinking > 0 {
719 | ignoreThink = true
720 | } else if body.IgnoreThinking == 0 {
721 | ignoreThink = false
722 | }
723 |
724 | grokClient := NewGrokClient(cookie, isReasoning, enableSearch, uploadMessage, keepConversation, ignoreThink, *longTxt)
725 | log.Printf("使用索引 %d 的 cookie 请求 Grok 3 Web API", cookieIndex+1)
726 |
727 | respReader, err := grokClient.sendMessage(messageBuilder.String(), body.Stream)
728 | if err != nil {
729 | cookieStatus.Lock()
730 | cookieStatus.status[cookie] = false
731 | log.Printf("Cookie %d 报错,已标记为失效,原因: %v", cookieIndex+1, err)
732 | cookieStatus.Unlock()
733 |
734 | cookieIndex = getCookieIndex(grokCookies, cookieIndex+1)
735 | cookie = grokCookies[cookieIndex]
736 | grokClient = NewGrokClient(cookie, isReasoning, enableSearch, uploadMessage, keepConversation, ignoreThink, *longTxt)
737 | log.Printf("切换到索引 %d 的 cookie 重试", cookieIndex+1)
738 |
739 | respReader, err = grokClient.sendMessage(messageBuilder.String(), body.Stream)
740 | if err != nil {
741 | log.Printf("重试失败: %v", err)
742 | http.Error(w, fmt.Sprintf("错误: %v", err), http.StatusInternalServerError)
743 | return
744 | }
745 | }
746 | defer respReader.Close()
747 |
748 | if body.Stream {
749 | grokClient.createOpenAIStreamingResponse(respReader)(w, r)
750 | } else {
751 | grokClient.createOpenAIFullResponse(respReader)(w, r)
752 | }
753 | }
754 |
755 | // listModels 处理 /v1/models 的 GET 请求。
756 | func listModels(w http.ResponseWriter, r *http.Request) {
757 | log.Printf("来自 %s 的请求,路径: %s", r.RemoteAddr, listModelsPath)
758 |
759 | if r.URL.Path != listModelsPath || r.Method != http.MethodGet {
760 | log.Printf("无效请求: 方法 %s, 路径 %s", r.Method, r.URL.Path)
761 | http.Error(w, "方法不允许或路径未找到", http.StatusNotFound)
762 | return
763 | }
764 |
765 | list := ModelList{
766 | Object: "list",
767 | Data: []ModelData{
768 | {Id: grok3ModelName, Object: "model", Owned_by: "xAI"},
769 | {Id: grok3ReasoningModelName, Object: "model", Owned_by: "xAI"},
770 | },
771 | }
772 |
773 | w.Header().Set("Content-Type", "application/json")
774 | if err := json.NewEncoder(w).Encode(list); err != nil {
775 | log.Printf("编码响应错误: %v", err)
776 | http.Error(w, fmt.Sprintf("编码响应错误: %v", err), http.StatusInternalServerError)
777 | }
778 | }
779 |
780 | // main 解析命令行标志并启动服务器。
781 | func main() {
782 | apiToken = flag.String("token", "", "认证令牌 (GROK3_AUTH_TOKEN)")
783 | cookie = flag.String("cookie", "", "Grok cookie (GROK3_COOKIE)")
784 | cookiesDir = flag.String("cookiesDir", "cookies", "包含 cookie.txt 文件的目录")
785 | textBeforePrompt = flag.String("textBeforePrompt", defaultBeforePromptText, "提示前缀文本")
786 | textAfterPrompt = flag.String("textAfterPrompt", "", "提示后缀文本")
787 | keepChat = flag.Bool("keepChat", false, "保留聊天会话")
788 | ignoreThinking = flag.Bool("ignoreThinking", false, "忽略思考内容")
789 | charsLimit = flag.Uint("charsLimit", messageCharsLimit, "如果消息字符数超过此限制,则将消息上传为文件")
790 | longTxt = flag.Bool("longtxt", false, "启用长文本处理,后面可接阈值(如 -longtxt 60000),默认 40000")
791 | httpProxy = flag.String("httpProxy", "", "HTTP/SOCKS5 代理")
792 | httpProxyLower := flag.String("httpproxy", "", "HTTP/SOCKS5 代理 (小写别名)")
793 | port = flag.Uint("port", 8180, "服务器端口")
794 | flag.Parse()
795 |
796 | // 如果使用了小写形式的代理参数,则将其值赋给大写形式的参数
797 | if *httpProxyLower != "" {
798 | *httpProxy = *httpProxyLower
799 | }
800 |
801 | if *port > 65535 {
802 | log.Fatalf("服务器端口 %d 超过 65535", *port)
803 | }
804 |
805 | // 自定义解析 -longtxt 后面的阈值
806 | longTxtThreshold = 40000 // 默认阈值
807 | if *longTxt {
808 | // 检查命令行参数中 -longtxt 后的值
809 | for i, arg := range os.Args {
810 | if arg == "-longtxt" && i+1 < len(os.Args) {
811 | if threshold, err := strconv.Atoi(os.Args[i+1]); err == nil && threshold > 0 {
812 | longTxtThreshold = threshold
813 | break
814 | }
815 | }
816 | }
817 | }
818 |
819 | *apiToken = strings.TrimSpace(*apiToken)
820 | if *apiToken == "" {
821 | *apiToken = os.Getenv("GROK3_AUTH_TOKEN")
822 | if *apiToken == "" {
823 | log.Fatal("认证令牌 (GROK3_AUTH_TOKEN) 未设置")
824 | }
825 | }
826 |
827 | *cookie = strings.TrimSpace(*cookie)
828 | if *cookie == "" {
829 | *cookie = strings.TrimSpace(os.Getenv("GROK3_COOKIE"))
830 | }
831 | if *cookie != "" {
832 | // 先尝试解析为 JSON
833 | err := json.Unmarshal([]byte(*cookie), &grokCookies)
834 | if err != nil {
835 | // 如果不是 JSON,尝试按逗号分割
836 | if strings.Contains(*cookie, ",") {
837 | cookieList := strings.Split(*cookie, ",")
838 | grokCookies = make([]string, 0, len(cookieList))
839 | for _, c := range cookieList {
840 | c = strings.TrimSpace(c)
841 | if c != "" {
842 | grokCookies = append(grokCookies, c)
843 | }
844 | }
845 | } else {
846 | // 单个 cookie
847 | grokCookies = []string{*cookie}
848 | }
849 | }
850 | }
851 |
852 | // 如果未提供 cookie,则从 cookiesDir 加载
853 | if len(grokCookies) == 0 {
854 | err := loadCookiesFromDir(*cookiesDir)
855 | if err != nil {
856 | log.Printf("警告: 从目录 %s 加载 cookie 失败: %v", *cookiesDir, err)
857 | }
858 | if len(grokCookies) == 0 {
859 | log.Fatal("未找到有效 cookie")
860 | }
861 | }
862 |
863 | // 初始化 cookieStatus
864 | for _, ck := range grokCookies {
865 | cookieStatus.Lock()
866 | cookieStatus.status[ck] = true
867 | cookieStatus.Unlock()
868 | }
869 |
870 | *httpProxy = strings.TrimSpace(*httpProxy)
871 | // 配置全局 httpClient
872 | if *httpProxy != "" {
873 | proxyURL, err := url.Parse(*httpProxy)
874 | if err != nil {
875 | log.Fatalf("解析 HTTP/SOCKS5 代理错误: %v", err)
876 | }
877 | httpClient.Transport = &http.Transport{
878 | Proxy: http.ProxyURL(proxyURL),
879 | DialContext: (&net.Dialer{
880 | Timeout: 30 * time.Second,
881 | KeepAlive: 30 * time.Second,
882 | }).DialContext,
883 | ForceAttemptHTTP2: true,
884 | MaxIdleConns: 10,
885 | IdleConnTimeout: 600 * time.Second,
886 | TLSHandshakeTimeout: 20 * time.Second,
887 | }
888 | } else {
889 | // 支持系统代理
890 | httpClient.Transport = &http.Transport{
891 | Proxy: http.ProxyFromEnvironment,
892 | DialContext: (&net.Dialer{
893 | Timeout: 30 * time.Second,
894 | KeepAlive: 30 * time.Second,
895 | }).DialContext,
896 | ForceAttemptHTTP2: true,
897 | MaxIdleConns: 10,
898 | IdleConnTimeout: 600 * time.Second,
899 | TLSHandshakeTimeout: 20 * time.Second,
900 | }
901 | }
902 |
903 | http.HandleFunc(completionsPath, handleChatCompletion)
904 | http.HandleFunc(listModelsPath, listModels)
905 | log.Printf("服务器启动于 :%d,长文本处理: %v,阈值: %d,已加载 cookie 数量: %d", *port, *longTxt, longTxtThreshold, len(grokCookies))
906 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
907 | }
908 |
--------------------------------------------------------------------------------
/cookies/把含有cookie的txt放在这里:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/cookies/把含有cookie的txt放在这里
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/orzogc/grok3_api
2 |
3 | go 1.24.0
4 |
5 | require github.com/google/uuid v1.6.0
6 |
7 | require github.com/andybalholm/brotli v1.1.1
8 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
2 | github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
3 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
4 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
5 |
--------------------------------------------------------------------------------
/grok3_api_arm64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/grok3_api_arm64
--------------------------------------------------------------------------------
/一键编译.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo "========== 开始编译 Grok3 API ==========="
4 | echo "正在编译Linux AMD64测试版..."
5 | export GOOS=linux
6 | export GOARCH=amd64
7 | go build -o grok3_api app-test.go
8 |
9 | echo "正在编译Linux AMD64稳定版..."
10 | export GOOS=linux
11 | export GOARCH=amd64
12 | go build -o 稳定版/grok3_api_stable 稳定版/app.go
13 |
14 | echo "正在编译Linux ARM64测试版..."
15 | export GOOS=linux
16 | export GOARCH=arm64
17 | go build -o grok3_api_arm64 app-test.go
18 |
19 | echo "正在编译Linux ARM64稳定版..."
20 | export GOOS=linux
21 | export GOARCH=arm64
22 | go build -o 稳定版/grok3_api_stable_arm64 稳定版/app.go
23 |
24 | echo "========== 编译完成 ==========="
25 | echo "Linux AMD64测试版已编译为: grok3_api"
26 | echo "Linux AMD64稳定版已编译为: 稳定版/grok3_api_stable"
27 | echo "Linux ARM64测试版已编译为: grok3_api_arm64"
28 | echo "Linux ARM64稳定版已编译为: 稳定版/grok3_api_stable_arm64"
29 | echo
--------------------------------------------------------------------------------
/一键编译Mac.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo "========== 开始编译 Grok3 API =========="
4 | echo "正在编译macOS测试版..."
5 | export GOOS=darwin
6 | export GOARCH=amd64
7 | go build -o grok3_api_darwin_amd64 app-test.go
8 |
9 | echo "正在编译macOS ARM64测试版(适用于M系列芯片)..."
10 | export GOOS=darwin
11 | export GOARCH=arm64
12 | go build -o grok3_api_darwin_arm64 app-test.go
13 |
14 | echo "正在编译macOS稳定版..."
15 | export GOOS=darwin
16 | export GOARCH=amd64
17 | go build -o 稳定版/grok3_api_stable_darwin_amd64 稳定版/app.go
18 |
19 | echo "========== 编译完成 =========="
20 | echo "macOS AMD64测试版已编译为: grok3_api_darwin_amd64"
21 | echo "macOS ARM64测试版已编译为: grok3_api_darwin_arm64"
22 | echo "macOS稳定版已编译为: 稳定版/grok3_api_stable_darwin_amd64"
23 | echo
--------------------------------------------------------------------------------
/一键编译Windows.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | chcp 65001 >nul
3 |
4 | echo ========== 开始编译 Grok3 API ==========
5 | echo 正在编译Windows测试版...
6 | go build -o app-test.exe app-test.go
7 |
8 | echo 正在编译Windows稳定版...
9 | go build -o 稳定版\app.exe 稳定版\app.go
10 |
11 | echo 正在交叉编译Linux AMD64测试版...
12 | set GOOS=linux
13 | set GOARCH=amd64
14 | go build -o grok3_api app-test.go
15 | set GOOS=windows
16 | set GOARCH=amd64
17 |
18 | echo ========== 编译完成 ==========
19 | echo Windows测试版已编译为: app-test.exe
20 | echo Windows稳定版已编译为: 稳定版\app.exe
21 | echo Linux AMD64测试版已编译为: grok3_api
22 | echo.
23 | pause
--------------------------------------------------------------------------------
/测试版启动器.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | chcp 65001 >nul
3 |
4 | echo. ========== Grok3 API 启动 ==========
5 | "%~dp0app-test.exe" -token 123456 -longtxt 40000
6 |
--------------------------------------------------------------------------------
/稳定版/app-test.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/稳定版/app-test.exe
--------------------------------------------------------------------------------
/稳定版/app-test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/base64"
6 | "encoding/json"
7 | "flag"
8 | "fmt"
9 | "io"
10 | "log"
11 | "net"
12 | "net/http"
13 | "net/url"
14 | "os"
15 | "path/filepath"
16 | "strings"
17 | "sync"
18 | "time"
19 | "unicode/utf8"
20 |
21 | "github.com/google/uuid"
22 | )
23 |
24 | // GrokClient 定义了与 Grok 3 Web API 交互的客户端。
25 | type GrokClient struct {
26 | headers map[string]string // HTTP 请求头
27 | isReasoning bool // 是否使用推理模型
28 | enableSearch bool // 是否启用网络搜索
29 | uploadMessage bool // 是否将消息上传为文件
30 | keepChat bool // 是否保留聊天历史
31 | ignoreThinking bool // 是否忽略思考令牌
32 | }
33 |
34 | // NewGrokClient 创建一个新的 GrokClient 实例。
35 | func NewGrokClient(cookie string, isReasoning, enableSearch, uploadMessage, keepChat, ignoreThinking bool) *GrokClient {
36 | return &GrokClient{
37 | headers: map[string]string{
38 | "accept": "*/*",
39 | "accept-language": "en-GB,en;q=0.9",
40 | "content-type": "application/json",
41 | "origin": "https://grok.com",
42 | "priority": "u=1, i",
43 | "referer": "https://grok.com/",
44 | "sec-ch-ua": `"Not/A)Brand";v="8", "Chromium";v="126", "Brave";v="126"`,
45 | "sec-ch-ua-mobile": "?0",
46 | "sec-ch-ua-platform": `"macOS"`,
47 | "sec-fetch-dest": "empty",
48 | "sec-fetch-mode": "cors",
49 | "sec-fetch-site": "same-origin",
50 | "sec-gpc": "1",
51 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
52 | "cookie": cookie,
53 | },
54 | isReasoning: isReasoning,
55 | enableSearch: enableSearch,
56 | uploadMessage: uploadMessage,
57 | keepChat: keepChat,
58 | ignoreThinking: ignoreThinking,
59 | }
60 | }
61 |
62 | // ToolOverrides 定义工具覆盖选项。
63 | type ToolOverrides struct {
64 | ImageGen bool `json:"imageGen"`
65 | TrendsSearch bool `json:"trendsSearch"`
66 | WebSearch bool `json:"webSearch"`
67 | XMediaSearch bool `json:"xMediaSearch"`
68 | XPostAnalyze bool `json:"xPostAnalyze"`
69 | XSearch bool `json:"xSearch"`
70 | }
71 |
72 | // preparePayload 构造 Grok 3 Web API 的请求负载。
73 | func (c *GrokClient) preparePayload(message string, fileId string) map[string]any {
74 | var toolOverrides any = ToolOverrides{}
75 | if c.enableSearch {
76 | toolOverrides = map[string]any{}
77 | }
78 |
79 | fileAttachments := []string{}
80 | if fileId != "" {
81 | fileAttachments = []string{fileId}
82 | }
83 |
84 | return map[string]any{
85 | "deepsearchPreset": "",
86 | "disableSearch": false,
87 | "enableImageGeneration": true,
88 | "enableImageStreaming": true,
89 | "enableSideBySide": true,
90 | "fileAttachments": fileAttachments,
91 | "forceConcise": false,
92 | "imageAttachments": []string{},
93 | "imageGenerationCount": 2,
94 | "isPreset": false,
95 | "isReasoning": c.isReasoning,
96 | "message": message,
97 | "modelName": "grok-3",
98 | "returnImageBytes": false,
99 | "returnRawGrokInXaiRequest": false,
100 | "sendFinalMetadata": true,
101 | "temporary": !c.keepChat,
102 | "toolOverrides": toolOverrides,
103 | "webpageUrls": []string{},
104 | }
105 | }
106 |
107 | // getModelName 根据 isReasoning 标志返回模型名称。
108 | func (c *GrokClient) getModelName() string {
109 | if c.isReasoning {
110 | return grok3ReasoningModelName
111 | }
112 | return grok3ModelName
113 | }
114 |
115 | // RequestBody 表示 /v1/chat/completions 的 POST 请求 JSON 结构体。
116 | type RequestBody struct {
117 | Model string `json:"model"`
118 | Messages []struct {
119 | Role string `json:"role"`
120 | Content string `json:"content"`
121 | } `json:"messages"`
122 | Stream bool `json:"stream"`
123 | GrokCookies any `json:"grokCookies,omitempty"`
124 | CookieIndex uint `json:"cookieIndex,omitempty"`
125 | EnableSearch int `json:"enableSearch,omitempty"`
126 | UploadMessage int `json:"uploadMessage,omitempty"`
127 | TextBeforePrompt string `json:"textBeforePrompt,omitempty"`
128 | TextAfterPrompt string `json:"textAfterPrompt,omitempty"`
129 | KeepChat int `json:"keepChat,omitempty"`
130 | IgnoreThinking int `json:"ignoreThinking,omitempty"`
131 | }
132 |
133 | // ResponseToken 表示 Grok 3 Web API 的单个令牌响应。
134 | type ResponseToken struct {
135 | Result struct {
136 | Response struct {
137 | Token string `json:"token"`
138 | IsThinking bool `json:"isThinking"`
139 | } `json:"response"`
140 | } `json:"result"`
141 | }
142 |
143 | // ModelData 表示 OpenAI 兼容响应的模型元数据。
144 | type ModelData struct {
145 | Id string `json:"id"`
146 | Object string `json:"object"`
147 | Owned_by string `json:"owned_by"`
148 | }
149 |
150 | // ModelList 包含 OpenAI 兼容端点的可用模型。
151 | type ModelList struct {
152 | Object string `json:"object"`
153 | Data []ModelData `json:"data"`
154 | }
155 |
156 | // UploadFileRequest 表示上传文件的请求结构体。
157 | type UploadFileRequest struct {
158 | Content string `json:"content"`
159 | FileMimeType string `json:"fileMimeType"`
160 | FileName string `json:"fileName"`
161 | }
162 |
163 | // UploadFileResponse 表示上传文件的响应结构体。
164 | type UploadFileResponse struct {
165 | FileMetadataId string `json:"fileMetadataId"`
166 | }
167 |
168 | const (
169 | newChatUrl = "https://grok.com/rest/app-chat/conversations/new"
170 | uploadFileUrl = "https://grok.com/rest/app-chat/upload-file"
171 | grok3ModelName = "grok-3"
172 | grok3ReasoningModelName = "grok-3-reasoning"
173 | completionsPath = "/v1/chat/completions"
174 | listModelsPath = "/v1/models"
175 | messageCharLimit = 80000
176 | defaultBeforePromptText = "For the data below, entries with 'system' are system information, entries with 'assistant' are messages you have previously sent, entries with 'user' are messages sent by the user. You need to respond to the user's last message accordingly based on the corresponding data."
177 | )
178 |
179 | // 全局配置变量
180 | var (
181 | apiToken *string
182 | grokCookies []string
183 | textBeforePrompt *string
184 | textAfterPrompt *string
185 | keepChat *bool
186 | ignoreThinking *bool
187 | longTxt *bool
188 | httpProxy *string
189 | cookiesDir *string
190 | httpClient = &http.Client{Timeout: 30 * time.Minute}
191 | cookie *string // 修复:添加全局 cookie 变量
192 | port *uint // 修复:添加全局 port 变量
193 | nextCookieIndex = struct {
194 | sync.Mutex
195 | index uint
196 | }{}
197 | )
198 |
199 | // doRequest 发送 HTTP 请求并返回响应。
200 | func (c *GrokClient) doRequest(method, url string, payload any) (*http.Response, error) {
201 | jsonPayload, err := json.Marshal(payload)
202 | if err != nil {
203 | return nil, fmt.Errorf("序列化请求负载失败: %v", err)
204 | }
205 |
206 | req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonPayload))
207 | if err != nil {
208 | return nil, fmt.Errorf("创建请求失败: %v", err)
209 | }
210 |
211 | for key, value := range c.headers {
212 | req.Header.Set(key, value)
213 | }
214 |
215 | resp, err := httpClient.Do(req)
216 | if err != nil {
217 | return nil, fmt.Errorf("发送请求失败: %v", err)
218 | }
219 | if resp.StatusCode != http.StatusOK {
220 | defer resp.Body.Close()
221 | body, _ := io.ReadAll(resp.Body)
222 | return nil, fmt.Errorf("Grok API 错误: %d %s, 响应体: %s", resp.StatusCode, resp.Status, string(body))
223 | }
224 | return resp, nil
225 | }
226 |
227 | // uploadMessageAsFile 将消息上传为文件并返回文件 ID。
228 | func (c *GrokClient) uploadMessageAsFile(message string) (*UploadFileResponse, error) {
229 | content := base64.StdEncoding.EncodeToString([]byte(message))
230 | payload := UploadFileRequest{
231 | Content: content,
232 | FileMimeType: "text/plain",
233 | FileName: uuid.New().String() + ".txt",
234 | }
235 | log.Println("正在将消息上传为文件")
236 | resp, err := c.doRequest(http.MethodPost, uploadFileUrl, payload)
237 | if err != nil {
238 | return nil, err
239 | }
240 | defer resp.Body.Close()
241 | body, err := io.ReadAll(resp.Body)
242 | if err != nil {
243 | return nil, fmt.Errorf("上传文件错误: %d %s", resp.StatusCode, resp.Status)
244 | }
245 | response := &UploadFileResponse{}
246 | err = json.Unmarshal(body, response)
247 | if err != nil || response.FileMetadataId == "" {
248 | return nil, fmt.Errorf("解析 JSON 错误或 FileMetadataId 为空: %s", string(body))
249 | }
250 | return response, nil
251 | }
252 |
253 | // sendMessage 向 Grok 3 Web API 发送消息并返回响应体。
254 | func (c *GrokClient) sendMessage(message string, stream bool) (io.ReadCloser, error) {
255 | fileId := ""
256 | if c.uploadMessage || (len(message) > messageCharLimit && utf8.RuneCountInString(message) > messageCharLimit) {
257 | uploadResp, err := c.uploadMessageAsFile(message)
258 | if err != nil {
259 | return nil, err
260 | }
261 | fileId = uploadResp.FileMetadataId
262 | message = "请按照附件中的说明进行回复。"
263 | }
264 |
265 | payload := c.preparePayload(message, fileId)
266 | resp, err := c.doRequest(http.MethodPost, newChatUrl, payload)
267 | if err != nil {
268 | return nil, err
269 | }
270 |
271 | if stream {
272 | return resp.Body, nil
273 | }
274 | defer resp.Body.Close()
275 | body, err := io.ReadAll(resp.Body)
276 | if err != nil {
277 | return nil, fmt.Errorf("读取响应体失败: %v", err)
278 | }
279 | return io.NopCloser(bytes.NewReader(body)), nil
280 | }
281 |
282 | // parseGrok3StreamingJson 解析 Grok 3 的流式响应。
283 | func (c *GrokClient) parseGrok3StreamingJson(stream io.Reader, handler func(respToken string)) {
284 | isThinking := false
285 | decoder := json.NewDecoder(stream)
286 | for {
287 | var token ResponseToken
288 | err := decoder.Decode(&token)
289 | if err == io.EOF {
290 | break
291 | } else if err != nil {
292 | log.Printf("解析 JSON 错误: %v", err)
293 | break
294 | }
295 |
296 | respToken := token.Result.Response.Token
297 | if c.ignoreThinking && token.Result.Response.IsThinking {
298 | continue
299 | } else if token.Result.Response.IsThinking {
300 | if !isThinking {
301 | respToken = "\n" + respToken
302 | }
303 | isThinking = true
304 | } else if isThinking {
305 | respToken = respToken + "\n\n\n"
306 | isThinking = false
307 | }
308 |
309 | if respToken != "" {
310 | handler(respToken)
311 | }
312 | }
313 | }
314 |
315 | // OpenAIChatCompletionMessage 定义 OpenAI 响应的消息结构。
316 | type OpenAIChatCompletionMessage struct {
317 | Role string `json:"role"`
318 | Content string `json:"content"`
319 | }
320 |
321 | // OpenAIChatCompletionChunkChoice 定义流式响应中的选择结构。
322 | type OpenAIChatCompletionChunkChoice struct {
323 | Index int `json:"index"`
324 | Delta OpenAIChatCompletionMessage `json:"delta"`
325 | FinishReason string `json:"finish_reason"`
326 | }
327 |
328 | // OpenAIChatCompletionChunk 表示 OpenAI 的流式响应格式。
329 | type OpenAIChatCompletionChunk struct {
330 | ID string `json:"id"`
331 | Object string `json:"object"`
332 | Created int64 `json:"created"`
333 | Model string `json:"model"`
334 | Choices []OpenAIChatCompletionChunkChoice `json:"choices"`
335 | }
336 |
337 | // OpenAIChatCompletionChoice 定义完整响应中的选择结构。
338 | type OpenAIChatCompletionChoice struct {
339 | Index int `json:"index"`
340 | Message OpenAIChatCompletionMessage `json:"message"`
341 | FinishReason string `json:"finish_reason"`
342 | }
343 |
344 | // OpenAIChatCompletionUsage 跟踪令牌使用情况。
345 | type OpenAIChatCompletionUsage struct {
346 | PromptTokens int `json:"prompt_tokens"`
347 | CompletionTokens int `json:"completion_tokens"`
348 | TotalTokens int `json:"total_tokens"`
349 | }
350 |
351 | // OpenAIChatCompletion 表示 OpenAI 的非流式响应格式。
352 | type OpenAIChatCompletion struct {
353 | ID string `json:"id"`
354 | Object string `json:"object"`
355 | Created int64 `json:"created"`
356 | Model string `json:"model"`
357 | Choices []OpenAIChatCompletionChoice `json:"choices"`
358 | Usage OpenAIChatCompletionUsage `json:"usage"`
359 | }
360 |
361 | // createOpenAIStreamingResponse 返回流式响应处理函数。
362 | func (c *GrokClient) createOpenAIStreamingResponse(grokStream io.Reader) http.HandlerFunc {
363 | return func(w http.ResponseWriter, r *http.Request) {
364 | w.Header().Set("Content-Type", "text/event-stream")
365 | w.Header().Set("Cache-Control", "no-cache")
366 | w.Header().Set("Connection", "keep-alive")
367 |
368 | flusher, ok := w.(http.Flusher)
369 | if !ok {
370 | log.Println("流式传输不支持")
371 | http.Error(w, "流式传输不支持", http.StatusInternalServerError)
372 | return
373 | }
374 |
375 | completionID := "chatcmpl-" + uuid.New().String()
376 | startChunk := OpenAIChatCompletionChunk{
377 | ID: completionID,
378 | Object: "chat.completion.chunk",
379 | Created: time.Now().Unix(),
380 | Model: c.getModelName(),
381 | Choices: []OpenAIChatCompletionChunkChoice{
382 | {Index: 0, Delta: OpenAIChatCompletionMessage{Role: "assistant"}, FinishReason: ""},
383 | },
384 | }
385 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(startChunk))
386 | flusher.Flush()
387 |
388 | c.parseGrok3StreamingJson(grokStream, func(respToken string) {
389 | chunk := OpenAIChatCompletionChunk{
390 | ID: completionID,
391 | Object: "chat.completion.chunk",
392 | Created: time.Now().Unix(),
393 | Model: c.getModelName(),
394 | Choices: []OpenAIChatCompletionChunkChoice{
395 | {Index: 0, Delta: OpenAIChatCompletionMessage{Content: respToken}, FinishReason: ""},
396 | },
397 | }
398 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(chunk))
399 | flusher.Flush()
400 | })
401 |
402 | finalChunk := OpenAIChatCompletionChunk{
403 | ID: completionID,
404 | Object: "chat.completion.chunk",
405 | Created: time.Now().Unix(),
406 | Model: c.getModelName(),
407 | Choices: []OpenAIChatCompletionChunkChoice{
408 | {Index: 0, Delta: OpenAIChatCompletionMessage{}, FinishReason: "stop"},
409 | },
410 | }
411 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(finalChunk))
412 | flusher.Flush()
413 |
414 | fmt.Fprintf(w, "data: [DONE]\n\n")
415 | flusher.Flush()
416 | }
417 | }
418 |
419 | // createOpenAIFullResponse 返回完整响应处理函数。
420 | func (c *GrokClient) createOpenAIFullResponse(grokFull io.Reader) http.HandlerFunc {
421 | return func(w http.ResponseWriter, r *http.Request) {
422 | var fullResponse strings.Builder
423 | c.parseGrok3StreamingJson(grokFull, func(respToken string) {
424 | fullResponse.WriteString(respToken)
425 | })
426 |
427 | openAIResponse := c.createOpenAIFullResponseBody(fullResponse.String())
428 | w.Header().Set("Content-Type", "application/json")
429 | if err := json.NewEncoder(w).Encode(openAIResponse); err != nil {
430 | log.Printf("编码响应错误: %v", err)
431 | http.Error(w, fmt.Sprintf("编码响应错误: %v", err), http.StatusInternalServerError)
432 | }
433 | }
434 | }
435 |
436 | // createOpenAIFullResponseBody 创建非流式请求的 OpenAI 响应体。
437 | func (c *GrokClient) createOpenAIFullResponseBody(content string) OpenAIChatCompletion {
438 | return OpenAIChatCompletion{
439 | ID: "chatcmpl-" + uuid.New().String(),
440 | Object: "chat.completion",
441 | Created: time.Now().Unix(),
442 | Model: c.getModelName(),
443 | Choices: []OpenAIChatCompletionChoice{
444 | {
445 | Index: 0,
446 | Message: OpenAIChatCompletionMessage{Role: "assistant", Content: content},
447 | FinishReason: "stop",
448 | },
449 | },
450 | Usage: OpenAIChatCompletionUsage{PromptTokens: -1, CompletionTokens: -1, TotalTokens: -1},
451 | }
452 | }
453 |
454 | // mustMarshal 将值序列化为 JSON 字符串。
455 | func mustMarshal(v any) string {
456 | b, err := json.Marshal(v)
457 | if err != nil {
458 | panic(err)
459 | }
460 | return string(b)
461 | }
462 |
463 | // getCookieIndex 以轮询方式选择下一个 cookie 索引。
464 | func getCookieIndex(len int, cookieIndex uint) uint {
465 | if cookieIndex == 0 || cookieIndex > uint(len) {
466 | nextCookieIndex.Lock()
467 | defer nextCookieIndex.Unlock()
468 | index := nextCookieIndex.index
469 | nextCookieIndex.index = (nextCookieIndex.index + 1) % uint(len)
470 | return index % uint(len)
471 | }
472 | return cookieIndex - 1
473 | }
474 |
475 | // loadCookiesFromDir 从指定目录加载 cookies。
476 | func loadCookiesFromDir(dir string) error {
477 | if _, err := os.Stat(dir); os.IsNotExist(err) {
478 | return fmt.Errorf("cookie 目录不存在: %s", dir)
479 | }
480 |
481 | files, err := os.ReadDir(dir)
482 | if err != nil {
483 | return fmt.Errorf("读取目录 %s 失败: %v", dir, err)
484 | }
485 |
486 | grokCookies = []string{}
487 | for _, file := range files {
488 | if !file.IsDir() && strings.HasSuffix(file.Name(), ".txt") {
489 | filePath := filepath.Join(dir, file.Name())
490 | content, err := os.ReadFile(filePath)
491 | if err != nil {
492 | log.Printf("警告: 读取 cookie 文件 %s 失败: %v", filePath, err)
493 | continue
494 | }
495 | cookie := strings.TrimSpace(string(content))
496 | if cookie != "" {
497 | grokCookies = append(grokCookies, cookie)
498 | log.Printf("从 %s 加载 cookie", filePath)
499 | }
500 | }
501 | }
502 | return nil
503 | }
504 |
505 | // handleChatCompletion 处理 /v1/chat/completions 的 POST 请求。
506 | func handleChatCompletion(w http.ResponseWriter, r *http.Request) {
507 | log.Printf("来自 %s 的请求,路径: %s", r.RemoteAddr, completionsPath)
508 |
509 | if r.URL.Path != completionsPath || r.Method != http.MethodPost {
510 | log.Printf("无效请求: 方法 %s, 路径 %s", r.Method, r.URL.Path)
511 | http.Error(w, "方法不允许或路径未找到", http.StatusMethodNotAllowed)
512 | return
513 | }
514 |
515 | authHeader := r.Header.Get("Authorization")
516 | if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
517 | log.Println("未授权: 需要 Bearer 令牌")
518 | http.Error(w, "未授权: 需要 Bearer 令牌", http.StatusUnauthorized)
519 | return
520 | }
521 |
522 | token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
523 | if token != *apiToken {
524 | log.Println("未授权: 无效令牌")
525 | http.Error(w, "未授权: 无效令牌", http.StatusUnauthorized)
526 | return
527 | }
528 |
529 | var body RequestBody
530 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
531 | log.Println("错误请求: 无效 JSON")
532 | http.Error(w, "错误请求: 无效 JSON", http.StatusBadRequest)
533 | return
534 | }
535 |
536 | if len(body.Messages) == 0 {
537 | log.Println("错误请求: 未提供消息")
538 | http.Error(w, "错误请求: 未提供消息", http.StatusBadRequest)
539 | return
540 | }
541 |
542 | var cookie string
543 | var cookieIndex uint
544 | if body.GrokCookies != nil {
545 | if ck, ok := body.GrokCookies.(string); ok {
546 | cookie = ck
547 | } else if list, ok := body.GrokCookies.([]any); ok {
548 | if len(list) > 0 {
549 | cookieIndex = getCookieIndex(len(list), body.CookieIndex)
550 | if ck, ok := list[cookieIndex].(string); ok {
551 | cookie = ck
552 | }
553 | }
554 | }
555 | }
556 | cookie = strings.TrimSpace(cookie)
557 | if cookie == "" && len(grokCookies) > 0 {
558 | cookieIndex = getCookieIndex(len(grokCookies), body.CookieIndex)
559 | cookie = grokCookies[cookieIndex]
560 | }
561 | cookie = strings.TrimSpace(cookie)
562 | if cookie == "" {
563 | log.Println("错误: 无 Grok 3 cookie")
564 | http.Error(w, "错误: 无 Grok 3 cookie", http.StatusBadRequest)
565 | return
566 | }
567 |
568 | var beforePromptText, afterPromptText string
569 | if body.TextBeforePrompt != "" {
570 | beforePromptText = body.TextBeforePrompt
571 | } else {
572 | beforePromptText = *textBeforePrompt
573 | }
574 | if body.TextAfterPrompt != "" {
575 | afterPromptText = body.TextAfterPrompt
576 | } else {
577 | afterPromptText = *textAfterPrompt
578 | }
579 |
580 | var messageBuilder strings.Builder
581 | fmt.Fprintln(&messageBuilder, beforePromptText)
582 | for _, msg := range body.Messages {
583 | fmt.Fprintf(&messageBuilder, "\n[[%s]]\n", msg.Role)
584 | messageBuilder.WriteString(msg.Content)
585 | }
586 | fmt.Fprintf(&messageBuilder, "\n%s", afterPromptText)
587 |
588 | isReasoning := strings.TrimSpace(body.Model) == grok3ReasoningModelName
589 | enableSearch := body.EnableSearch > 0
590 | uploadMessage := body.UploadMessage > 0
591 | keepConversation := *keepChat
592 | if body.KeepChat > 0 {
593 | keepConversation = true
594 | } else if body.KeepChat == 0 {
595 | keepConversation = false
596 | }
597 | ignoreThink := *ignoreThinking
598 | if body.IgnoreThinking > 0 {
599 | ignoreThink = true
600 | } else if body.IgnoreThinking == 0 {
601 | ignoreThink = false
602 | }
603 |
604 | grokClient := NewGrokClient(cookie, isReasoning, enableSearch, uploadMessage, keepConversation, ignoreThink)
605 | log.Printf("使用索引 %d 的 cookie 请求 Grok 3 Web API", cookieIndex+1)
606 |
607 | respReader, err := grokClient.sendMessage(messageBuilder.String(), body.Stream)
608 | if err != nil {
609 | log.Printf("错误: %v", err)
610 | http.Error(w, fmt.Sprintf("错误: %v", err), http.StatusInternalServerError)
611 | return
612 | }
613 | defer respReader.Close()
614 |
615 | if body.Stream {
616 | grokClient.createOpenAIStreamingResponse(respReader)(w, r)
617 | } else {
618 | grokClient.createOpenAIFullResponse(respReader)(w, r)
619 | }
620 | }
621 |
622 | // listModels 处理 /v1/models 的 GET 请求。
623 | func listModels(w http.ResponseWriter, r *http.Request) {
624 | log.Printf("来自 %s 的请求,路径: %s", r.RemoteAddr, listModelsPath)
625 |
626 | if r.URL.Path != listModelsPath || r.Method != http.MethodGet {
627 | log.Printf("无效请求: 方法 %s, 路径 %s", r.Method, r.URL.Path)
628 | http.Error(w, "方法不允许或路径未找到", http.StatusNotFound)
629 | return
630 | }
631 |
632 | list := ModelList{
633 | Object: "list",
634 | Data: []ModelData{
635 | {Id: grok3ModelName, Object: "model", Owned_by: "xAI"},
636 | {Id: grok3ReasoningModelName, Object: "model", Owned_by: "xAI"},
637 | },
638 | }
639 |
640 | w.Header().Set("Content-Type", "application/json")
641 | if err := json.NewEncoder(w).Encode(list); err != nil {
642 | log.Printf("编码响应错误: %v", err)
643 | http.Error(w, fmt.Sprintf("编码响应错误: %v", err), http.StatusInternalServerError)
644 | }
645 | }
646 |
647 | // main 解析命令行标志并启动服务器。
648 | func main() {
649 | apiToken = flag.String("token", "", "认证令牌 (GROK3_AUTH_TOKEN)")
650 | cookie = flag.String("cookie", "", "Grok cookie (GROK3_COOKIE)")
651 | cookiesDir = flag.String("cookiesDir", "cookies", "包含 cookie.txt 文件的目录")
652 | textBeforePrompt = flag.String("textBeforePrompt", defaultBeforePromptText, "提示前缀文本")
653 | textAfterPrompt = flag.String("textAfterPrompt", "", "提示后缀文本")
654 | keepChat = flag.Bool("keepChat", false, "保留聊天会话")
655 | ignoreThinking = flag.Bool("ignoreThinking", false, "忽略思考内容")
656 | longTxt = flag.Bool("longtxt", false, "启用长文本处理(仅标志,未在 sendMessage 中实现)")
657 | httpProxy = flag.String("httpProxy", "", "HTTP/SOCKS5 代理")
658 | httpProxyLower := flag.String("httpproxy", "", "HTTP/SOCKS5 代理 (小写别名)")
659 | port = flag.Uint("port", 8180, "服务器端口")
660 | flag.Parse()
661 |
662 | // 如果使用了小写形式的代理参数,则将其值赋给大写形式的参数
663 | if *httpProxyLower != "" {
664 | *httpProxy = *httpProxyLower
665 | }
666 |
667 | if *port > 65535 {
668 | log.Fatalf("服务器端口 %d 超过 65535", *port)
669 | }
670 |
671 | *apiToken = strings.TrimSpace(*apiToken)
672 | if *apiToken == "" {
673 | *apiToken = os.Getenv("GROK3_AUTH_TOKEN")
674 | if *apiToken == "" {
675 | log.Fatal("认证令牌 (GROK3_AUTH_TOKEN) 未设置")
676 | }
677 | }
678 |
679 | *cookie = strings.TrimSpace(*cookie)
680 | if *cookie == "" {
681 | *cookie = strings.TrimSpace(os.Getenv("GROK3_COOKIE"))
682 | }
683 | if *cookie != "" {
684 | err := json.Unmarshal([]byte(*cookie), &grokCookies)
685 | if err != nil {
686 | grokCookies = []string{*cookie}
687 | }
688 | }
689 |
690 | // 如果未提供 cookie,则从 cookiesDir 加载
691 | if len(grokCookies) == 0 {
692 | err := loadCookiesFromDir(*cookiesDir)
693 | if err != nil {
694 | log.Printf("警告: 从目录 %s 加载 cookie 失败: %v", *cookiesDir, err)
695 | }
696 | if len(grokCookies) == 0 {
697 | log.Fatal("未找到有效 cookie")
698 | }
699 | }
700 |
701 | *httpProxy = strings.TrimSpace(*httpProxy)
702 | // 配置全局 httpClient
703 | if *httpProxy != "" {
704 | proxyURL, err := url.Parse(*httpProxy)
705 | if err != nil {
706 | log.Fatalf("解析 HTTP/SOCKS5 代理错误: %v", err)
707 | }
708 | httpClient.Transport = &http.Transport{
709 | Proxy: http.ProxyURL(proxyURL),
710 | DialContext: (&net.Dialer{
711 | Timeout: 30 * time.Second,
712 | KeepAlive: 30 * time.Second,
713 | }).DialContext,
714 | ForceAttemptHTTP2: true,
715 | MaxIdleConns: 10,
716 | IdleConnTimeout: 600 * time.Second,
717 | TLSHandshakeTimeout: 20 * time.Second,
718 | }
719 | } else {
720 | // 支持系统代理
721 | httpClient.Transport = &http.Transport{
722 | Proxy: http.ProxyFromEnvironment,
723 | DialContext: (&net.Dialer{
724 | Timeout: 30 * time.Second,
725 | KeepAlive: 30 * time.Second,
726 | }).DialContext,
727 | ForceAttemptHTTP2: true,
728 | MaxIdleConns: 10,
729 | IdleConnTimeout: 600 * time.Second,
730 | TLSHandshakeTimeout: 20 * time.Second,
731 | }
732 | }
733 |
734 | http.HandleFunc(completionsPath, handleChatCompletion)
735 | http.HandleFunc(listModelsPath, listModels)
736 | log.Printf("服务器启动于 :%d,长文本处理: %v,已加载 cookie 数量: %d", *port, *longTxt, len(grokCookies))
737 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
738 | }
739 |
--------------------------------------------------------------------------------
/稳定版/app.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "flag"
7 | "fmt"
8 | "io"
9 | "log"
10 | "net"
11 | "net/http"
12 | "net/url"
13 | "os"
14 | "path/filepath"
15 | "strings"
16 | "sync"
17 | "time"
18 |
19 | "github.com/google/uuid"
20 | )
21 |
22 | // GrokClient defines a client for interacting with the Grok 3 Web API.
23 | type GrokClient struct {
24 | newUrl string // Endpoint for creating new conversations
25 | headers map[string]string // HTTP headers for API requests
26 | isReasoning bool // Flag for using reasoning model
27 | enableSearch bool // Flag for searching in the Web
28 | keepChat bool // Flag to preserve chat history
29 | ignoreThinking bool // Flag to exclude thinking tokens in responses
30 | }
31 |
32 | // NewGrokClient creates a new instance of GrokClient with the provided cookies and configuration flags.
33 | func NewGrokClient(cookie string, isReasoning bool, enableSearch bool, keepChat bool, ignoreThinking bool) *GrokClient {
34 | return &GrokClient{
35 | newUrl: "https://grok.com/rest/app-chat/conversations/new",
36 | headers: map[string]string{
37 | "accept": "*/*",
38 | "accept-language": "en-GB,en;q=0.9",
39 | "content-type": "application/json",
40 | "origin": "https://grok.com",
41 | "priority": "u=1, i",
42 | "referer": "https://grok.com/",
43 | "sec-ch-ua": `"Not/A)Brand";v="8", "Chromium";v="126", "Brave";v="126"`,
44 | "sec-ch-ua-mobile": "?0",
45 | "sec-ch-ua-platform": `"macOS"`,
46 | "sec-fetch-dest": "empty",
47 | "sec-fetch-mode": "cors",
48 | "sec-fetch-site": "same-origin",
49 | "sec-gpc": "1",
50 | "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
51 | "cookie": cookie,
52 | },
53 | isReasoning: isReasoning,
54 | enableSearch: enableSearch,
55 | keepChat: keepChat,
56 | ignoreThinking: ignoreThinking,
57 | }
58 | }
59 |
60 | // ToolOverrides defines the tool overrides for the Grok 3 Web API.
61 | type ToolOverrides struct {
62 | WebSearch bool `json:"webSearch"`
63 | }
64 |
65 | // preparePayload constructs the request payload for the Grok 3 Web API.
66 | func (c *GrokClient) preparePayload(message string, fileAttachments []string) map[string]any {
67 | toolOverrides := ToolOverrides{WebSearch: c.enableSearch}
68 | return map[string]any{
69 | "message": message,
70 | "modelName": "grok-3",
71 | "isReasoning": c.isReasoning,
72 | "temporary": !c.keepChat,
73 | "fileAttachments": fileAttachments,
74 | "toolOverrides": toolOverrides,
75 | }
76 | }
77 |
78 | // getModelName returns the appropriate model name based on the isReasoning flag.
79 | func (c *GrokClient) getModelName() string {
80 | if c.isReasoning {
81 | return "grok-3-reasoning"
82 | }
83 | return "grok-3"
84 | }
85 |
86 | // RequestBody represents the structure of the JSON body for /v1/chat/completions.
87 | type RequestBody struct {
88 | Model string `json:"model"`
89 | Messages []struct {
90 | Role string `json:"role"`
91 | Content string `json:"content"`
92 | } `json:"messages"`
93 | Stream bool `json:"stream"`
94 | GrokCookies any `json:"grokCookies,omitempty"`
95 | CookieIndex uint `json:"cookieIndex,omitempty"`
96 | EnableSearch int `json:"enableSearch,omitempty"`
97 | KeepChat int `json:"keepChat,omitempty"`
98 | IgnoreThinking int `json:"ignoreThinking,omitempty"`
99 | }
100 |
101 | // ResponseToken represents a single token response from the Grok 3 Web API.
102 | type ResponseToken struct {
103 | Result struct {
104 | Response struct {
105 | Token string `json:"token"`
106 | IsThinking bool `json:"isThinking"`
107 | } `json:"response"`
108 | } `json:"result"`
109 | }
110 |
111 | // ModelData represents model metadata for OpenAI-compatible response.
112 | type ModelData struct {
113 | Id string `json:"id"`
114 | Object string `json:"object"`
115 | Owned_by string `json:"owned_by"`
116 | }
117 |
118 | // ModelList contains available models for OpenAI-compatible endpoint.
119 | type ModelList struct {
120 | Object string `json:"object"`
121 | Data []ModelData `json:"data"`
122 | }
123 |
124 | const (
125 | grok3ModelName = "grok-3"
126 | grok3ReasoningModelName = "grok-3-reasoning"
127 | completionsPath = "/v1/chat/completions"
128 | listModelsPath = "/v1/models"
129 | )
130 |
131 | // Global configuration variables.
132 | var (
133 | apiToken *string
134 | grokCookies []string
135 | keepChat *bool
136 | ignoreThinking *bool
137 | httpProxy *string
138 | cookiesDir *string
139 | longTxt *bool
140 | httpClient = &http.Client{Timeout: 30 * time.Minute}
141 | nextCookieIndex = struct {
142 | sync.Mutex
143 | index uint
144 | }{}
145 | )
146 |
147 | // sendMessage sends a message to the Grok 3 Web API and returns the response body.
148 | func (c *GrokClient) sendMessage(message string, stream bool, fileAttachments []string) (io.ReadCloser, error) {
149 | payload := c.preparePayload(message, fileAttachments)
150 | jsonPayload, err := json.Marshal(payload)
151 | if err != nil {
152 | return nil, fmt.Errorf("failed to marshal payload: %v", err)
153 | }
154 |
155 | req, err := http.NewRequest(http.MethodPost, c.newUrl, bytes.NewBuffer(jsonPayload))
156 | if err != nil {
157 | return nil, fmt.Errorf("failed to create request: %v", err)
158 | }
159 |
160 | for key, value := range c.headers {
161 | req.Header.Set(key, value)
162 | }
163 |
164 | resp, err := httpClient.Do(req)
165 | if err != nil {
166 | return nil, fmt.Errorf("failed to send request: %v", err)
167 | }
168 | if resp.StatusCode != http.StatusOK {
169 | defer resp.Body.Close()
170 | body, err := io.ReadAll(resp.Body)
171 | if err != nil {
172 | return nil, fmt.Errorf("the Grok API error: %d %s", resp.StatusCode, resp.Status)
173 | }
174 | return nil, fmt.Errorf("the Grok API error: %d %s, response body: %s", resp.StatusCode, resp.Status, string(body))
175 | }
176 |
177 | if stream {
178 | return resp.Body, nil
179 | } else {
180 | defer resp.Body.Close()
181 | body, err := io.ReadAll(resp.Body)
182 | if err != nil {
183 | return nil, fmt.Errorf("failed to read response body: %v", err)
184 | }
185 | return io.NopCloser(bytes.NewReader(body)), nil
186 | }
187 | }
188 |
189 | // OpenAIChatCompletionMessage defines the message structure for OpenAI responses.
190 | type OpenAIChatCompletionMessage struct {
191 | Role string `json:"role"`
192 | Content string `json:"content"`
193 | }
194 |
195 | // OpenAIChatCompletionChunkChoice defines a choice in a streaming chunk.
196 | type OpenAIChatCompletionChunkChoice struct {
197 | Index int `json:"index"`
198 | Delta OpenAIChatCompletionMessage `json:"delta"`
199 | FinishReason string `json:"finish_reason"`
200 | }
201 |
202 | // OpenAIChatCompletionChunk represents the streaming response format.
203 | type OpenAIChatCompletionChunk struct {
204 | ID string `json:"id"`
205 | Object string `json:"object"`
206 | Created int64 `json:"created"`
207 | Model string `json:"model"`
208 | Choices []OpenAIChatCompletionChunkChoice `json:"choices"`
209 | }
210 |
211 | // OpenAIChatCompletionChoice defines a choice in a full response.
212 | type OpenAIChatCompletionChoice struct {
213 | Index int `json:"index"`
214 | Message OpenAIChatCompletionMessage `json:"message"`
215 | FinishReason string `json:"finish_reason"`
216 | }
217 |
218 | // OpenAIChatCompletionUsage tracks token usage.
219 | type OpenAIChatCompletionUsage struct {
220 | PromptTokens int `json:"prompt_tokens"`
221 | CompletionTokens int `json:"completion_tokens"`
222 | TotalTokens int `json:"total_tokens"`
223 | }
224 |
225 | // OpenAIChatCompletion represents the non-streaming response format.
226 | type OpenAIChatCompletion struct {
227 | ID string `json:"id"`
228 | Object string `json:"object"`
229 | Created int64 `json:"created"`
230 | Model string `json:"model"`
231 | Choices []OpenAIChatCompletionChoice `json:"choices"`
232 | Usage OpenAIChatCompletionUsage `json:"usage"`
233 | }
234 |
235 | // parseGrok3StreamingJson parses the streaming response from Grok 3.
236 | func (c *GrokClient) parseGrok3StreamingJson(stream io.Reader, handler func(respToken string)) {
237 | isThinking := false
238 | decoder := json.NewDecoder(stream)
239 | for {
240 | var token ResponseToken
241 | err := decoder.Decode(&token)
242 | if err == io.EOF {
243 | break
244 | } else if err != nil {
245 | log.Printf("Parsing json error: %v", err)
246 | break
247 | }
248 |
249 | respToken := token.Result.Response.Token
250 | if c.ignoreThinking && token.Result.Response.IsThinking {
251 | continue
252 | } else if token.Result.Response.IsThinking {
253 | if !isThinking {
254 | respToken = "\n" + respToken
255 | }
256 | isThinking = true
257 | } else if isThinking {
258 | respToken = respToken + "\n\n\n"
259 | isThinking = false
260 | }
261 |
262 | if respToken != "" {
263 | handler(respToken)
264 | }
265 | }
266 | }
267 |
268 | // CreateOpenAIStreamingResponse converts Grok 3 streaming response to OpenAI format.
269 | func (c *GrokClient) CreateOpenAIStreamingResponse(grokStream io.Reader) http.HandlerFunc {
270 | return func(w http.ResponseWriter, r *http.Request) {
271 | w.Header().Set("Content-Type", "text/event-stream")
272 | w.Header().Set("Cache-Control", "no-cache")
273 | w.Header().Set("Connection", "keep-alive")
274 |
275 | flusher, ok := w.(http.Flusher)
276 | if !ok {
277 | log.Println("Streaming unsupported")
278 | http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
279 | return
280 | }
281 |
282 | completionID := "chatcmpl-" + uuid.New().String()
283 |
284 | startChunk := OpenAIChatCompletionChunk{
285 | ID: completionID,
286 | Object: "chat.completion.chunk",
287 | Created: time.Now().Unix(),
288 | Model: c.getModelName(),
289 | Choices: []OpenAIChatCompletionChunkChoice{
290 | {
291 | Index: 0,
292 | Delta: OpenAIChatCompletionMessage{
293 | Role: "assistant",
294 | },
295 | FinishReason: "",
296 | },
297 | },
298 | }
299 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(startChunk))
300 | flusher.Flush()
301 |
302 | c.parseGrok3StreamingJson(grokStream, func(respToken string) {
303 | chunk := OpenAIChatCompletionChunk{
304 | ID: completionID,
305 | Object: "chat.completion.chunk",
306 | Created: time.Now().Unix(),
307 | Model: c.getModelName(),
308 | Choices: []OpenAIChatCompletionChunkChoice{
309 | {
310 | Index: 0,
311 | Delta: OpenAIChatCompletionMessage{
312 | Content: respToken,
313 | },
314 | FinishReason: "",
315 | },
316 | },
317 | }
318 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(chunk))
319 | flusher.Flush()
320 | })
321 |
322 | finalChunk := OpenAIChatCompletionChunk{
323 | ID: completionID,
324 | Object: "chat.completion.chunk",
325 | Created: time.Now().Unix(),
326 | Model: c.getModelName(),
327 | Choices: []OpenAIChatCompletionChunkChoice{
328 | {
329 | Index: 0,
330 | Delta: OpenAIChatCompletionMessage{},
331 | FinishReason: "stop",
332 | },
333 | },
334 | }
335 | fmt.Fprintf(w, "data: %s\n\n", mustMarshal(finalChunk))
336 | flusher.Flush()
337 |
338 | fmt.Fprintf(w, "data: [DONE]\n\n")
339 | flusher.Flush()
340 | }
341 | }
342 |
343 | // CreateOpenAIFullResponse converts Grok 3 full response to OpenAI format.
344 | func (c *GrokClient) CreateOpenAIFullResponse(grokFull io.Reader) http.HandlerFunc {
345 | return func(w http.ResponseWriter, r *http.Request) {
346 | var fullResponse strings.Builder
347 | c.parseGrok3StreamingJson(grokFull, func(respToken string) {
348 | fullResponse.WriteString(respToken)
349 | })
350 |
351 | openAIResponse := c.createOpenAIFullResponseBody(fullResponse.String())
352 | w.Header().Set("Content-Type", "application/json")
353 | if err := json.NewEncoder(w).Encode(openAIResponse); err != nil {
354 | log.Printf("Encoding response error: %v", err)
355 | http.Error(w, fmt.Sprintf("Encoding response error: %v", err), http.StatusInternalServerError)
356 | return
357 | }
358 | }
359 | }
360 |
361 | // createOpenAIFullResponseBody creates the OpenAI response body for non-streaming requests.
362 | func (c *GrokClient) createOpenAIFullResponseBody(content string) OpenAIChatCompletion {
363 | return OpenAIChatCompletion{
364 | ID: "chatcmpl-" + uuid.New().String(),
365 | Object: "chat.completion",
366 | Created: time.Now().Unix(),
367 | Model: c.getModelName(),
368 | Choices: []OpenAIChatCompletionChoice{
369 | {
370 | Index: 0,
371 | Message: OpenAIChatCompletionMessage{
372 | Role: "assistant",
373 | Content: content,
374 | },
375 | FinishReason: "stop",
376 | },
377 | },
378 | Usage: OpenAIChatCompletionUsage{
379 | PromptTokens: -1,
380 | CompletionTokens: -1,
381 | TotalTokens: -1,
382 | },
383 | }
384 | }
385 |
386 | // mustMarshal serializes a value to JSON, panicking on error.
387 | func mustMarshal(v any) string {
388 | b, err := json.Marshal(v)
389 | if err != nil {
390 | panic(err)
391 | }
392 | return string(b)
393 | }
394 |
395 | // getCookieIndex selects the next cookie index in a round-robin fashion.
396 | func getCookieIndex(len int, cookieIndex uint) uint {
397 | if cookieIndex == 0 || cookieIndex > uint(len) {
398 | nextCookieIndex.Lock()
399 | defer nextCookieIndex.Unlock()
400 | index := nextCookieIndex.index
401 | nextCookieIndex.index = (nextCookieIndex.index + 1) % uint(len)
402 | return index % uint(len)
403 | } else {
404 | return cookieIndex - 1
405 | }
406 | }
407 |
408 | // createMessagesAttachment creates a text file with message history.
409 | func createMessagesAttachment(messages []struct {
410 | Role string `json:"role"`
411 | Content string `json:"content"`
412 | }) (string, error) {
413 | var builder strings.Builder
414 | for _, msg := range messages {
415 | builder.WriteString(fmt.Sprintf("[%s]\n%s\n\n", msg.Role, msg.Content))
416 | }
417 |
418 | fileName := fmt.Sprintf("messages-%s.txt", uuid.New().String())
419 | tempFile, err := os.Create(fileName)
420 | if err != nil {
421 | return "", fmt.Errorf("failed to create file: %v", err)
422 | }
423 | defer tempFile.Close()
424 |
425 | if _, err := tempFile.WriteString(builder.String()); err != nil {
426 | return "", fmt.Errorf("failed to write to file: %v", err)
427 | }
428 |
429 | return tempFile.Name(), nil
430 | }
431 |
432 | // handleChatCompletion handles POST requests to /v1/chat/completions.
433 | func handleChatCompletion(w http.ResponseWriter, r *http.Request) {
434 | log.Printf("Request from %s for %s", r.RemoteAddr, completionsPath)
435 |
436 | if r.URL.Path != completionsPath {
437 | log.Printf("Requested Path %s Not Found", r.URL.Path)
438 | http.Error(w, "Requested Path Not Found", http.StatusNotFound)
439 | return
440 | }
441 |
442 | if r.Method != http.MethodPost {
443 | log.Printf("Method %s Not Allowed", r.Method)
444 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
445 | return
446 | }
447 |
448 | authHeader := r.Header.Get("Authorization")
449 | if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
450 | log.Println("Unauthorized: Bearer token required")
451 | http.Error(w, "Unauthorized: Bearer token required", http.StatusUnauthorized)
452 | return
453 | }
454 |
455 | token := strings.TrimSpace(strings.TrimPrefix(authHeader, "Bearer "))
456 | if token != *apiToken {
457 | log.Println("Unauthorized: Invalid token")
458 | http.Error(w, "Unauthorized: Invalid token", http.StatusUnauthorized)
459 | return
460 | }
461 |
462 | body := RequestBody{EnableSearch: -1, KeepChat: -1, IgnoreThinking: -1}
463 | if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
464 | log.Println("Bad Request: Invalid JSON")
465 | http.Error(w, "Bad Request: Invalid JSON", http.StatusBadRequest)
466 | return
467 | }
468 |
469 | var cookie string
470 | var cookieIndex uint
471 | if body.GrokCookies != nil {
472 | if ck, ok := body.GrokCookies.(string); ok {
473 | cookie = ck
474 | } else if list, ok := body.GrokCookies.([]any); ok {
475 | if len(list) > 0 {
476 | cookieIndex = getCookieIndex(len(list), body.CookieIndex)
477 | if ck, ok := list[cookieIndex].(string); ok {
478 | cookie = ck
479 | }
480 | }
481 | }
482 | }
483 | cookie = strings.TrimSpace(cookie)
484 | if cookie == "" && len(grokCookies) > 0 {
485 | cookieIndex = getCookieIndex(len(grokCookies), body.CookieIndex)
486 | cookie = grokCookies[cookieIndex]
487 | }
488 | cookie = strings.TrimSpace(cookie)
489 | if cookie == "" {
490 | log.Println("Error: No Grok 3 cookie")
491 | http.Error(w, "Error: No Grok 3 cookie", http.StatusBadRequest)
492 | return
493 | }
494 |
495 | messages := body.Messages
496 | if len(messages) == 0 {
497 | log.Println("Bad Request: No messages provided")
498 | http.Error(w, "Bad Request: No messages provided", http.StatusBadRequest)
499 | return
500 | }
501 |
502 | messageJson := bytes.NewBuffer([]byte{})
503 | jsonEncoder := json.NewEncoder(messageJson)
504 | jsonEncoder.SetEscapeHTML(false)
505 | jsonEncoder.SetIndent("", "")
506 | err := jsonEncoder.Encode(messages)
507 | if err != nil {
508 | log.Println("Error: Encoding JSON failed")
509 | http.Error(w, "Error: Encoding JSON failed", http.StatusInternalServerError)
510 | return
511 | }
512 | if messageJson.Len() <= 2 {
513 | log.Println("Bad Request: No user message found")
514 | http.Error(w, "Bad Request: No user message found", http.StatusBadRequest)
515 | return
516 | }
517 |
518 | var fileAttachments []string
519 | if *longTxt && len(messages) > 1 {
520 | tempFilePath, err := createMessagesAttachment(messages)
521 | if err != nil {
522 | log.Printf("Error creating message attachment: %v", err)
523 | http.Error(w, fmt.Sprintf("Error creating message attachment: %v", err), http.StatusInternalServerError)
524 | return
525 | }
526 | fileAttachments = append(fileAttachments, tempFilePath)
527 | defer os.Remove(tempFilePath)
528 | log.Printf("Created message attachment with %d messages at %s", len(messages), tempFilePath)
529 | }
530 |
531 | isReasoning := false
532 | if strings.TrimSpace(body.Model) == grok3ReasoningModelName {
533 | isReasoning = true
534 | }
535 |
536 | enableSearch := false
537 | if body.EnableSearch > 0 {
538 | enableSearch = true
539 | }
540 |
541 | keepConversation := false
542 | if body.KeepChat > 0 {
543 | keepConversation = true
544 | } else if body.KeepChat < 0 {
545 | keepConversation = *keepChat
546 | }
547 |
548 | ignoreThink := false
549 | if body.IgnoreThinking > 0 {
550 | ignoreThink = true
551 | } else if body.IgnoreThinking < 0 {
552 | ignoreThink = *ignoreThinking
553 | }
554 |
555 | grokClient := NewGrokClient(cookie, isReasoning, enableSearch, keepConversation, ignoreThink)
556 | log.Printf("Use the cookie with index %d to request Grok 3 Web API", cookieIndex+1)
557 |
558 | respReader, err := grokClient.sendMessage(messageJson.String(), body.Stream, fileAttachments)
559 | if err != nil {
560 | log.Printf("Error: %v", err)
561 | http.Error(w, fmt.Sprintf("Error: %v", err), http.StatusInternalServerError)
562 | return
563 | }
564 | defer respReader.Close()
565 |
566 | if body.Stream {
567 | grokClient.CreateOpenAIStreamingResponse(respReader)(w, r)
568 | } else {
569 | grokClient.CreateOpenAIFullResponse(respReader)(w, r)
570 | }
571 | }
572 |
573 | // listModels handles GET requests to /v1/models.
574 | func listModels(w http.ResponseWriter, r *http.Request) {
575 | log.Printf("Request from %s for %s", r.RemoteAddr, listModelsPath)
576 |
577 | if r.URL.Path != listModelsPath {
578 | log.Printf("Requested Path %s Not Found", r.URL.Path)
579 | http.Error(w, "Requested Path Not Found", http.StatusNotFound)
580 | return
581 | }
582 |
583 | if r.Method != http.MethodGet {
584 | log.Printf("Method %s Not Allowed", r.Method)
585 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
586 | return
587 | }
588 |
589 | list := ModelList{
590 | Object: "list",
591 | Data: []ModelData{
592 | {
593 | Id: grok3ModelName,
594 | Object: "model",
595 | Owned_by: "xAI",
596 | },
597 | {
598 | Id: grok3ReasoningModelName,
599 | Object: "model",
600 | Owned_by: "xAI",
601 | },
602 | },
603 | }
604 |
605 | w.Header().Set("Content-Type", "application/json")
606 | if err := json.NewEncoder(w).Encode(list); err != nil {
607 | log.Printf("Encoding response error: %v", err)
608 | http.Error(w, fmt.Sprintf("Encoding response error: %v", err), http.StatusInternalServerError)
609 | return
610 | }
611 | }
612 |
613 | // loadCookiesFromDir loads cookies from the specified directory.
614 | func loadCookiesFromDir(dir string) error {
615 | if _, err := os.Stat(dir); os.IsNotExist(err) {
616 | return fmt.Errorf("cookies directory does not exist: %s", dir)
617 | }
618 |
619 | files, err := os.ReadDir(dir)
620 | if err != nil {
621 | return fmt.Errorf("failed to read directory %s: %v", dir, err)
622 | }
623 |
624 | grokCookies = []string{}
625 | for _, file := range files {
626 | if !file.IsDir() && strings.HasSuffix(file.Name(), ".txt") {
627 | filePath := filepath.Join(dir, file.Name())
628 | content, err := os.ReadFile(filePath)
629 | if err != nil {
630 | log.Printf("Warning: Failed to read cookie file %s: %v", filePath, err)
631 | continue
632 | }
633 | cookie := strings.TrimSpace(string(content))
634 | if cookie != "" {
635 | grokCookies = append(grokCookies, cookie)
636 | log.Printf("Loaded cookie from %s", filePath)
637 | }
638 | }
639 | }
640 | return nil
641 | }
642 |
643 | // main sets up the HTTP server and starts listening.
644 | func main() {
645 | apiToken = flag.String("token", "", "Authentication token (GROK3_AUTH_TOKEN)")
646 | cookie := flag.String("cookie", "", "Grok cookie (GROK3_COOKIE)")
647 | cookiesDir = flag.String("cookiesDir", "cookies", "Directory containing cookie.txt files")
648 | keepChat = flag.Bool("keepChat", false, "Retain the chat conversation")
649 | ignoreThinking = flag.Bool("ignoreThinking", false, "Ignore thinking content")
650 | httpProxy = flag.String("httpProxy", "", "HTTP/SOCKS5 proxy")
651 | httpProxyLower := flag.String("httpproxy", "", "HTTP/SOCKS5 proxy (lowercase alias)")
652 | longTxt = flag.Bool("longtxt", false, "Enable uploading long conversations as text file")
653 | port := flag.Uint("port", 8180, "Server port")
654 | flag.Parse()
655 |
656 | // If lowercase form of proxy parameter is used, assign its value to the uppercase form
657 | if *httpProxyLower != "" {
658 | *httpProxy = *httpProxyLower
659 | }
660 |
661 | if *port > 65535 {
662 | log.Fatalf("Server port %d is greater than 65535", *port)
663 | }
664 |
665 | *apiToken = strings.TrimSpace(*apiToken)
666 | if *apiToken == "" {
667 | *apiToken = os.Getenv("GROK3_AUTH_TOKEN")
668 | if *apiToken == "" {
669 | log.Fatal("Authentication token (GROK3_AUTH_TOKEN) is unset")
670 | }
671 | }
672 |
673 | *cookie = strings.TrimSpace(*cookie)
674 | if *cookie == "" {
675 | *cookie = strings.TrimSpace(os.Getenv("GROK3_COOKIE"))
676 | }
677 | if *cookie != "" {
678 | err := json.Unmarshal([]byte(*cookie), &grokCookies)
679 | if err != nil {
680 | grokCookies = []string{*cookie}
681 | }
682 | }
683 |
684 | if len(grokCookies) == 0 {
685 | err := loadCookiesFromDir(*cookiesDir)
686 | if err != nil {
687 | log.Printf("Warning: Failed to load cookies from directory %s: %v", *cookiesDir, err)
688 | }
689 | if len(grokCookies) == 0 {
690 | log.Fatal("No valid cookies found")
691 | }
692 | }
693 |
694 | *httpProxy = strings.TrimSpace(*httpProxy)
695 | if *httpProxy != "" {
696 | proxyURL, err := url.Parse(*httpProxy)
697 | if err == nil {
698 | httpClient.Transport = &http.Transport{
699 | Proxy: http.ProxyURL(proxyURL),
700 | DialContext: (&net.Dialer{
701 | Timeout: 30 * time.Second,
702 | KeepAlive: 30 * time.Second,
703 | }).DialContext,
704 | ForceAttemptHTTP2: true,
705 | MaxIdleConns: 10,
706 | IdleConnTimeout: 600 * time.Second,
707 | TLSHandshakeTimeout: 20 * time.Second,
708 | }
709 | } else {
710 | log.Fatalf("Parsing HTTP/SOCKS5 proxy error: %v", err)
711 | }
712 | }
713 |
714 | http.HandleFunc(completionsPath, handleChatCompletion)
715 | http.HandleFunc(listModelsPath, listModels)
716 | log.Printf("Server starting on :%d with %d cookies loaded, longtxt enabled: %v", *port, len(grokCookies), *longTxt)
717 |
718 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
719 | }
720 |
--------------------------------------------------------------------------------
/稳定版/grok3_api_stable:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/稳定版/grok3_api_stable
--------------------------------------------------------------------------------
/稳定版/grok3_api_stable_arm64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/稳定版/grok3_api_stable_arm64
--------------------------------------------------------------------------------
/稳定版/仅保存初始代码,无更多附加功能:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GhostXia/grok3_api-Fix/721a0b1f29f0269cc9180f32ec3dff7e6512754a/稳定版/仅保存初始代码,无更多附加功能
--------------------------------------------------------------------------------
/稳定版/启动.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | chcp 65001 >nul
3 |
4 | echo ========== Grok3 API 启动 ==========
5 | "%~dp0app.exe" -token 123456
--------------------------------------------------------------------------------