├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── assets
├── example1.png
├── example2.png
├── example3.png
├── example4.png
└── example5.png
├── chatblade
├── __init__.py
├── __main__.py
├── chat.py
├── cli.py
├── errors.py
├── parser.py
├── printer.py
├── session.py
├── storage.py
└── utils.py
├── pyproject.toml
├── requirements.txt
├── setup.cfg
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | **/__pycache__
2 | build
3 | **.egg-info
4 | venv
5 | .DS_Store
6 | .idea
7 | .vscode
8 | dist
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright © 2007 Free Software Foundation, Inc.
5 |
6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 | The GNU General Public License is a free, copyleft license for software and other kinds of works.
10 |
11 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
12 |
13 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
14 |
15 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
16 |
17 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
18 |
19 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
20 |
21 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
22 |
23 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
24 |
25 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
26 |
27 | The precise terms and conditions for copying, distribution and modification follow.
28 |
29 | TERMS AND CONDITIONS
30 | 0. Definitions.
31 | “This License” refers to version 3 of the GNU General Public License.
32 |
33 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
34 |
35 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
36 |
37 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
38 |
39 | A “covered work” means either the unmodified Program or a work based on the Program.
40 |
41 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
42 |
43 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
44 |
45 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
46 |
47 | 1. Source Code.
48 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
49 |
50 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
51 |
52 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
53 |
54 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
55 |
56 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
57 |
58 | The Corresponding Source for a work in source code form is that same work.
59 |
60 | 2. Basic Permissions.
61 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
62 |
63 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
64 |
65 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
66 |
67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
68 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
69 |
70 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
71 |
72 | 4. Conveying Verbatim Copies.
73 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
74 |
75 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
76 |
77 | 5. Conveying Modified Source Versions.
78 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
79 |
80 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
81 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
82 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
83 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
84 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
85 |
86 | 6. Conveying Non-Source Forms.
87 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
88 |
89 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
90 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
91 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
92 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
93 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
94 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
95 |
96 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
97 |
98 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
99 |
100 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
101 |
102 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
103 |
104 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
105 |
106 | 7. Additional Terms.
107 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
108 |
109 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
110 |
111 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
112 |
113 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
114 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
115 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
116 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
117 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
118 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
119 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
120 |
121 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
122 |
123 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
124 |
125 | 8. Termination.
126 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
127 |
128 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
129 |
130 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
131 |
132 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
133 |
134 | 9. Acceptance Not Required for Having Copies.
135 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
136 |
137 | 10. Automatic Licensing of Downstream Recipients.
138 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
139 |
140 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
141 |
142 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
143 |
144 | 11. Patents.
145 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
146 |
147 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
148 |
149 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
150 |
151 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
152 |
153 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
154 |
155 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
156 |
157 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
158 |
159 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
160 |
161 | 12. No Surrender of Others' Freedom.
162 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
163 |
164 | 13. Use with the GNU Affero General Public License.
165 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
166 |
167 | 14. Revised Versions of this License.
168 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
169 |
170 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
171 |
172 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
173 |
174 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
175 |
176 | 15. Disclaimer of Warranty.
177 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
178 |
179 | 16. Limitation of Liability.
180 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
181 |
182 | 17. Interpretation of Sections 15 and 16.
183 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
184 |
185 | END OF TERMS AND CONDITIONS
186 |
187 | How to Apply These Terms to Your New Programs
188 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
189 |
190 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
191 |
192 |
193 | Copyright (C)
194 |
195 | This program is free software: you can redistribute it and/or modify
196 | it under the terms of the GNU General Public License as published by
197 | the Free Software Foundation, either version 3 of the License, or
198 | (at your option) any later version.
199 |
200 | This program is distributed in the hope that it will be useful,
201 | but WITHOUT ANY WARRANTY; without even the implied warranty of
202 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
203 | GNU General Public License for more details.
204 |
205 | You should have received a copy of the GNU General Public License
206 | along with this program. If not, see .
207 | Also add information on how to contact you by electronic and paper mail.
208 |
209 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
210 |
211 | Copyright (C)
212 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
213 | This is free software, and you are welcome to redistribute it
214 | under certain conditions; type `show c' for details.
215 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
216 |
217 | You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see .
218 |
219 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .
220 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | venv/bin/activate: requirements.txt
2 | python3 -m venv venv
3 | ./venv/bin/pip install -r requirements.txt
4 |
5 | setup: venv/bin/activate
6 |
7 | clean: clean-build clean-pyc
8 |
9 | sanitize: clean clean-venv
10 |
11 | clean-venv:
12 | rm -rf venv/
13 |
14 | clean-build:
15 | rm -fr build/
16 | rm -fr dist/
17 | rm -fr .eggs/
18 | find . -name '*.egg-info' -exec rm -fr {} +
19 | find . -name '*.egg' -exec rm -f {} +
20 |
21 | clean-pyc:
22 | find . -name '*.pyc' -exec rm -f {} +
23 | find . -name '*.pyo' -exec rm -f {} +
24 | find . -name '*~' -exec rm -f {} +
25 | find . -name '__pycache__' -exec rm -fr {} +
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Chatblade
2 |
3 | ## A CLI Swiss Army Knife for ChatGPT
4 |
5 | Chatblade is a versatile command-line interface (CLI) tool designed to interact with OpenAI's ChatGPT. It accepts piped input, arguments, or both, and allows you to save common prompt preambles for quick usage. Additionally, Chatblade provides utility methods to extract JSON or Markdown from ChatGPT responses.
6 |
7 | **Note**: You'll need to set up your OpenAI API key to use Chatblade.
8 |
9 | You can do that by either passing `--openai-api-key KEY` or by setting an env variable `OPENAI_API_KEY` (recommended). The examples below all assume an env variable is set.
10 |
11 | ## Install
12 |
13 | ### Latest and greatest
14 |
15 | To stay up to date with the current main branch you can:
16 |
17 | - check out the project, and run `pip install .`
18 | - or `pip install 'chatblade @ git+https://github.com/npiv/chatblade'`
19 |
20 | ### Via pypi
21 |
22 | The last released version can be installed with `pip install chatblade --upgrade`
23 |
24 | ### Via Brew
25 |
26 | ```
27 | brew install chatblade
28 | ```
29 |
30 | ## Documentation
31 |
32 | ### Making queries
33 |
34 | #### A new conversation
35 |
36 | You can begin any query by just typing. f.e.:
37 |
38 | ```bash
39 | chatblade how can I extract a still frame from a video at 22:01 with ffmpeg
40 | ```
41 |
42 |
43 |
44 | #### recall the last conversation
45 |
46 | if you would like to recall the last conversation just call it back with `-l`
47 |
48 | ```bash
49 | chatblade -l
50 | ```
51 |
52 | #### Continue the last conversation
53 |
54 | To continue the conversation and ask for a change within the context, you can again use `-l` but with a query.
55 |
56 | ```bash
57 | chatblade -l can we make a gif instead from 00:22:01 to 00:22:04
58 | ```
59 |
60 | `-l` is shorthand for `-S last` or the last session. We can keep track of and continue various distinct conversations using the [session options](#session-options)
61 |
62 | #### Picking between gpt-3.5 and 4
63 |
64 | By default, gpt-3.5 is used, you can switch at any point to 4 by using `-c 4` or the latest 4o ("omni") by using `-c 4o`.
65 |
66 | Additionally, you can pass any arbitrary full model name, f.e. `-c gpt-3.5-turbo-16k`.
67 |
68 | #### Chatting interactively
69 |
70 | If you preferred to chat interactively instead just use `chatblade -i`.
71 |
72 | #### Show streaming text (experimental)
73 |
74 | You can also stream the responses, just like in the webui. At the end of the stream it will format the result. This can be combined in an interactive session
75 |
76 | ```chatblade -s -i```
77 |
78 |
79 |
80 | ### Formatting the results
81 |
82 | Responses are parsed and if chatblade thinks its markdown it will be presented as such, to get syntax highlighting. But sometimes this may not be what you want, as it removes new lines, or because you are only interested in extracting a part of the result to pipe to another command.
83 |
84 | In that case you have 2 options:
85 |
86 | - `-r` for raw, which just prints the text exactly as ChatGPT returned it, and doesn't pass it through Markdown.
87 | - `-e` for extract, which will try to detect what was returned (either a code block or json) and extract only that part. If neither of those are found it does the same as `-r`
88 |
89 | Both options can be used either with a new query, e.g.
90 |
91 | ```bash
92 | chatblade -e write me a python boilerplate script that starts a server and prints hello world > main.py
93 | ```
94 |
95 | or with the last result (json in this example)
96 |
97 | ```bash
98 | chatblade -l -e | jq
99 | ```
100 |
101 | ### Piping content into chatblade
102 |
103 | If we have long prompts we don't want to type everytime, or just want to provide context for our query we can pipe into chatblade.
104 |
105 | e.g.
106 |
107 | ```bash
108 | curl https://news.ycombinator.com/rss | chatblade given the above rss can you show me the top 3 articles about AI and their links -c 4
109 | ```
110 |
111 | The piped input is placed above the query and sent to ChatGPT.
112 |
113 |
114 |
115 | or
116 |
117 | ```bash
118 | chatblade what does this script do < script.sh
119 | ```
120 |
121 | What gets sent to ChatGPT over the wire is:
122 |
123 | ```
124 | piped input
125 | -------
126 | query
127 | ```
128 |
129 | #### Session Options
130 |
131 | Sessions are named conversations.
132 |
133 | If you start chatblade with a session name SESS of your choice:
134 |
135 | ```bash
136 | chatblade -S SESS can we make a gif instead from 00:22:01 to 00:22:04
137 | ```
138 |
139 | chatblade will create a session called SESS if it does not exist, and it will store the current exchange (query-response pair) for SESS.
140 |
141 | If such a session already exists, the saved conversation will be loaded and the new exchange will be appended.
142 |
143 | Without a session argument, the exchange also gets stored in a session named `last`; however, subsequent sessionless invocation will overwrite the content of `last`. (You can continue a conversation that was started as a sessionless exchange by passing `-S last`, but `last` won't be a safe space for keeping a conversation, as the next sessionless invocation will clear it again.) The `-l` option is provided as a shorthand for `-S last`.
144 |
145 | If you specify a session without a query:
146 |
147 | ```bash
148 | chatblade -S SESS
149 | ```
150 |
151 | chatblade will recall the conversation without modifying the session.
152 |
153 | chatblade supports various operations on sessions. It provides the `--session-OP` options, where `OP` can be `list`, `path`, `dump`, `delete`, `rename`.
154 |
155 | ### Checking token count and estimated costs
156 |
157 | If you want to check the approximate cost and token usage of a previous query, you can use the `-t` flag for "tokens."
158 |
159 | We could do this when passing in a lot of context like in the example above for instance.
160 |
161 | ```bash
162 | curl https://news.ycombinator.com/rss | chatblade given the above rss can you show me the top 3 articles about AI and their links -t
163 | ```
164 |
165 |
166 |
167 | This won't perform any action over the wire, and just calculates the tokens locally.
168 |
169 | ### Use custom prompts (the system msg)
170 |
171 | The system message is used to instruct the model how to behave, see [OpenAI - Instructing Chat Models](https://platform.openai.com/docs/guides/chat/instructing-chat-models).
172 |
173 | These can be loaded with `-p`. For convenience any file we place under ~/.config/chatblade/ will be picked up by this command.
174 |
175 | So for example, given the following file `~/.config/chatblade/etymology`, which contains:
176 |
177 | ```
178 | I want you to act as a professional Etymologist and Quiz Generator. You have a deep knowledge of etymology and will be provided with a word.
179 | The goal is to create cards that quiz on both the etymology and finding the word by its definition.
180 |
181 | The following is what a perfect answer would look like for the word "disparage":
182 |
183 | [{
184 | "question": "A verb used to indicate the act of speaking about someone or something in a negative or belittling way.
E.g He would often _______ his coworkers behind their backs.",
185 | "answer": "disparage"
186 | },
187 | {
188 | "question": "What is the etymological root of the word disparage?",
189 | "answer": "From the Old French word 'desparagier', meaning 'marry someone of unequal rank', which comes from 'des-' (dis-) and 'parage' (equal rank)"
190 | }]
191 |
192 | You will return answers in JSON only. Answer truthfully and if you don't know then say so. Keep questions as close as possible to the
193 | provided examples. Make sure to include an example in the definition question. Use HTML within the strings to nicely format your answers.
194 |
195 | If multiple words are provided, create questions and answers for each of them in one list.
196 |
197 | Only answer in JSON, don't provide any more text. Valid JSON uses "" quotes to wrap its items.
198 | ```
199 |
200 | We can now run a command and refer to this prompt with `-p etymology`:
201 |
202 | ```bash
203 | chatblade -p etymology gregarious
204 | ```
205 |
206 | You can also point -p to a file path directly to load a system message from any arbitrary location
207 |
208 |
209 |
210 | And since we asked for JSON, we can pipe our result to something else, e.g.:
211 |
212 | ```bash
213 | chatblade -l -e > toanki
214 | ```
215 |
216 | ### Configuring for Azure OpenAI
217 |
218 | chatblade can be used with an Azure OpenAI endpoint, in which case in addition to the `OPENAI_API_KEY` you'll need to set the following environment variables:
219 |
220 | - `OPENAI_API_TYPE` :: Set to `azure`. As required by [openai-python](https://github.com/openai/openai-python)
221 | - `AZURE_OPENAI_ENDPOINT` :: URL to your cognitive services' endpoint, e.g. `https://eastus.api.cognitive.microsoft.com/`. Please note this is a *breaking change* introduced by `openai-python` and the previous environment variable name is `OPENAI_API_BASE`
222 | - `OPENAI_API_AZURE_ENGINE` :: name of your deployment in Azure, f.e. `my-gpt-35-turbo` (maps to a specific model)
223 |
224 | *Note*: that this will override any option for `-c 3.5` or `-c 4` which don't make sense in this case.
225 |
226 | ### Help
227 |
228 | ```
229 | usage: Chatblade [-h] [--openai-api-key key] [--openai-base-url key] [--temperature t] [-c CHAT_GPT] [-i] [-s] [-t] [--version] [-p name] [-e] [-r] [-n] [-o] [--theme theme] [-l]
230 | [-S sess] [--session-list] [--session-path] [--session-dump] [--session-delete] [--session-rename newsess]
231 | [query ...]
232 |
233 | a CLI Swiss Army Knife for ChatGPT
234 |
235 | positional arguments:
236 | query Query to send to chat GPT
237 |
238 | options:
239 | -h, --help show this help message and exit
240 | --openai-api-key key the OpenAI API key can also be set as env variable OPENAI_API_KEY
241 | --openai-base-url key A custom url to use the openAI against a local or custom model, eg ollama
242 | --temperature t temperature (openai setting)
243 | -c CHAT_GPT, --chat-gpt CHAT_GPT
244 | chat GPT model use either the fully qualified model name, or 3.5 (gpt-3.5-turbo), 4 (gpt-4), 4t (gpt-4-turbo), 4o (gpt-4o), mini (gpt-4o-mini),
245 | o1 (o1-preview), o1mini (o1-mini). Can also be set via env variable OPENAI_API_MODEL
246 | -i, --interactive start an interactive chat session. This will implicitly continue the conversation
247 | -s, --stream Stream the incoming text to the terminal
248 | -t, --tokens display what *would* be sent, how many tokens, and estimated costs
249 | --version display the chatblade version
250 | -p name, --prompt-file name prompt name - will load the prompt with that name at ~/.config/chatblade/name or a path to a file
251 |
252 | result formatting options:
253 | -e, --extract extract content from response if possible (either json or code block)
254 | -r, --raw print session as pure text, don't pretty print or format
255 | -n, --no-format do not add pretty print formatting to output
256 | -o, --only Only display the response, omit query
257 | --theme theme Set the theme for syntax highlighting see https://pygments.org/styles/, can also be set with CHATBLADE_THEME
258 |
259 | session options:
260 | -l, --last alias for '-S last', the default session if none is specified
261 | -S sess, --session sess initiate or continue named session
262 | --session-list list sessions
263 | --session-path show path to session file
264 | --session-dump dump session to stdout
265 | --session-delete delete session
266 | --session-rename newsess rename session
267 | ```
268 |
269 |
--------------------------------------------------------------------------------
/assets/example1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/assets/example1.png
--------------------------------------------------------------------------------
/assets/example2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/assets/example2.png
--------------------------------------------------------------------------------
/assets/example3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/assets/example3.png
--------------------------------------------------------------------------------
/assets/example4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/assets/example4.png
--------------------------------------------------------------------------------
/assets/example5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/assets/example5.png
--------------------------------------------------------------------------------
/chatblade/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/npiv/chatblade/9f12a3405a1daf0f09da0e0889d97ac366ceaa7b/chatblade/__init__.py
--------------------------------------------------------------------------------
/chatblade/__main__.py:
--------------------------------------------------------------------------------
1 | from . import cli
2 |
3 |
4 | def main():
5 | cli.cli()
6 |
7 |
8 | if __name__ == "__main__":
9 | try:
10 | main()
11 | except (EOFError, KeyboardInterrupt):
12 | exit()
13 |
--------------------------------------------------------------------------------
/chatblade/chat.py:
--------------------------------------------------------------------------------
1 | import collections
2 | import os
3 | import yaml
4 |
5 | import tiktoken
6 | import openai
7 | from openai._exceptions import OpenAIError
8 |
9 | from . import utils, errors
10 |
11 |
12 | class Message(collections.namedtuple("Message", ["role", "content"])):
13 | @staticmethod
14 | def represent_for_yaml(dumper, msg):
15 | val = []
16 | md = msg._asdict()
17 |
18 | for fie in msg._fields:
19 | val.append([dumper.represent_data(e) for e in (fie, md[fie])])
20 |
21 | return yaml.nodes.MappingNode("tag:yaml.org,2002:map", val)
22 |
23 | @classmethod
24 | def import_yaml(cls, seq):
25 | """instantiate from YAML provided representation"""
26 | return cls(**seq)
27 |
28 |
29 | yaml.add_representer(Message, Message.represent_for_yaml)
30 |
31 |
32 | CostConfig = collections.namedtuple("CostConfig", "name prompt_cost completion_cost")
33 | CostCalculation = collections.namedtuple("CostCalculation", "name tokens cost")
34 |
35 | costs = [
36 | CostConfig("gpt-3.5-turbo", 0.5, 1.5),
37 | CostConfig("gpt-4-turbo", 10, 30),
38 | CostConfig("gpt-4", 30, 60),
39 | CostConfig("gpt-4-1106-preview", 10, 60),
40 | CostConfig("gpt-4o-mini", 0.15, 0.075),
41 | CostConfig("o1-preview", 15, 60),
42 | CostConfig("o1-mini", 3, 1.5),
43 | ]
44 |
45 |
46 | def get_tokens_and_costs(messages):
47 | return [
48 | CostCalculation(
49 | cost_config.name, *num_tokens_in_messages(messages, cost_config)
50 | )
51 | for cost_config in costs
52 | ]
53 |
54 |
55 | def num_tokens_in_messages(messages, cost_config):
56 | """Returns the number of tokens used by a list of messages."""
57 | try:
58 | encoding = tiktoken.encoding_for_model(f"{cost_config.name}-0301")
59 | except KeyError:
60 | encoding = tiktoken.get_encoding("cl100k_base")
61 | num_tokens = 0
62 | cost = 0
63 | for i, message in enumerate(messages):
64 | msg_tokens = (
65 | 4 # every message follows {role/name}\n{content}\n
66 | )
67 | msg_tokens += len(encoding.encode(message.role))
68 | msg_tokens += len(encoding.encode(message.content))
69 | if i == len(messages) - 1 and message.role == "assistant":
70 | cost += cost_config.completion_cost * msg_tokens
71 | else:
72 | cost += cost_config.prompt_cost * msg_tokens
73 | num_tokens += msg_tokens
74 | if messages[-1].role == "user":
75 | num_tokens += 2 # every reply is primed with assistant
76 | cost += cost_config.prompt_cost * 2
77 | return num_tokens, cost / 1000000
78 |
79 |
80 | def init_conversation(user_msg, system_msg=None):
81 | system = [Message("system", system_msg)] if system_msg else []
82 | return system + [Message("user", user_msg)]
83 |
84 |
85 | DEFAULT_OPENAI_SETTINGS = {
86 | "model": "gpt-3.5-turbo",
87 | "temperature": 0.1,
88 | "n": 1,
89 | "stream": False,
90 | }
91 |
92 |
93 | def map_from_stream(openai_gen):
94 | """maps a openai streaming generator a stream of Message with the
95 | final one being the completed Message"""
96 | role, message = None, ""
97 | for update in openai_gen:
98 | delta = [choice.delta for choice in update.choices][0]
99 | if delta.role:
100 | role = delta.role
101 | elif delta.content:
102 | message += delta.content
103 | yield Message(role, message)
104 |
105 |
106 | def map_single(result):
107 | """maps a result to a Message"""
108 | response_message = [choice.message for choice in result.choices][0]
109 | return Message(response_message.role, response_message.content)
110 |
111 |
112 | def build_client(config):
113 | if "OPENAI_API_AZURE_ENGINE" in os.environ:
114 | return openai.AzureOpenAI(
115 | api_key=config["openai_api_key"],
116 | azure_deployment=os.environ.get("OPENAI_API_AZURE_ENGINE"),
117 | )
118 | else:
119 | return openai.OpenAI(
120 | api_key=config["openai_api_key"], base_url=config["openai_base_url"]
121 | )
122 |
123 |
124 | def query_chat_gpt(messages, config):
125 | """Queries the chat GPT API with the given messages and config."""
126 | client = build_client(config)
127 | config = utils.merge_dicts(DEFAULT_OPENAI_SETTINGS, config)
128 | dict_messages = [msg._asdict() for msg in messages]
129 | try:
130 | result = client.chat.completions.create(messages=dict_messages, **config)
131 | if isinstance(result, openai._streaming.Stream):
132 | return map_from_stream(result)
133 | elif isinstance(result, openai.types.chat.ChatCompletion):
134 | return map_single(result)
135 | else:
136 | raise ValueError(f"unexpected result openai: {result}")
137 | except OpenAIError as e:
138 | raise errors.ChatbladeError(f"openai error: {e}")
139 |
--------------------------------------------------------------------------------
/chatblade/cli.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import types
3 | import os
4 |
5 | import rich
6 | from rich.prompt import Prompt
7 | from rich.live import Live
8 | from rich.text import Text
9 |
10 | from . import printer, chat, utils, storage, errors, parser, session
11 |
12 |
13 | def fetch_and_cache(messages, params):
14 | result = chat.query_chat_gpt(messages, params)
15 | if isinstance(result, types.GeneratorType):
16 | text = Text("")
17 | message = None
18 | with Live(text, refresh_per_second=4, vertical_overflow="visible") as live:
19 | for message in result:
20 | live.update(message.content)
21 | live.update("")
22 | response_msg = message
23 | else:
24 | response_msg = result
25 | messages.append(response_msg)
26 | storage.to_cache(messages, params.session or utils.scratch_session)
27 | return messages
28 |
29 |
30 | def start_repl(messages, params):
31 | while True:
32 | try:
33 | query = Prompt.ask("[yellow]query (type 'quit' to exit)[/yellow]")
34 | except (EOFError, KeyboardInterrupt):
35 | rich.print("\n")
36 | exit()
37 | if query.lower() == "quit":
38 | exit()
39 |
40 | if not messages:
41 | init_msgs = (
42 | [storage.load_prompt_file(params.prompt_file)]
43 | if params.prompt_file
44 | else []
45 | )
46 | messages = chat.init_conversation(query, *init_msgs)
47 | else:
48 | messages.append(chat.Message("user", query))
49 |
50 | messages = fetch_and_cache(messages, params)
51 | printer.print_messages(messages[-1:], params)
52 |
53 |
54 | def handle_input(query, params):
55 | utils.debug(title="cli input", query=query, params=params)
56 |
57 | messages = None
58 | if params.session:
59 | messages = storage.messages_from_cache(params.session)
60 | if messages: # a session specified and it alredy exists
61 | if params.prompt_file:
62 | printer.warn("refusing to prepend prompt to existing session")
63 | exit(1)
64 | if query: # continue conversation
65 | messages.append(chat.Message("user", query))
66 | else:
67 | if query:
68 | init_msgs = (
69 | [storage.load_prompt_file(params.prompt_file)]
70 | if params.prompt_file
71 | else []
72 | )
73 | messages = chat.init_conversation(query, *init_msgs)
74 |
75 | if messages:
76 | if params.tokens:
77 | token_prices = chat.get_tokens_and_costs(messages)
78 | printer.print_tokens(messages, token_prices, params)
79 | else:
80 | if messages[-1].role == "user":
81 | messages = fetch_and_cache(messages, params)
82 | printer.print_messages(messages, params)
83 | elif params.interactive:
84 | pass
85 | else:
86 | if params.session:
87 | printer.warn(
88 | f"session {params.session} does not exist, query is needed to initialize it"
89 | )
90 | exit(1)
91 | else:
92 | printer.warn("no query or option given. nothing to do...")
93 | exit(0)
94 |
95 | if params.interactive:
96 | start_repl(messages, params)
97 |
98 |
99 | def do_session_op(sess, op, rename_to):
100 | if op == "list":
101 | print(*session.list_sessions(), sep="\n")
102 | return 0
103 |
104 | err = None
105 | if not sess:
106 | err = "session name required"
107 | elif op == "path" or op == "dump":
108 | sess_path = storage.get_session_path(sess, True)
109 | if sess_path:
110 | if op == "path":
111 | data = sess_path
112 | else:
113 | with open(sess_path, "r") as f:
114 | data = f.read()
115 | print(data)
116 | else:
117 | err = "session does not exist"
118 | elif op == "delete":
119 | err = session.delete_session(sess)
120 | elif op == "rename":
121 | err = session.rename_session(sess, rename_to)
122 | else:
123 | raise ValueError(f"unknown session operation: {op}")
124 |
125 | if err:
126 | printer.warn(err)
127 | return 1
128 |
129 | return 0
130 |
131 |
132 | def migrate_old_cache_file_if_exists():
133 | cache_path = storage.get_cache_path()
134 | if os.path.isfile(cache_path):
135 | try:
136 | storage.migrate_to_session(utils.scratch_session)
137 | except Exception as e:
138 | printer.warn(f"failed to migrate old cache file: {e}")
139 | return 1
140 |
141 |
142 | def cli():
143 | migrate_old_cache_file_if_exists()
144 |
145 | query, params = parser.parse(sys.argv[1:])
146 | if params.session_op:
147 | ret = do_session_op(params.session, params.session_op, params.rename_to)
148 | exit(ret)
149 | if params.debug:
150 | utils.CONSOLE_DEBUG_LOGGING = True
151 | if params.version:
152 | from importlib.metadata import version as get_version
153 | print(f"chatblade {get_version('chatblade')}")
154 | exit(0)
155 | try:
156 | handle_input(query, params)
157 | except errors.ChatbladeError as e:
158 | printer.warn(e)
159 | exit(1)
160 |
--------------------------------------------------------------------------------
/chatblade/errors.py:
--------------------------------------------------------------------------------
1 | class ChatbladeError(Exception):
2 | pass
3 |
--------------------------------------------------------------------------------
/chatblade/parser.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import os
3 | import argparse
4 |
5 | from . import utils
6 |
7 |
8 | def get_piped_input():
9 | if not sys.stdin.isatty():
10 | return sys.stdin.read()
11 | return None
12 |
13 |
14 | def get_openai_key(options):
15 | if options["openai_api_key"]:
16 | return options["openai_api_key"]
17 | elif "OPENAI_API_KEY" in os.environ:
18 | return os.environ["OPENAI_API_KEY"]
19 | else:
20 | return None
21 |
22 |
23 | # https://platform.openai.com/docs/models/continuous-model-upgrades
24 | model_mappings = {
25 | "3.5": "gpt-3.5-turbo",
26 | "4": "gpt-4",
27 | "4t": "gpt-4-turbo",
28 | "4o": "gpt-4o",
29 | "mini": "gpt-4o-mini",
30 | "o1": "o1-preview",
31 | "o1mini": "o1-mini",
32 | }
33 |
34 | DEFAULT_MODEL = "mini"
35 |
36 |
37 | def get_openai_model(options):
38 | choice = options["chat_gpt"]
39 | if not choice:
40 | if "OPENAI_API_MODEL" in os.environ:
41 | choice = os.environ["OPENAI_API_MODEL"]
42 | else:
43 | choice = DEFAULT_MODEL
44 |
45 | if choice in model_mappings:
46 | return model_mappings[choice]
47 | else:
48 | return choice
49 |
50 |
51 | def get_theme(options):
52 | if options["theme"]:
53 | return options["theme"]
54 | elif "CHATBLADE_THEME" in os.environ:
55 | return os.environ["CHATBLADE_THEME"]
56 | else:
57 | return None
58 |
59 |
60 | def extract_query(query):
61 | """The query comes from both the query and any piped input
62 | The user can provide either only a query, a piped input, or both
63 | in which case the piped input gets placed above the query
64 | """
65 | query = " ".join(query) if query else None
66 | piped_input = get_piped_input()
67 | if query and piped_input:
68 | return piped_input + "\n----------------\n" + query
69 | elif query:
70 | return query
71 | elif piped_input:
72 | return piped_input
73 | else:
74 | return None
75 |
76 |
77 | def extract_options(options):
78 | options = vars(options) # to map
79 | options["openai_api_key"] = get_openai_key(options)
80 | options["theme"] = get_theme(options)
81 | options["model"] = get_openai_model(options)
82 | del options["query"]
83 | del options["chat_gpt"]
84 | return utils.DotDict(options)
85 |
86 |
87 | def valid_session(sess):
88 | if all(char not in sess for char in ["/", "\\", "\n"]):
89 | return sess
90 | else:
91 | raise argparse.ArgumentTypeError(f"invalid session name {sess}")
92 |
93 |
94 | class RenameAction(argparse.Action):
95 | def __call__(self, parser, namespace, values, option_string=None):
96 | namespace.session_op = "rename"
97 | try:
98 | namespace.rename_to = valid_session(values[0])
99 | except argparse.ArgumentTypeError as e:
100 | raise argparse.ArgumentError(self, f"target: {e}")
101 |
102 |
103 | model_mappings_str = ", ".join(["%s (%s)" % e for e in model_mappings.items()])
104 |
105 |
106 | def parse(args):
107 | parser = argparse.ArgumentParser(
108 | "Chatblade",
109 | description="a CLI Swiss Army Knife for ChatGPT",
110 | formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=35),
111 | )
112 | parser.add_argument("query", type=str, nargs="*", help="Query to send to chat GPT")
113 |
114 | parser.add_argument(
115 | "--openai-api-key",
116 | metavar="key",
117 | type=str,
118 | help="the OpenAI API key can also be set as env variable OPENAI_API_KEY",
119 | )
120 | parser.add_argument(
121 | "--openai-base-url",
122 | metavar="key",
123 | type=str,
124 | help="A custom url to use the openAI against a local or custom model, eg ollama",
125 | )
126 | parser.add_argument(
127 | "--temperature",
128 | metavar="t",
129 | type=float,
130 | help="temperature (openai setting)",
131 | default=0.0,
132 | )
133 | parser.add_argument(
134 | "-c",
135 | "--chat-gpt",
136 | help=f"""chat GPT model use either the fully qualified model name, or
137 | {model_mappings_str}. Can also be set via env variable OPENAI_API_MODEL
138 | """,
139 | type=str,
140 | )
141 | parser.add_argument(
142 | "-i",
143 | "--interactive",
144 | help="start an interactive chat session. This will implicitly continue the conversation",
145 | action="store_true",
146 | )
147 | parser.add_argument(
148 | "-s",
149 | "--stream",
150 | help="Stream the incoming text to the terminal",
151 | action="store_true",
152 | )
153 | parser.add_argument(
154 | "-t",
155 | "--tokens",
156 | help="display what *would* be sent, how many tokens, and estimated costs",
157 | action="store_true",
158 | )
159 | parser.add_argument(
160 | "--version",
161 | help="display the chatblade version",
162 | action="store_true",
163 | )
164 | parser.add_argument(
165 | "-p",
166 | "--prompt-file",
167 | metavar="name",
168 | type=str,
169 | help="prompt name - will load the prompt with that name at ~/.config/chatblade/name or a path to a file",
170 | )
171 |
172 | display_opts = parser.add_argument_group("result formatting options")
173 | display_opts.add_argument(
174 | "-e",
175 | "--extract",
176 | help="extract content from response if possible (either json or code block)",
177 | action="store_true",
178 | )
179 | display_opts.add_argument(
180 | "-r",
181 | "--raw",
182 | help="print session as pure text, don't pretty print or format",
183 | action="store_true",
184 | )
185 | display_opts.add_argument(
186 | "-n",
187 | "--no-format",
188 | help="do not add pretty print formatting to output",
189 | action="store_true",
190 | )
191 | display_opts.add_argument(
192 | "-o",
193 | "--only",
194 | help="Only display the response, omit query",
195 | action="store_true",
196 | )
197 | display_opts.add_argument(
198 | "--theme",
199 | metavar="theme",
200 | type=str,
201 | help="Set the theme for syntax highlighting see https://pygments.org/styles/, can also be set with CHATBLADE_THEME",
202 | )
203 |
204 | session_opts = parser.add_argument_group("session options")
205 | session_opts.add_argument(
206 | "-l",
207 | "--last",
208 | dest="session",
209 | action="store_const",
210 | const=utils.scratch_session,
211 | help=f"alias for '-S {utils.scratch_session}', the default session if none is specified",
212 | )
213 | session_opts.add_argument(
214 | "-S",
215 | "--session",
216 | metavar="sess",
217 | type=valid_session,
218 | help="""initiate or continue named session""",
219 | )
220 | session_opts.add_argument(
221 | "--session-list",
222 | dest="session_op",
223 | action="store_const",
224 | const="list",
225 | help="list sessions",
226 | )
227 | session_opts.add_argument(
228 | "--session-path",
229 | dest="session_op",
230 | action="store_const",
231 | const="path",
232 | help="show path to session file",
233 | )
234 | session_opts.add_argument(
235 | "--session-dump",
236 | dest="session_op",
237 | action="store_const",
238 | const="dump",
239 | help="dump session to stdout",
240 | )
241 | session_opts.add_argument(
242 | "--session-delete",
243 | dest="session_op",
244 | action="store_const",
245 | const="delete",
246 | help="delete session",
247 | )
248 | session_opts.add_argument(
249 | "--session-rename",
250 | metavar="newsess",
251 | action=RenameAction,
252 | nargs=1,
253 | help="rename session",
254 | )
255 |
256 | # --- debug
257 | parser.add_argument("--debug", action="store_true", help=argparse.SUPPRESS)
258 |
259 | options = parser.parse_args(args)
260 | return extract_query(options.query), extract_options(options)
261 |
--------------------------------------------------------------------------------
/chatblade/printer.py:
--------------------------------------------------------------------------------
1 | import json
2 | import re
3 | import sys
4 | import rich
5 | from rich.console import Console
6 | from rich.json import JSON
7 | from rich.markdown import Markdown
8 | from rich.table import Table
9 | from rich.rule import Rule
10 |
11 | from chatblade import utils
12 | from pylatexenc.latex2text import LatexNodes2Text
13 |
14 |
15 | console = Console()
16 |
17 |
18 | def warn(msg):
19 | rich.print(f"[red]{msg}[/red]", file=sys.stderr)
20 |
21 |
22 | def print_tokens(messages, token_stats, args):
23 | if args.only:
24 | args.roles = ["assistant"]
25 | else:
26 | args.roles = ["user", "assistant", "system"]
27 | print_messages(messages, args)
28 | console.print()
29 | table = Table(title="tokens/costs")
30 | table.add_column("Model", no_wrap=True)
31 | table.add_column("Tokens", no_wrap=True)
32 | table.add_column("Price", style="bold", justify="right")
33 | for token_stat in token_stats:
34 | table.add_row(
35 | token_stat.name,
36 | "{:d}".format(token_stat.tokens),
37 | "${:.6f}".format(token_stat.cost),
38 | )
39 | console.print(table)
40 | console.print(
41 | "[red] * estimated costs do not include the tokens that may be returned[/red]"
42 | )
43 |
44 |
45 | def print_messages(messages, args):
46 | if "roles" not in args:
47 | if args.only:
48 | args.roles = ["assistant"]
49 | else:
50 | args.roles = ["user", "assistant"]
51 | if args.extract:
52 | extract_messages(messages, args)
53 | else:
54 | for message in messages:
55 | if message.role in args.roles:
56 | print_message(message, args)
57 |
58 |
59 | COLORS = {"user": "blue", "assistant": "green", "system": "red"}
60 |
61 |
62 | def print_message(message, args):
63 | printable = message.content
64 | if not args.raw:
65 | printable = detect_and_format_message(
66 | message.content, cutoff=1000 if message.role == "user" else None, theme=args.theme
67 | )
68 | if not args.no_format:
69 | console.print(Rule(message.role, style=COLORS[message.role]))
70 |
71 | if args.raw:
72 | print(message.content)
73 | else:
74 | console.print(printable)
75 |
76 | if not args.no_format:
77 | console.print(Rule(style=COLORS[message.role]))
78 |
79 |
80 | def extract_messages(messages, args):
81 | message = messages[-1]
82 | if contains_json(message.content):
83 | print(extract_json(message.content))
84 | elif contains_block(message.content):
85 | print(extract_block(message.content))
86 | else:
87 | print(message.content.strip())
88 |
89 | def format_latex(msg):
90 | # Replace code blocks and inline code with markers. Use null delimiters to
91 | # hopefully avoid any overlap with anything chatgpt could ever output.
92 | code_block_pattern = re.compile(r"```[\w]*\n.*?\n```", re.DOTALL)
93 | code_blocks = re.findall(code_block_pattern, msg)
94 | msg = re.sub(code_block_pattern, "\0CODE_BLOCK\0", msg)
95 | code_inline_pattern = re.compile(r"`.*?`", re.DOTALL)
96 | code_inlines = re.findall(code_inline_pattern, msg)
97 | msg = re.sub(code_inline_pattern, "\0CODE_INLINE\0", msg)
98 |
99 | converter = LatexNodes2Text(keep_comments=True)
100 | msg = converter.latex_to_text(msg)
101 |
102 | # do no change code blocks to smart quotes, this will break the markdown
103 | # parser.
104 | msg = msg.replace("“", "``")
105 |
106 | # Restore the code blocks and inline code at the markers
107 | for code_block in code_blocks:
108 | msg = msg.replace("\0CODE_BLOCK\0", code_block, 1)
109 | for code_inline in code_inlines:
110 | msg = msg.replace("\0CODE_INLINE\0", code_inline, 1)
111 |
112 | return msg
113 |
114 |
115 | def detect_and_format_message(msg, cutoff=None, theme=None):
116 | # convert any latex markup to ASCII.
117 | msg = format_latex(msg)
118 |
119 | if cutoff and len(msg) > cutoff:
120 | msg = "... **text shortened** ... " + msg[-cutoff:]
121 | return msg
122 | elif contains_json(msg):
123 | utils.debug(detected="json")
124 | return JSON(extract_json(msg))
125 | elif looks_like_markdown(msg):
126 | utils.debug(detected="markdown")
127 | theme = "monokai" if theme is None else theme
128 | return Markdown(msg,code_theme=theme)
129 | else:
130 | utils.debug(detected="regular")
131 | return msg
132 |
133 |
134 | def extract_json_lists(str_lists, flatten=False):
135 | lists = [json.loads(extract_json(x)) for x in str_lists if contains_json(x)]
136 | if flatten:
137 | return json.dumps([item for sublist in lists for item in sublist])
138 | else:
139 | return json.dumps(lists)
140 |
141 |
142 | def contains_block(str):
143 | if extract_block(str):
144 | return True
145 | return False
146 |
147 |
148 | def extract_block(str):
149 | matches = re.findall(r"```[\w]*(.*?)```", str, re.DOTALL)
150 | try:
151 | return sorted(matches, key=lambda x: len(x))[-1].strip()
152 | except IndexError:
153 | return None
154 |
155 |
156 | def looks_like_markdown(str):
157 | """very rudimentary, but avoids making things markdown that shouldn't be"""
158 | md_links = len(re.findall(r"\[[^]]+\]\(https?:\/\/\S+\)", str))
159 | md_text = len(re.findall(r"\s(__|\*\*)(?!\s)(.(?!\1))+(?!\s(?=\1))", str))
160 | md_blocks = len(re.findall(r"```(.*?)```", str, re.DOTALL))
161 | md_inline_blocks = len(re.findall(r"`[^`]+`", str)) - md_blocks
162 |
163 | md_blocks *= 2
164 | utils.debug(
165 | title="counted",
166 | md_links=md_links,
167 | md_text=md_text,
168 | md_inline_blocks=md_inline_blocks,
169 | md_blocks=md_blocks,
170 | )
171 | score = md_links + md_text + md_inline_blocks + md_blocks
172 | return score >= 2
173 |
174 |
175 | def contains_json(str):
176 | try:
177 | extract_json(str)
178 | except ValueError:
179 | return False
180 | return True
181 |
182 |
183 | def extract_json(str):
184 | """
185 | try to extract json from a string that may contain other lines before the json
186 | returns the json as a string or raises a ValueError if no json is found
187 | """
188 | lines_with_idxs = enumerate(str.splitlines())
189 | for idx, line in lines_with_idxs:
190 | if line.strip().startswith("{") or line.strip().startswith("["):
191 | return json.dumps(json.loads(" ".join(str.splitlines()[idx:])))
192 |
193 | raise ValueError("No json in string")
194 |
--------------------------------------------------------------------------------
/chatblade/session.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import re
3 | import os
4 |
5 | from . import storage
6 |
7 |
8 | def list_sessions():
9 | """List names of sessions"""
10 | sess_paths = glob.glob(os.path.join(storage.get_cache_path(), "*.yaml"))
11 | return sorted(
12 | [
13 | re.sub("\\.yaml\\Z", "", os.path.basename(sess_path))
14 | for sess_path in sess_paths
15 | ]
16 | )
17 |
18 |
19 | def rename_session(session, newname):
20 | """renames session
21 | Returns None on success, error string otherwise"""
22 | session_path = storage.get_session_path(session, True)
23 | if not session_path:
24 | return f"session {session} does not exist"
25 | new_session_path = storage.get_session_path(newname, True)
26 | if new_session_path:
27 | return f"session {newname} already exists"
28 | new_session_path = storage.get_session_path(newname)
29 | os.rename(session_path, new_session_path)
30 |
31 |
32 | def delete_session(session):
33 | """deletes a session
34 | Returns None on success, error string otherwise"""
35 | session_path = storage.get_session_path(session, True)
36 | if not session_path:
37 | return f"session {session} does not exist"
38 | os.unlink(session_path)
39 |
--------------------------------------------------------------------------------
/chatblade/storage.py:
--------------------------------------------------------------------------------
1 | """
2 | Handles storage of cache and prompt config directories, as well
3 | as figuring out where to put them on various platforms
4 | """
5 |
6 | import os
7 | import platformdirs
8 | import pickle
9 | import yaml
10 | import random
11 | import string
12 |
13 | from . import errors, chat
14 |
15 | APP_NAME = "chatblade"
16 |
17 |
18 | def make_postfix():
19 | return "." + "".join(random.choices(string.ascii_letters + string.digits, k=10))
20 |
21 |
22 | def get_cache_path(create=True):
23 | """
24 | if ~/.cache is availabe always use ~/.cache/chatblade as the cachefile
25 | otherwise fallback to the platform recommended location and create the directory
26 | e.g. ~/Library/Caches/chatblade on osx
27 | """
28 | os_cache_path = os.path.expanduser("~/.cache")
29 | if not os.path.exists(os_cache_path):
30 | os_cache_path = platformdirs.user_cache_dir(APP_NAME)
31 | if not os.path.exists(os_cache_path):
32 | os.makedirs(os_cache_path)
33 |
34 | cache_path = os.path.join(os_cache_path, APP_NAME)
35 | if create and not os.path.exists(cache_path):
36 | os.makedirs(cache_path)
37 |
38 | return cache_path
39 |
40 |
41 | def get_session_path(session, exists=False):
42 | """get the path of a session file
43 | If exists=True, return None if the path does not exists"""
44 | session_path = os.path.join(get_cache_path(), f"{session}.yaml")
45 | if exists and not os.path.exists(session_path):
46 | return
47 | return session_path
48 |
49 |
50 | def to_cache(messages, session):
51 | """cache the current messages state"""
52 | file_path = get_session_path(session)
53 | file_path_tmp = file_path + make_postfix()
54 | with open(file_path_tmp, "w") as f:
55 | yaml.dump(messages, f)
56 | os.replace(file_path_tmp, file_path)
57 |
58 |
59 | def messages_from_cache(session):
60 | """load messages from session
61 | Return empty list if not exists"""
62 | file_path = get_session_path(session)
63 | if not os.path.exists(file_path):
64 | return []
65 | else:
66 | with open(file_path, "r") as f:
67 | return [chat.Message.import_yaml(m) for m in yaml.load(f, yaml.SafeLoader)]
68 |
69 |
70 | def messages_from_cache_legacy():
71 | """load messages from last state or ChatbladeError if not exists"""
72 | file_path = get_cache_path(False)
73 | if not os.path.exists(file_path):
74 | raise errors.ChatbladeError("No last state cached from which to begin")
75 | else:
76 | with open(file_path, "rb") as f:
77 | return pickle.load(f)
78 |
79 |
80 | def migrate_to_session(session):
81 | """save pre-session last messages to session"""
82 | file_path = get_cache_path(False)
83 | messages = messages_from_cache_legacy()
84 | file_path_tmp = file_path + make_postfix()
85 | # resolve name conflict, but keep old cache file
86 | # until all has gone through fine
87 | os.replace(file_path, file_path_tmp)
88 | to_cache(messages, session)
89 | os.unlink(file_path_tmp)
90 |
91 |
92 | def load_prompt_file(prompt_name):
93 | """
94 | load a prompt configuration by its name
95 | Assumes the user created the ~/.config/chatblade/{prompt_name}
96 | or a file directly by path
97 | """
98 | paths_to_try = [
99 | prompt_name,
100 | os.path.expanduser(os.path.join("~/.config/chatblade", f"{prompt_name}")),
101 | ]
102 | try:
103 | for file_path in paths_to_try:
104 | if os.path.exists(file_path):
105 | with open(file_path, "r") as f:
106 | return f.read()
107 | # fallback legacy
108 | load_prompt_config_legacy_yaml(prompt_name)
109 | except Exception:
110 | locations = "".join(["\n - " + p for p in paths_to_try])
111 | raise errors.ChatbladeError(
112 | f"no prompt {prompt_name} found in any of following locations: {locations}"
113 | )
114 |
115 |
116 | def load_prompt_config_legacy_yaml(prompt_name):
117 | """
118 | LEGACY: keep right now for people that still use yaml
119 | load a prompt configuration by its name
120 | Assumes the user created the {name}.yaml in ~/.config/chatblade
121 | """
122 | path = os.path.expanduser(
123 | os.path.join("~/.config/chatblade", f"{prompt_name}.yaml")
124 | )
125 | try:
126 | with open(path, "r") as f:
127 | return yaml.load(f, Loader=yaml.FullLoader)["system"]
128 | except FileNotFoundError:
129 | raise errors.ChatbladeError(f"Prompt {prompt_name} not found in {path}")
130 |
--------------------------------------------------------------------------------
/chatblade/utils.py:
--------------------------------------------------------------------------------
1 | from rich.pretty import pprint
2 |
3 | CONSOLE_DEBUG_LOGGING = False
4 |
5 | scratch_session = "last"
6 |
7 |
8 | class DotDict(dict):
9 | """dot.notation access to dictionary attributes"""
10 |
11 | __getattr__ = dict.get
12 | __setattr__ = dict.__setitem__
13 | __delattr__ = dict.__delitem__
14 |
15 |
16 | def merge_dicts(dict1, dict2):
17 | """merge 2 dicts with priority from dict2, but only for keys known by dict1"""
18 | merged = {**dict1, **dict2}
19 | merged = {k: v for k, v in merged.items() if v is not None and k in dict1}
20 | return DotDict(merged)
21 |
22 |
23 | def debug(title=None, **kwargs):
24 | if CONSOLE_DEBUG_LOGGING:
25 | if title:
26 | pprint({f"{title}": kwargs})
27 | else:
28 | pprint(kwargs)
29 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | build-backend = "setuptools.build_meta"
3 | requires = ["setuptools", "wheel"]
4 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | openai==1.35.15
2 | platformdirs==4.2.2
3 | pylatexenc==2.10
4 | PyYAML==6.0.1
5 | rich==13.7.1
6 | tiktoken==0.8.0
7 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = chatblade
3 | version = 0.7.0
4 | description = CLI Swiss Army Knife for ChatGPT
5 | long_description = file: README.md
6 | long_description_content_type=text/markdown
7 | license_file = LICENSE
8 | url = https://github.com/npiv/chatblade
9 | keywords = chatblade chatgpt cli python
10 | project_urls =
11 | Documentation = https://github.com/npiv/chatblade
12 |
13 | [options]
14 | packages = chatblade
15 | python_requires = >=3.8
16 | install_requires =
17 | openai~=1.35.15
18 | tiktoken~=0.8.0
19 | rich~=13.7.1
20 | PyYAML~=6.0.1
21 | platformdirs~=4.2.2
22 | pylatexenc==2.10
23 |
24 | [options.entry_points]
25 | console_scripts =
26 | chatblade = chatblade.__main__:main
27 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup()
4 |
--------------------------------------------------------------------------------