├── LICENSE ├── README.md ├── amd ├── build │ ├── lib.min.js │ ├── lib.min.js.map │ ├── settings.min.js │ └── settings.min.js.map └── src │ ├── lib.js │ └── settings.js ├── api ├── completion.php └── thread.php ├── block_openai_chat.php ├── classes ├── completion.php ├── completion │ ├── assistant.php │ ├── azure.php │ └── chat.php ├── privacy │ └── provider.php └── report.php ├── db ├── access.php ├── install.xml └── upgrade.php ├── edit_form.php ├── lang └── en │ └── block_openai_chat.php ├── lib.php ├── pix ├── arrow-right.svg ├── arrow-up-right-from-square.svg └── refresh.svg ├── report.php ├── settings.php ├── styles.css ├── templates ├── control_bar.mustache └── report_page.mustache └── version.php /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # moodle-block_openai_chat 2 | 3 | 4 | 5 | ### GPT powered AI chat block for Moodle 6 | 7 | This block allows your Moodle users to get 24/7 chat support via OpenAI's GPT AI. The block offers multiple options for customizing the persona of the AI and the prompt it is given, in order to influence the text it outputs. 8 | 9 | To get started, create an OpenAI account [here](https://openai.com/api/). **This plugin requries a commercial subscription via a paid OpenAI account. For more information on purchasing a subscription, please see the aforementioned link. Once a paid account is created, all you need to do is add the API key to the plugin settings.** 10 | 11 | This plugin supports both the [Chat API](https://platform.openai.com/docs/guides/chat) and the [Assistant API](https://platform.openai.com/docs/assistants/overview). 12 | 13 | # Global block settings 14 | 15 | The global block settings can be found by going to Site Administration > Plugins > Blocks > OpenAI Chat Block. The options are: 16 | - **OpenAI API Key:** This is where you add the API key given to you by OpenAI 17 | - **API Type:** The plugin can only use either the Chat API or the Assistant API globally; this selector allows an admin to switch between which API is active. The rest of the settings on this page will change based on which is selected. 18 | - **Restrict chat usage to logged-in users:** If this box is checked, only logged-in users will be able to use the chat box. 19 | - **Assistant name:** When the Chat API is enabled, the AI will use this name for itself in the conversation. It is also always used for the UI headings in the chat window. 20 | - **User name:** When the Chat API is enabled, the AI will use this name for the user in the conversation. Both this and the above option can be used to influence the persona and responses of the AI. It is also always used for the UI headings in the chat window. 21 | - **Enable logging:** Checking this box will record all messages sent by users along with the AI response. When logging is enabled, a recording icon is displayed in the block to indicate to users that their messages are being saved. Interactions with the AI can be found at Site Administration > Reports > OpenAI Chat Logs. 22 | 23 | ### Assistant API settings 24 | These settings only appear when "Assistant" is chosen as the API Type 25 | - **Assistant:** Which assistant to set as the global default. The list is pulled from your OpenAI account, and can be changed at a per-block level if instance-level settings are enabled. 26 | - **Persist conversations:** If this is enabled, a user's conversations will be carried between page loads within the same context. For example, a user can start a conversation with the assistant on a main course page, and then refresh the page or navigate to another course page that contains the same block instance, and continue the same conversation. A block instance in a different context, such as the Dashboard, will not load the same conversation, however. 27 | 28 | ### Chat API settings 29 | These settings only appear when "Chat" is chosen as the API Type 30 | - **Completion prompt:** Here you can edit the text added to the top of the conversation in order to influence the AI's persona and responses 31 | - **Source of truth:** Here you can add a list of questions and answers that the AI will use to accurately respond to queries. Anything added here in the SoT at the plugin level will be applied to every block instance on the site. 32 | There is also an "Advanced" section that allows a user to fine-tune the AI's parameters. Please see OpenAI's documentation for more information on these options. 33 | 34 | ### Advanced 35 | These are extra, advanced parameters to adjust the behavior of the model 36 | - **Instance-level settings:** Checking this box will allow anybody that can add a block to adjust all settings at a per-block level. Enabling this could incur extra charges. 37 | - For more information on advanced settings, please see OpenAI documentation. 38 | 39 | ## Individual block settings 40 | 41 | There are a few settings that can be changed on a per-block basis. You can access these settings by entering editing mode on your site and clicking the gear on the block, and then going to "Configure OpenAI Chat Block" 42 | 43 | - **Block title:** The title for this block 44 | - **Show labels:** Whether or not the names chosen for "Assistant name" and "User name" should appear in the chat UI 45 | - **Source of Truth:** (Only available with Chat API) Here you can add a list of questions and answers that the AI will use to accurately respond to queries at the block instance level. Information provided here will only apply to this specific block. 46 | - **Custom Instructions:** (Only available with Assistant API) The instructions for the given assistant can be overridden on a per-block basis here. 47 | 48 | If "Instance-level settings" is checked in the global block settings, the following extra settings will also be available: 49 | 50 | - **Assistant name:** When the Chat API is enabled, the AI will use this name for itself in the conversation. It is also always used for the UI headings in the chat window. 51 | - **User name:** When the Chat API is enabled, the AI will use this name for the user in the conversation. Both this and the above option can be used to influence the persona and responses of the AI. It is also always used for the UI headings in the chat window. 52 | - **Completion prompt:** (Only available with Chat API) This allows a completion prompt to be set per-block 53 | - **Assistant:** (Only available with Assistant API) Which assistant to use for this block. The list is pulled from the OpenAI account corresponding to the API key set on this block instance (or globally if not specified for this specific block). 54 | - **Persist conversations:** (Only available with Assistant API) This can be used to enable or disable this feature at a per-block level. See above for more information on this feature. 55 | - **Advanced:** These are extra, advanced parameters to adjust the behavior of the model 56 | - **OpenAI API Key:** This allows a separate API key to be used on individual block instances 57 | - For more information on advanced settings, please see OpenAI documentation. 58 | 59 | Note that any instance-level settings that are blank will default to the global block settings. 60 | 61 | # Using the Assistant API 62 | Assistants can be managed in your OpenAI account [here](https://platform.openai.com/assistants). The plugin will pull from your list of assistants to allow you to select the one you want to use. If an API key is set at the per-block level, the list of assistants will be pulled from the given account instead of the default. 63 | 64 | # Using the Chat API 65 | 66 | ## Source of truth 67 | 68 | Although the AI is very capable out-of-the-box, if it doesn't know the answer to a question, it is more likely to confidently give incorrect information than to refuse to answer. The plugin provides a text area at both the *block instance* level as well as the *plugin* level where teachers or administrators can include a list of questions and answers that the AI will ingest before generating a completion; as a result, the AI is more likely to provide accurate information when a submitted query is similar to the questions it has been given direct answers to. For example, an AI that hasn't been provided any extra information may respond to the query "What color is the car?" with a random color, such as red. However, if the following is included in the source of truth box: 69 | ``` 70 | Q: What color is the car? 71 | A: The car is blue. 72 | ``` 73 | the AI will then respond to the question "What color is the car?" with the exact answer provided, "The car is blue." The AI will also still answer accurately if the question is asked in a different way; for example, a user might ask, "What color is the apple?" "What color is the forest?" and finally, "and what about the car?" The AI will correctly identify the apple, the forest, and the car as red, green, and blue, respectively. 74 | 75 | ## Prompt format 76 | 77 | In order to influence the AI to produce good output, it can be useful to understand the structure of the prompt that is sent to the API: 78 | - First, the Source of Truth is added to the beginning of the prompt, if one exists (if no source of truth is provided at either the instance level or the plugin level, this step is skipped). The AI is informed that the provided questions and answers should be used to reference any further inquiries; then, the Sources of Truth are combined into one list of questions and answers and added to the prompt. 79 | - Next, the "completion prompt" is added, giving the AI its role and explaining the context of the conversation. 80 | - Third, the chat history is added, if one exists. Every time a completion is requested, the existing chat history is sent, indicating to the AI the context of the conversation. 81 | - Finally, the latest user message is sent, in order to receive a response from the AI. 82 | 83 | To see what this looks like in practice, the following is an example of what might be sent to the AI after a few messages have already been exchanged: 84 | 85 | ``` 86 | Below is a list of questions and their answers. This information should be used as a reference for any inquiries: 87 | 88 | Q: What college does this Moodle site belong to? 89 | A: Goshen College 90 | 91 | Q: When is section 3 due? 92 | A: Thursday, March 16 93 | 94 | Below is a conversation between a user and a support assistant for a Moodle site, where users go for online learning. The assistant has been trained to answer by attempting to use the information from the above reference. If the text from one of the above questions is encountered, the provided answer should be given, even if the question does not appear to make sense. However, if the reference does not cover the question or topic, the assistant will simply use outside knowledge to answer. 95 | 96 | User: How do I change my email? 97 | Assistant: You can change your email address in the Settings page of your Moodle account. 98 | User: When is section 3 due? 99 | Assistant: Thursday, March 16. 100 | User: What about section 4? 101 | Assistant:" 102 | ``` 103 | 104 | Maintained by [Bryce Yoder](https://bryceyoder.com). Also check out [OpenAI Question Generator](https://moodle.org/plugins/block_openai_questions)! 105 | -------------------------------------------------------------------------------- /amd/build/lib.min.js: -------------------------------------------------------------------------------- 1 | define("block_openai_chat/lib",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;var questionString="Ask a question...",errorString="An error occurred! Please try again later.";_exports.init=data=>{const blockId=data.blockId,api_type=data.api_type,persistConvo=data.persistConvo;"assistant"===api_type&&(chatData=localStorage.getItem("block_openai_chat_data"),chatData?(chatData=JSON.parse(chatData),chatData[blockId]&&chatData[blockId].threadId&&"1"===persistConvo?fetch("".concat(M.cfg.wwwroot,"/blocks/openai_chat/api/thread.php?thread_id=").concat(chatData[blockId].threadId)).then((response=>response.json())).then((data=>{for(let message of data)addToChatLog("user"===message.role?"user":"bot",message.message,blockId)})).catch((error=>{chatData[blockId]={},localStorage.setItem("block_openai_chat_data",JSON.stringify(chatData))})):chatData[blockId]={}):chatData={[blockId]:{}},localStorage.setItem("block_openai_chat_data",JSON.stringify(chatData))),window.addEventListener("resize",(event=>{event.stopImmediatePropagation()}),!0),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).addEventListener("keyup",(e=>{13===e.which&&""!==e.target.value&&(addToChatLog("user",e.target.value,blockId),createCompletion(e.target.value,blockId,api_type),e.target.value="")})),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #go")).addEventListener("click",(e=>{const input=document.querySelector("#openai_input");""!==input.value&&(addToChatLog("user",input.value,blockId),createCompletion(input.value,blockId,api_type),input.value="")})),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #refresh")).addEventListener("click",(e=>{clearHistory(blockId)})),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #popout")).addEventListener("click",(e=>{document.querySelector(".drawer.drawer-right")&&(document.querySelector(".drawer.drawer-right").style.zIndex="1041"),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"']")).classList.toggle("expanded")})),require(["core/str"],(function(str){str.get_strings([{key:"askaquestion",component:"block_openai_chat"},{key:"erroroccurred",component:"block_openai_chat"}]).then((results=>{questionString=results[0],errorString=results[1]}))}))};const addToChatLog=(type,message,blockId)=>{let messageContainer=document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_chat_log"));const messageElem=document.createElement("div");messageElem.classList.add("openai_message");for(let className of type.split(" "))messageElem.classList.add(className);const messageText=document.createElement("span");messageText.innerHTML=message,messageElem.append(messageText),messageContainer.append(messageElem),messageText.offsetWidth&&(messageElem.style.width=messageText.offsetWidth+40+"px"),messageContainer.scrollTop=messageContainer.scrollHeight,messageContainer.closest(".block_openai_chat > div").scrollTop=messageContainer.scrollHeight},clearHistory=blockId=>{chatData=localStorage.getItem("block_openai_chat_data"),chatData&&(chatData=JSON.parse(chatData),chatData[blockId]&&(chatData[blockId]={},localStorage.setItem("block_openai_chat_data",JSON.stringify(chatData)))),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_chat_log")).innerHTML=""},createCompletion=(message,blockId,api_type)=>{let chatData,threadId=null;"assistant"===api_type&&(chatData=localStorage.getItem("block_openai_chat_data"),chatData?(chatData=JSON.parse(chatData),chatData[blockId]&&(threadId=chatData[blockId].threadId||null)):chatData={[blockId]:{}});const history=buildTranscript(blockId);document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #control_bar")).classList.add("disabled"),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).classList.remove("error"),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).placeholder=questionString,document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).blur(),addToChatLog("bot loading","...",blockId),fetch("".concat(M.cfg.wwwroot,"/blocks/openai_chat/api/completion.php"),{method:"POST",body:JSON.stringify({message:message,history:history,blockId:blockId,threadId:threadId})}).then((response=>{let messageContainer=document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_chat_log"));if(messageContainer.removeChild(messageContainer.lastElementChild),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #control_bar")).classList.remove("disabled"),response.ok)return response.json();throw Error(response.statusText)})).then((data=>{try{addToChatLog("bot",data.message,blockId),data.thread_id&&(chatData[blockId].threadId=data.thread_id,localStorage.setItem("block_openai_chat_data",JSON.stringify(chatData)))}catch(error){console.log(error),addToChatLog("bot",data.error.message,blockId)}document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).focus()})).catch((error=>{console.log(error),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).classList.add("error"),document.querySelector(".block_openai_chat[data-instance-id='".concat(blockId,"'] #openai_input")).placeholder=errorString}))},buildTranscript=blockId=>{let transcript=[];return document.querySelectorAll(".block_openai_chat[data-instance-id='".concat(blockId,"'] .openai_message")).forEach(((message,index)=>{if(index===document.querySelectorAll(".block_openai_chat[data-instance-id='".concat(blockId,"'] .openai_message")).length-1)return;let user=userName;message.classList.contains("bot")&&(user=assistantName),transcript.push({user:user,message:message.innerText})})),transcript}})); 2 | 3 | //# sourceMappingURL=lib.min.js.map -------------------------------------------------------------------------------- /amd/build/lib.min.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"lib.min.js","sources":["../src/lib.js"],"sourcesContent":["var questionString = 'Ask a question...'\nvar errorString = 'An error occurred! Please try again later.'\n\nexport const init = (data) => {\n const blockId = data['blockId']\n const api_type = data['api_type']\n const persistConvo = data['persistConvo']\n\n // Initialize local data storage if necessary\n // If a thread ID exists for this block, make an API request to get existing messages\n if (api_type === 'assistant') {\n chatData = localStorage.getItem(\"block_openai_chat_data\")\n if (chatData) {\n chatData = JSON.parse(chatData)\n if (chatData[blockId] && chatData[blockId]['threadId'] && persistConvo === \"1\") {\n fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/thread.php?thread_id=${chatData[blockId]['threadId']}`)\n .then(response => response.json())\n .then(data => {\n for (let message of data) {\n addToChatLog(message.role === 'user' ? 'user' : 'bot', message.message, blockId)\n }\n })\n // Some sort of error in the API call. Probably the thread no longer exists, so lets reset it\n .catch(error => {\n chatData[blockId] = {}\n localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n })\n // The block ID doesn't exist in the chat data object, so let's create it\n } else {\n chatData[blockId] = {}\n }\n // We don't even have a chat data object, so we'll create one\n } else {\n chatData = {[blockId]: {}}\n }\n localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n }\n\n // Prevent sidebar from closing when osk pops up (hack for MDL-77957)\n window.addEventListener('resize', event => {\n event.stopImmediatePropagation();\n }, true);\n\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).addEventListener('keyup', e => {\n if (e.which === 13 && e.target.value !== \"\") {\n addToChatLog('user', e.target.value, blockId)\n createCompletion(e.target.value, blockId, api_type)\n e.target.value = ''\n }\n })\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #go`).addEventListener('click', e => {\n const input = document.querySelector('#openai_input')\n if (input.value !== \"\") {\n addToChatLog('user', input.value, blockId)\n createCompletion(input.value, blockId, api_type)\n input.value = ''\n }\n })\n\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #refresh`).addEventListener('click', e => {\n clearHistory(blockId)\n })\n\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #popout`).addEventListener('click', e => {\n if (document.querySelector('.drawer.drawer-right')) {\n document.querySelector('.drawer.drawer-right').style.zIndex = '1041'\n }\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}']`).classList.toggle('expanded')\n })\n\n require(['core/str'], function(str) {\n var strings = [\n {\n key: 'askaquestion',\n component: 'block_openai_chat'\n },\n {\n key: 'erroroccurred',\n component: 'block_openai_chat'\n },\n ];\n str.get_strings(strings).then((results) => {\n questionString = results[0];\n errorString = results[1];\n });\n });\n}\n\n/**\n * Add a message to the chat UI\n * @param {string} type Which side of the UI the message should be on. Can be \"user\" or \"bot\"\n * @param {string} message The text of the message to add\n * @param {int} blockId The ID of the block to manipulate\n */\nconst addToChatLog = (type, message, blockId) => {\n let messageContainer = document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`)\n \n const messageElem = document.createElement('div')\n messageElem.classList.add('openai_message')\n for (let className of type.split(' ')) {\n messageElem.classList.add(className)\n }\n\n const messageText = document.createElement('span')\n messageText.innerHTML = message\n messageElem.append(messageText)\n\n messageContainer.append(messageElem)\n if (messageText.offsetWidth) {\n messageElem.style.width = (messageText.offsetWidth + 40) + \"px\"\n }\n messageContainer.scrollTop = messageContainer.scrollHeight\n messageContainer.closest('.block_openai_chat > div').scrollTop = messageContainer.scrollHeight\n}\n\n/**\n * Clears the thread ID from local storage and removes the messages from the UI in order to refresh the chat\n */\nconst clearHistory = (blockId) => {\n chatData = localStorage.getItem(\"block_openai_chat_data\")\n if (chatData) {\n chatData = JSON.parse(chatData)\n if (chatData[blockId]) {\n chatData[blockId] = {}\n localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n }\n }\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`).innerHTML = \"\"\n}\n\n/**\n * Makes an API request to get a completion from GPT-3, and adds it to the chat log\n * @param {string} message The text to get a completion for\n * @param {int} blockId The ID of the block this message is being sent from -- used to override settings if necessary\n * @param {string} api_type \"assistant\" | \"chat\" The type of API to use\n */\nconst createCompletion = (message, blockId, api_type) => {\n let threadId = null\n let chatData\n\n // If the type is assistant, attempt to fetch a thread ID\n if (api_type === 'assistant') {\n chatData = localStorage.getItem(\"block_openai_chat_data\")\n if (chatData) {\n chatData = JSON.parse(chatData)\n if (chatData[blockId]) {\n threadId = chatData[blockId]['threadId'] || null\n }\n } else {\n // create the chat data item if necessary\n chatData = {[blockId]: {}}\n }\n } \n\n const history = buildTranscript(blockId)\n\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #control_bar`).classList.add('disabled')\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).classList.remove('error')\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).placeholder = questionString\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).blur()\n addToChatLog('bot loading', '...', blockId);\n\n fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/completion.php`, {\n method: 'POST',\n body: JSON.stringify({\n message: message,\n history: history,\n blockId: blockId,\n threadId: threadId\n })\n })\n .then(response => {\n let messageContainer = document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`)\n messageContainer.removeChild(messageContainer.lastElementChild)\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #control_bar`).classList.remove('disabled')\n\n if (!response.ok) {\n throw Error(response.statusText)\n } else {\n return response.json()\n }\n })\n .then(data => {\n try {\n addToChatLog('bot', data.message, blockId)\n if (data.thread_id) {\n chatData[blockId]['threadId'] = data.thread_id\n localStorage.setItem(\"block_openai_chat_data\", JSON.stringify(chatData));\n }\n } catch (error) {\n console.log(error)\n addToChatLog('bot', data.error.message, blockId)\n }\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).focus()\n })\n .catch(error => {\n console.log(error)\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).classList.add('error')\n document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).placeholder = errorString\n })\n}\n\n/**\n * Using the existing messages in the chat history, create a string that can be used to aid completion\n * @param {int} blockId The block from which to build the history\n * @return {JSONObject} A transcript of the conversation up to this point\n */\nconst buildTranscript = (blockId) => {\n let transcript = []\n document.querySelectorAll(`.block_openai_chat[data-instance-id='${blockId}'] .openai_message`).forEach((message, index) => {\n if (index === document.querySelectorAll(`.block_openai_chat[data-instance-id='${blockId}'] .openai_message`).length - 1) {\n return\n }\n\n let user = userName\n if (message.classList.contains('bot')) {\n user = assistantName\n }\n transcript.push({\"user\": user, \"message\": message.innerText})\n })\n\n return transcript\n}\n"],"names":["questionString","errorString","data","blockId","api_type","persistConvo","chatData","localStorage","getItem","JSON","parse","fetch","M","cfg","wwwroot","then","response","json","message","addToChatLog","role","catch","error","setItem","stringify","window","addEventListener","event","stopImmediatePropagation","document","querySelector","e","which","target","value","createCompletion","input","clearHistory","style","zIndex","classList","toggle","require","str","get_strings","key","component","results","type","messageContainer","messageElem","createElement","add","className","split","messageText","innerHTML","append","offsetWidth","width","scrollTop","scrollHeight","closest","threadId","history","buildTranscript","remove","placeholder","blur","method","body","removeChild","lastElementChild","ok","Error","statusText","thread_id","console","log","focus","transcript","querySelectorAll","forEach","index","length","user","userName","contains","assistantName","push","innerText"],"mappings":"gJAAIA,eAAiB,oBACjBC,YAAc,2DAEGC,aACXC,QAAUD,KAAI,QACdE,SAAWF,KAAI,SACfG,aAAeH,KAAI,aAIR,cAAbE,WACAE,SAAWC,aAAaC,QAAQ,0BAC5BF,UACAA,SAAWG,KAAKC,MAAMJ,UAClBA,SAASH,UAAYG,SAASH,SAAT,UAAkD,MAAjBE,aACtDM,gBAASC,EAAEC,IAAIC,gEAAuDR,SAASH,SAAT,WACrEY,MAAKC,UAAYA,SAASC,SAC1BF,MAAKb,WACG,IAAIgB,WAAWhB,KAChBiB,aAA8B,SAAjBD,QAAQE,KAAkB,OAAS,MAAOF,QAAQA,QAASf,YAI/EkB,OAAMC,QACHhB,SAASH,SAAW,GACpBI,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,cAIlEA,SAASH,SAAW,IAIxBG,SAAW,EAAEH,SAAU,IAE3BI,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,YAIlEmB,OAAOC,iBAAiB,UAAUC,QAC9BA,MAAMC,8BACP,GAEHC,SAASC,6DAAsD3B,6BAA2BuB,iBAAiB,SAASK,IAChG,KAAZA,EAAEC,OAAmC,KAAnBD,EAAEE,OAAOC,QAC3Bf,aAAa,OAAQY,EAAEE,OAAOC,MAAO/B,SACrCgC,iBAAiBJ,EAAEE,OAAOC,MAAO/B,QAASC,UAC1C2B,EAAEE,OAAOC,MAAQ,OAGzBL,SAASC,6DAAsD3B,mBAAiBuB,iBAAiB,SAASK,UAChGK,MAAQP,SAASC,cAAc,iBACjB,KAAhBM,MAAMF,QACNf,aAAa,OAAQiB,MAAMF,MAAO/B,SAClCgC,iBAAiBC,MAAMF,MAAO/B,QAASC,UACvCgC,MAAMF,MAAQ,OAItBL,SAASC,6DAAsD3B,wBAAsBuB,iBAAiB,SAASK,IAC3GM,aAAalC,YAGjB0B,SAASC,6DAAsD3B,uBAAqBuB,iBAAiB,SAASK,IACtGF,SAASC,cAAc,0BACvBD,SAASC,cAAc,wBAAwBQ,MAAMC,OAAS,QAElEV,SAASC,6DAAsD3B,eAAaqC,UAAUC,OAAO,eAGjGC,QAAQ,CAAC,aAAa,SAASC,KAW3BA,IAAIC,YAVU,CACV,CACIC,IAAK,eACLC,UAAW,qBAEf,CACID,IAAK,gBACLC,UAAW,uBAGM/B,MAAMgC,UAC3B/C,eAAiB+C,QAAQ,GACzB9C,YAAc8C,QAAQ,gBAW5B5B,aAAe,CAAC6B,KAAM9B,QAASf,eAC7B8C,iBAAmBpB,SAASC,6DAAsD3B,sCAEhF+C,YAAcrB,SAASsB,cAAc,OAC3CD,YAAYV,UAAUY,IAAI,sBACrB,IAAIC,aAAaL,KAAKM,MAAM,KAC7BJ,YAAYV,UAAUY,IAAIC,iBAGxBE,YAAc1B,SAASsB,cAAc,QAC3CI,YAAYC,UAAYtC,QACxBgC,YAAYO,OAAOF,aAEnBN,iBAAiBQ,OAAOP,aACpBK,YAAYG,cACZR,YAAYZ,MAAMqB,MAASJ,YAAYG,YAAc,GAAM,MAE/DT,iBAAiBW,UAAYX,iBAAiBY,aAC9CZ,iBAAiBa,QAAQ,4BAA4BF,UAAYX,iBAAiBY,cAMhFxB,aAAgBlC,UAClBG,SAAWC,aAAaC,QAAQ,0BAC5BF,WACAA,SAAWG,KAAKC,MAAMJ,UAClBA,SAASH,WACTG,SAASH,SAAW,GACpBI,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,aAGtEuB,SAASC,6DAAsD3B,gCAA8BqD,UAAY,IASvGrB,iBAAmB,CAACjB,QAASf,QAASC,gBAEpCE,SADAyD,SAAW,KAIE,cAAb3D,WACAE,SAAWC,aAAaC,QAAQ,0BAC5BF,UACAA,SAAWG,KAAKC,MAAMJ,UAClBA,SAASH,WACT4D,SAAWzD,SAASH,SAAT,UAAiC,OAIhDG,SAAW,EAAEH,SAAU,WAIzB6D,QAAUC,gBAAgB9D,SAEhC0B,SAASC,6DAAsD3B,4BAA0BqC,UAAUY,IAAI,YACvGvB,SAASC,6DAAsD3B,6BAA2BqC,UAAU0B,OAAO,SAC3GrC,SAASC,6DAAsD3B,6BAA2BgE,YAAcnE,eACxG6B,SAASC,6DAAsD3B,6BAA2BiE,OAC1FjD,aAAa,cAAe,MAAOhB,SAEnCQ,gBAASC,EAAEC,IAAIC,kDAAiD,CAC5DuD,OAAQ,OACRC,KAAM7D,KAAKe,UAAU,CACjBN,QAASA,QACT8C,QAASA,QACT7D,QAASA,QACT4D,SAAUA,aAGjBhD,MAAKC,eACEiC,iBAAmBpB,SAASC,6DAAsD3B,mCACtF8C,iBAAiBsB,YAAYtB,iBAAiBuB,kBAC9C3C,SAASC,6DAAsD3B,4BAA0BqC,UAAU0B,OAAO,YAErGlD,SAASyD,UAGHzD,SAASC,aAFVyD,MAAM1D,SAAS2D,eAK5B5D,MAAKb,WAEEiB,aAAa,MAAOjB,KAAKgB,QAASf,SAC9BD,KAAK0E,YACLtE,SAASH,SAAT,SAAgCD,KAAK0E,UACrCrE,aAAagB,QAAQ,yBAA0Bd,KAAKe,UAAUlB,YAEpE,MAAOgB,OACLuD,QAAQC,IAAIxD,OACZH,aAAa,MAAOjB,KAAKoB,MAAMJ,QAASf,SAE5C0B,SAASC,6DAAsD3B,6BAA2B4E,WAE7F1D,OAAMC,QACHuD,QAAQC,IAAIxD,OACZO,SAASC,6DAAsD3B,6BAA2BqC,UAAUY,IAAI,SACxGvB,SAASC,6DAAsD3B,6BAA2BgE,YAAclE,gBAS1GgE,gBAAmB9D,cACjB6E,WAAa,UACjBnD,SAASoD,gEAAyD9E,+BAA6B+E,SAAQ,CAAChE,QAASiE,YACzGA,QAAUtD,SAASoD,gEAAyD9E,+BAA6BiF,OAAS,aAIlHC,KAAOC,SACPpE,QAAQsB,UAAU+C,SAAS,SAC3BF,KAAOG,eAEXR,WAAWS,KAAK,MAASJ,aAAiBnE,QAAQwE,eAG/CV"} -------------------------------------------------------------------------------- /amd/build/settings.min.js: -------------------------------------------------------------------------------- 1 | define("block_openai_chat/settings",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.init=void 0;_exports.init=()=>{var _document$querySelect;null===(_document$querySelect=document.querySelector("#id_s_block_openai_chat_type"))||void 0===_document$querySelect||_document$querySelect.addEventListener("change",(e=>{document.querySelector(".settingsform").classList.add("block_openai_chat"),document.querySelector(".settingsform").classList.add("disabled"),document.querySelector('.settingsform button[type="submit"]').click()}))}})); 2 | 3 | //# sourceMappingURL=settings.min.js.map -------------------------------------------------------------------------------- /amd/build/settings.min.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"settings.min.js","sources":["../src/settings.js"],"sourcesContent":["export const init = () => {\n document.querySelector('#id_s_block_openai_chat_type')?.addEventListener('change', e => {\n // If the API Type is changed, programmatically hit save so the page automatically reloads with the new options\n document.querySelector('.settingsform').classList.add('block_openai_chat')\n document.querySelector('.settingsform').classList.add('disabled')\n document.querySelector('.settingsform button[type=\"submit\"]').click()\n })\n}"],"names":["document","querySelector","addEventListener","e","classList","add","click"],"mappings":"+JAAoB,6DAChBA,SAASC,cAAc,wFAAiCC,iBAAiB,UAAUC,IAE/EH,SAASC,cAAc,iBAAiBG,UAAUC,IAAI,qBACtDL,SAASC,cAAc,iBAAiBG,UAAUC,IAAI,YACtDL,SAASC,cAAc,uCAAuCK"} -------------------------------------------------------------------------------- /amd/src/lib.js: -------------------------------------------------------------------------------- 1 | var questionString = 'Ask a question...' 2 | var errorString = 'An error occurred! Please try again later.' 3 | 4 | export const init = (data) => { 5 | const blockId = data['blockId'] 6 | const api_type = data['api_type'] 7 | const persistConvo = data['persistConvo'] 8 | 9 | // Initialize local data storage if necessary 10 | // If a thread ID exists for this block, make an API request to get existing messages 11 | if (api_type === 'assistant') { 12 | chatData = localStorage.getItem("block_openai_chat_data") 13 | if (chatData) { 14 | chatData = JSON.parse(chatData) 15 | if (chatData[blockId] && chatData[blockId]['threadId'] && persistConvo === "1") { 16 | fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/thread.php?thread_id=${chatData[blockId]['threadId']}`) 17 | .then(response => response.json()) 18 | .then(data => { 19 | for (let message of data) { 20 | addToChatLog(message.role === 'user' ? 'user' : 'bot', message.message, blockId) 21 | } 22 | }) 23 | // Some sort of error in the API call. Probably the thread no longer exists, so lets reset it 24 | .catch(error => { 25 | chatData[blockId] = {} 26 | localStorage.setItem("block_openai_chat_data", JSON.stringify(chatData)); 27 | }) 28 | // The block ID doesn't exist in the chat data object, so let's create it 29 | } else { 30 | chatData[blockId] = {} 31 | } 32 | // We don't even have a chat data object, so we'll create one 33 | } else { 34 | chatData = {[blockId]: {}} 35 | } 36 | localStorage.setItem("block_openai_chat_data", JSON.stringify(chatData)); 37 | } 38 | 39 | // Prevent sidebar from closing when osk pops up (hack for MDL-77957) 40 | window.addEventListener('resize', event => { 41 | event.stopImmediatePropagation(); 42 | }, true); 43 | 44 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).addEventListener('keyup', e => { 45 | if (e.which === 13 && e.target.value !== "") { 46 | addToChatLog('user', e.target.value, blockId) 47 | createCompletion(e.target.value, blockId, api_type) 48 | e.target.value = '' 49 | } 50 | }) 51 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #go`).addEventListener('click', e => { 52 | const input = document.querySelector('#openai_input') 53 | if (input.value !== "") { 54 | addToChatLog('user', input.value, blockId) 55 | createCompletion(input.value, blockId, api_type) 56 | input.value = '' 57 | } 58 | }) 59 | 60 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #refresh`).addEventListener('click', e => { 61 | clearHistory(blockId) 62 | }) 63 | 64 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #popout`).addEventListener('click', e => { 65 | if (document.querySelector('.drawer.drawer-right')) { 66 | document.querySelector('.drawer.drawer-right').style.zIndex = '1041' 67 | } 68 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}']`).classList.toggle('expanded') 69 | }) 70 | 71 | require(['core/str'], function(str) { 72 | var strings = [ 73 | { 74 | key: 'askaquestion', 75 | component: 'block_openai_chat' 76 | }, 77 | { 78 | key: 'erroroccurred', 79 | component: 'block_openai_chat' 80 | }, 81 | ]; 82 | str.get_strings(strings).then((results) => { 83 | questionString = results[0]; 84 | errorString = results[1]; 85 | }); 86 | }); 87 | } 88 | 89 | /** 90 | * Add a message to the chat UI 91 | * @param {string} type Which side of the UI the message should be on. Can be "user" or "bot" 92 | * @param {string} message The text of the message to add 93 | * @param {int} blockId The ID of the block to manipulate 94 | */ 95 | const addToChatLog = (type, message, blockId) => { 96 | let messageContainer = document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`) 97 | 98 | const messageElem = document.createElement('div') 99 | messageElem.classList.add('openai_message') 100 | for (let className of type.split(' ')) { 101 | messageElem.classList.add(className) 102 | } 103 | 104 | const messageText = document.createElement('span') 105 | messageText.innerHTML = message 106 | messageElem.append(messageText) 107 | 108 | messageContainer.append(messageElem) 109 | if (messageText.offsetWidth) { 110 | messageElem.style.width = (messageText.offsetWidth + 40) + "px" 111 | } 112 | messageContainer.scrollTop = messageContainer.scrollHeight 113 | messageContainer.closest('.block_openai_chat > div').scrollTop = messageContainer.scrollHeight 114 | } 115 | 116 | /** 117 | * Clears the thread ID from local storage and removes the messages from the UI in order to refresh the chat 118 | */ 119 | const clearHistory = (blockId) => { 120 | chatData = localStorage.getItem("block_openai_chat_data") 121 | if (chatData) { 122 | chatData = JSON.parse(chatData) 123 | if (chatData[blockId]) { 124 | chatData[blockId] = {} 125 | localStorage.setItem("block_openai_chat_data", JSON.stringify(chatData)); 126 | } 127 | } 128 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`).innerHTML = "" 129 | } 130 | 131 | /** 132 | * Makes an API request to get a completion from GPT-3, and adds it to the chat log 133 | * @param {string} message The text to get a completion for 134 | * @param {int} blockId The ID of the block this message is being sent from -- used to override settings if necessary 135 | * @param {string} api_type "assistant" | "chat" The type of API to use 136 | */ 137 | const createCompletion = (message, blockId, api_type) => { 138 | let threadId = null 139 | let chatData 140 | 141 | // If the type is assistant, attempt to fetch a thread ID 142 | if (api_type === 'assistant') { 143 | chatData = localStorage.getItem("block_openai_chat_data") 144 | if (chatData) { 145 | chatData = JSON.parse(chatData) 146 | if (chatData[blockId]) { 147 | threadId = chatData[blockId]['threadId'] || null 148 | } 149 | } else { 150 | // create the chat data item if necessary 151 | chatData = {[blockId]: {}} 152 | } 153 | } 154 | 155 | const history = buildTranscript(blockId) 156 | 157 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #control_bar`).classList.add('disabled') 158 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).classList.remove('error') 159 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).placeholder = questionString 160 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).blur() 161 | addToChatLog('bot loading', '...', blockId); 162 | 163 | fetch(`${M.cfg.wwwroot}/blocks/openai_chat/api/completion.php`, { 164 | method: 'POST', 165 | body: JSON.stringify({ 166 | message: message, 167 | history: history, 168 | blockId: blockId, 169 | threadId: threadId 170 | }) 171 | }) 172 | .then(response => { 173 | let messageContainer = document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_chat_log`) 174 | messageContainer.removeChild(messageContainer.lastElementChild) 175 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #control_bar`).classList.remove('disabled') 176 | 177 | if (!response.ok) { 178 | throw Error(response.statusText) 179 | } else { 180 | return response.json() 181 | } 182 | }) 183 | .then(data => { 184 | try { 185 | addToChatLog('bot', data.message, blockId) 186 | if (data.thread_id) { 187 | chatData[blockId]['threadId'] = data.thread_id 188 | localStorage.setItem("block_openai_chat_data", JSON.stringify(chatData)); 189 | } 190 | } catch (error) { 191 | console.log(error) 192 | addToChatLog('bot', data.error.message, blockId) 193 | } 194 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).focus() 195 | }) 196 | .catch(error => { 197 | console.log(error) 198 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).classList.add('error') 199 | document.querySelector(`.block_openai_chat[data-instance-id='${blockId}'] #openai_input`).placeholder = errorString 200 | }) 201 | } 202 | 203 | /** 204 | * Using the existing messages in the chat history, create a string that can be used to aid completion 205 | * @param {int} blockId The block from which to build the history 206 | * @return {JSONObject} A transcript of the conversation up to this point 207 | */ 208 | const buildTranscript = (blockId) => { 209 | let transcript = [] 210 | document.querySelectorAll(`.block_openai_chat[data-instance-id='${blockId}'] .openai_message`).forEach((message, index) => { 211 | if (index === document.querySelectorAll(`.block_openai_chat[data-instance-id='${blockId}'] .openai_message`).length - 1) { 212 | return 213 | } 214 | 215 | let user = userName 216 | if (message.classList.contains('bot')) { 217 | user = assistantName 218 | } 219 | transcript.push({"user": user, "message": message.innerText}) 220 | }) 221 | 222 | return transcript 223 | } 224 | -------------------------------------------------------------------------------- /amd/src/settings.js: -------------------------------------------------------------------------------- 1 | export const init = () => { 2 | document.querySelector('#id_s_block_openai_chat_type')?.addEventListener('change', e => { 3 | // If the API Type is changed, programmatically hit save so the page automatically reloads with the new options 4 | document.querySelector('.settingsform').classList.add('block_openai_chat') 5 | document.querySelector('.settingsform').classList.add('disabled') 6 | document.querySelector('.settingsform button[type="submit"]').click() 7 | }) 8 | } -------------------------------------------------------------------------------- /api/completion.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * API endpoint for retrieving GPT completion 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | use \block_openai_chat\completion; 26 | 27 | require_once('../../../config.php'); 28 | require_once($CFG->libdir . '/filelib.php'); 29 | require_once($CFG->dirroot . '/blocks/openai_chat/lib.php'); 30 | 31 | global $DB, $PAGE; 32 | 33 | if (get_config('block_openai_chat', 'restrictusage') !== "0") { 34 | require_login(); 35 | } 36 | 37 | if ($_SERVER['REQUEST_METHOD'] !== 'POST') { 38 | header("Location: $CFG->wwwroot"); 39 | die(); 40 | } 41 | 42 | $body = json_decode(file_get_contents('php://input'), true); 43 | $message = clean_param($body['message'], PARAM_NOTAGS); 44 | $history = clean_param_array($body['history'], PARAM_NOTAGS, true); 45 | $block_id = clean_param($body['blockId'], PARAM_INT, true); 46 | $thread_id = clean_param($body['threadId'], PARAM_NOTAGS, true); 47 | 48 | // So that we're not leaking info to the client like API key, the block makes an API request including its ID 49 | // Then we can look up that specific block to pull out its config data 50 | $instance_record = $DB->get_record('block_instances', ['blockname' => 'openai_chat', 'id' => $block_id], '*'); 51 | $instance = block_instance('openai_chat', $instance_record); 52 | if (!$instance) { 53 | print_error('invalidblockinstance', 'error', $id); 54 | } 55 | 56 | $context = context::instance_by_id($instance_record->parentcontextid); 57 | $PAGE->set_context($context); 58 | 59 | $block_settings = []; 60 | $setting_names = [ 61 | 'sourceoftruth', 62 | 'prompt', 63 | 'instructions', 64 | 'username', 65 | 'assistantname', 66 | 'apikey', 67 | 'model', 68 | 'temperature', 69 | 'maxlength', 70 | 'topp', 71 | 'frequency', 72 | 'presence', 73 | 'assistant' 74 | ]; 75 | foreach ($setting_names as $setting) { 76 | if ($instance->config && property_exists($instance->config, $setting)) { 77 | $block_settings[$setting] = $instance->config->$setting ? $instance->config->$setting : ""; 78 | } else { 79 | $block_settings[$setting] = ""; 80 | } 81 | } 82 | 83 | $engine_class; 84 | $model = get_config('block_openai_chat', 'model'); 85 | $api_type = get_config('block_openai_chat', 'type'); 86 | $engine_class = "\block_openai_chat\completion\\$api_type"; 87 | 88 | $completion = new $engine_class(...[$model, $message, $history, $block_settings, $thread_id]); 89 | $response = $completion->create_completion($PAGE->context); 90 | 91 | // Format the markdown of each completion message into HTML. 92 | $response["message"] = format_text($response["message"], FORMAT_MARKDOWN, ['context' => $context]); 93 | 94 | // Log the message 95 | log_message($message, $response['message'], $context); 96 | 97 | $response = json_encode($response); 98 | echo $response; 99 | -------------------------------------------------------------------------------- /api/thread.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * API endpoint for retrieving thread history 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | require_once('../../../config.php'); 26 | require_once($CFG->libdir . '/filelib.php'); 27 | require_once($CFG->dirroot . '/blocks/openai_chat/lib.php'); 28 | 29 | if (get_config('block_openai_chat', 'restrictusage') !== "0") { 30 | require_login(); 31 | } 32 | 33 | $thread_id = required_param('thread_id', PARAM_NOTAGS); 34 | $apikey = get_config('block_openai_chat', 'apikey'); 35 | 36 | $curl = new \curl(); 37 | $curl->setopt(array( 38 | 'CURLOPT_HTTPHEADER' => array( 39 | 'Authorization: Bearer ' . $apikey, 40 | 'Content-Type: application/json', 41 | 'OpenAI-Beta: assistants=v2' 42 | ), 43 | )); 44 | 45 | $response = $curl->get("https://api.openai.com/v1/threads/$thread_id/messages"); 46 | $response = json_decode($response); 47 | 48 | if (property_exists($response, 'error')) { 49 | throw new \Exception($response->error->message); 50 | } 51 | 52 | $api_response = []; 53 | $message_list = array_reverse($response->data); 54 | 55 | foreach ($message_list as $message) { 56 | array_push($api_response, [ 57 | "id" => $message->id, 58 | "role" => $message->role, 59 | "message" => $message->content[0]->text->value 60 | ]); 61 | } 62 | 63 | $api_response = json_encode($api_response); 64 | echo $api_response; 65 | -------------------------------------------------------------------------------- /block_openai_chat.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Block class 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | class block_openai_chat extends block_base { 26 | public function init() { 27 | $this->title = get_string('openai_chat', 'block_openai_chat'); 28 | } 29 | 30 | public function has_config() { 31 | return true; 32 | } 33 | 34 | function applicable_formats() { 35 | return array('all' => true); 36 | } 37 | 38 | public function specialization() { 39 | if (!empty($this->config->title)) { 40 | $this->title = $this->config->title; 41 | } 42 | } 43 | 44 | public function get_content() { 45 | global $OUTPUT; 46 | global $PAGE; 47 | 48 | if ($this->content !== null) { 49 | return $this->content; 50 | } 51 | 52 | // Send data to front end 53 | $persistconvo = get_config('block_openai_chat', 'persistconvo'); 54 | if (!empty($this->config)) { 55 | $persistconvo = (property_exists($this->config, 'persistconvo') && get_config('block_openai_chat', 'allowinstancesettings')) ? $this->config->persistconvo : $persistconvo; 56 | } 57 | $this->page->requires->js_call_amd('block_openai_chat/lib', 'init', [[ 58 | 'blockId' => $this->instance->id, 59 | 'api_type' => get_config('block_openai_chat', 'type') ? get_config('block_openai_chat', 'type') : 'chat', 60 | 'persistConvo' => $persistconvo 61 | ]]); 62 | 63 | // Determine if name labels should be shown. 64 | $showlabelscss = ''; 65 | if (!empty($this->config) && !$this->config->showlabels) { 66 | $showlabelscss = ' 67 | .openai_message:before { 68 | display: none; 69 | } 70 | .openai_message { 71 | margin-bottom: 0.5rem; 72 | } 73 | '; 74 | } 75 | 76 | // First, fetch the global settings for these (and the defaults if not set) 77 | $assistantname = get_config('block_openai_chat', 'assistantname') ? get_config('block_openai_chat', 'assistantname') : get_string('defaultassistantname', 'block_openai_chat'); 78 | $username = get_config('block_openai_chat', 'username') ? get_config('block_openai_chat', 'username') : get_string('defaultusername', 'block_openai_chat'); 79 | 80 | // Then, override with local settings if available 81 | if (!empty($this->config)) { 82 | $assistantname = (property_exists($this->config, 'assistantname') && $this->config->assistantname) ? $this->config->assistantname : $assistantname; 83 | $username = (property_exists($this->config, 'username') && $this->config->username) ? $this->config->username : $username; 84 | } 85 | $assistantname = format_string($assistantname, true, ['context' => $this->context]); 86 | $username = format_string($username, true, ['context' => $this->context]); 87 | 88 | $this->content = new stdClass; 89 | $this->content->text = ' 90 | 94 | 95 | 104 | 105 |
106 | '; 107 | 108 | if ( 109 | empty(get_config('block_openai_chat', 'apikey')) && 110 | (!get_config('block_openai_chat', 'allowinstancesettings') || empty($this->config->apikey)) 111 | ) { 112 | $this->content->footer = get_string('apikeymissing', 'block_openai_chat'); 113 | } else { 114 | $contextdata = [ 115 | 'logging_enabled' => get_config('block_openai_chat', 'logging'), 116 | 'is_edit_mode' => $PAGE->user_is_editing(), 117 | 'pix_popout' => '/blocks/openai_chat/pix/arrow-up-right-from-square.svg', 118 | 'pix_arrow_right' => '/blocks/openai_chat/pix/arrow-right.svg', 119 | 'pix_refresh' => '/blocks/openai_chat/pix/refresh.svg', 120 | ]; 121 | 122 | $this->content->footer = $OUTPUT->render_from_template('block_openai_chat/control_bar', $contextdata); 123 | } 124 | 125 | return $this->content; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /classes/completion.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Base completion object class 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat; 26 | defined('MOODLE_INTERNAL') || die; 27 | 28 | class completion { 29 | 30 | protected $apikey; 31 | protected $message; 32 | protected $history; 33 | 34 | protected $assistantname; 35 | protected $username; 36 | protected $prompt; 37 | protected $sourceoftruth; 38 | protected $model; 39 | protected $temperature; 40 | protected $maxlength; 41 | protected $topp; 42 | protected $frequency; 43 | protected $presence; 44 | 45 | protected $assistant; 46 | protected $instructions; 47 | 48 | /** 49 | * Initialize all the class properties that we'll need regardless of model 50 | * @param string model: The name of the model we're using 51 | * @param string message: The most recent message sent by the user 52 | * @param array history: An array of objects containing the history of the conversation 53 | * @param string block_settings: An object containing the instance-level settings if applicable 54 | */ 55 | public function __construct($model, $message, $history, $block_settings) { 56 | // Set default values 57 | $this->model = $model; 58 | $this->apikey = get_config('block_openai_chat', 'apikey'); 59 | 60 | // We fetch defaults for both chat and assistant APIs, even though only one can be active at a time 61 | // In the past, multiple different completion classes shared API types, so this might happen again 62 | // Any settings that don't apply to the current API type are just ignored 63 | 64 | $this->prompt = $this->get_setting('prompt', get_string('defaultprompt', 'block_openai_chat')); 65 | $this->assistantname = $this->get_setting('assistantname', get_string('defaultassistantname', 'block_openai_chat')); 66 | $this->username = $this->get_setting('username', get_string('defaultusername', 'block_openai_chat')); 67 | 68 | $this->temperature = $this->get_setting('temperature', 0.5); 69 | $this->maxlength = $this->get_setting('maxlength', 500); 70 | $this->topp = $this->get_setting('topp', 1); 71 | $this->frequency = $this->get_setting('frequency', 1); 72 | $this->presence = $this->get_setting('presence', 1); 73 | 74 | $this->assistant = $this->get_setting('assistant'); 75 | $this->instructions = $this->get_setting('instructions'); 76 | 77 | // Then override with block settings if applicable 78 | if (get_config('block_openai_chat', 'allowinstancesettings') === "1") { 79 | foreach ($block_settings as $name => $value) { 80 | if ($value) { 81 | $this->$name = $value; 82 | } 83 | } 84 | } 85 | 86 | $this->message = $message; 87 | $this->history = $history; 88 | 89 | $this->build_source_of_truth($block_settings['sourceoftruth']); 90 | } 91 | 92 | /** 93 | * Attempt to get the saved value for a setting; if this isn't set, return a passed default instead 94 | * @param string settingname: The name of the setting to fetch 95 | * @param mixed default_value: The default value to return if the setting isn't already set 96 | * @return mixed: The saved or default value 97 | */ 98 | protected function get_setting($settingname, $default_value = null) { 99 | $setting = get_config('block_openai_chat', $settingname); 100 | if (!$setting && $setting != 0) { 101 | $setting = $default_value; 102 | } 103 | return $setting; 104 | } 105 | 106 | /** 107 | * Make the source of truth ready to add to the prompt by appending some extra information 108 | * @param string localsourceoftruth: The instance-level source of truth we got from the API call 109 | */ 110 | private function build_source_of_truth($localsourceoftruth) { 111 | $sourceoftruth = get_config('block_openai_chat', 'sourceoftruth'); 112 | 113 | if ($sourceoftruth || $localsourceoftruth) { 114 | $sourceoftruth = 115 | get_string('sourceoftruthpreamble', 'block_openai_chat') 116 | . $sourceoftruth . "\n\n" 117 | . $localsourceoftruth . "\n\n"; 118 | } 119 | $this->sourceoftruth = $sourceoftruth; 120 | } 121 | } -------------------------------------------------------------------------------- /classes/completion/assistant.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Class providing completions for assistant API 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat\completion; 26 | 27 | use block_openai_chat\completion; 28 | defined('MOODLE_INTERNAL') || die; 29 | 30 | class assistant extends \block_openai_chat\completion { 31 | 32 | private $thread_id; 33 | 34 | public function __construct($model, $message, $history, $block_settings, $thread_id) { 35 | parent::__construct($model, $message, $history, $block_settings); 36 | 37 | // If thread_id is NULL, create a new thread 38 | if (!$thread_id) { 39 | $thread_id = $this->create_thread(); 40 | } 41 | $this->thread_id = $thread_id; 42 | } 43 | 44 | /** 45 | * Given everything we know after constructing the parent, create a completion by constructing the prompt and making the api call 46 | * @return JSON: The API response from OpenAI 47 | */ 48 | public function create_completion($context) { 49 | $this->add_message_to_thread(); 50 | return $this->run(); 51 | } 52 | 53 | private function create_thread() { 54 | $curl = new \curl(); 55 | $curl->setopt(array( 56 | 'CURLOPT_HTTPHEADER' => array( 57 | 'Authorization: Bearer ' . $this->apikey, 58 | 'Content-Type: application/json', 59 | 'OpenAI-Beta: assistants=v2' 60 | ), 61 | )); 62 | 63 | $response = $curl->post("https://api.openai.com/v1/threads"); 64 | $response = json_decode($response); 65 | 66 | return $response->id; 67 | } 68 | 69 | private function add_message_to_thread() { 70 | $curlbody = [ 71 | "role" => "user", 72 | "content" => $this->message 73 | ]; 74 | 75 | $curl = new \curl(); 76 | $curl->setopt(array( 77 | 'CURLOPT_HTTPHEADER' => array( 78 | 'Authorization: Bearer ' . $this->apikey, 79 | 'Content-Type: application/json', 80 | 'OpenAI-Beta: assistants=v2' 81 | ), 82 | )); 83 | 84 | $response = $curl->post( 85 | "https://api.openai.com/v1/threads/" . $this->thread_id ."/messages", 86 | json_encode($curlbody) 87 | ); 88 | $response = json_decode($response); 89 | 90 | return $response->id; 91 | } 92 | 93 | /** 94 | * Make the actual API call to OpenAI 95 | * @return JSON: The response from OpenAI 96 | */ 97 | private function run() { 98 | 99 | $curlbody = [ 100 | "assistant_id" => $this->assistant, 101 | ]; 102 | if ($this->instructions) { 103 | $curlbody["instructions"] = $this->instructions; 104 | } 105 | 106 | $curl = new \curl(); 107 | $curl->setopt(array( 108 | 'CURLOPT_HTTPHEADER' => array( 109 | 'Authorization: Bearer ' . $this->apikey, 110 | 'Content-Type: application/json', 111 | 'OpenAI-Beta: assistants=v2' 112 | ), 113 | )); 114 | 115 | $response = $curl->post( 116 | "https://api.openai.com/v1/threads/" . $this->thread_id . "/runs", 117 | json_encode($curlbody) 118 | ); 119 | $response = json_decode($response); 120 | 121 | if (isset($response->error)) { 122 | throw new \Exception($response->error->message); 123 | } 124 | 125 | $run_id = $response->id; 126 | $run_completed = false; 127 | $iters = 0; 128 | while (!$run_completed) { 129 | $iters++; 130 | if ($iters >= 60) { 131 | return [ 132 | "id" => 0, 133 | "message" => get_string('openaitimedout', 'block_cloudlearn_ai'), 134 | "thread_id" => 0 135 | ]; 136 | } 137 | $run_completed = $this->check_run_status($run_id); 138 | sleep(1); 139 | } 140 | 141 | $curl = new \curl(); 142 | $curl->setopt(array( 143 | 'CURLOPT_HTTPHEADER' => array( 144 | 'Authorization: Bearer ' . $this->apikey, 145 | 'Content-Type: application/json', 146 | 'OpenAI-Beta: assistants=v2' 147 | ), 148 | )); 149 | $response = $curl->get("https://api.openai.com/v1/threads/" . $this->thread_id . '/messages'); 150 | $response = json_decode($response); 151 | 152 | return [ 153 | "id" => $response->data[0]->id, 154 | "message" => $response->data[0]->content[0]->text->value, 155 | "thread_id" => $response->data[0]->thread_id 156 | ]; 157 | } 158 | 159 | private function check_run_status($run_id) { 160 | $curl = new \curl(); 161 | $curl->setopt(array( 162 | 'CURLOPT_HTTPHEADER' => array( 163 | 'Authorization: Bearer ' . $this->apikey, 164 | 'Content-Type: application/json', 165 | 'OpenAI-Beta: assistants=v2' 166 | ), 167 | )); 168 | 169 | $response = $curl->get("https://api.openai.com/v1/threads/" . $this->thread_id . "/runs/" . $run_id); 170 | $response = json_decode($response); 171 | 172 | if ($response->status === 'completed' || property_exists($response, 'error')) { 173 | return true; 174 | } 175 | return false; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /classes/completion/azure.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Class providing completions for Azure 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat\completion; 26 | 27 | use block_openai_chat\completion; 28 | defined('MOODLE_INTERNAL') || die; 29 | 30 | class azure extends \block_openai_chat\completion\chat { 31 | 32 | private $resourcename; 33 | private $deploymentid; 34 | private $apiversion; 35 | 36 | public function __construct($model, $message, $history, $block_settings, $thread_id = null) { 37 | parent::__construct($model, $message, $history, $block_settings); 38 | 39 | $this->resourcename = $this->get_setting('resourcename'); 40 | $this->deploymentid = $this->get_setting('deploymentid'); 41 | $this->apiversion = $this->get_setting('apiversion'); 42 | } 43 | 44 | /** 45 | * Given everything we know after constructing the parent, create a completion by constructing the prompt and making the api call 46 | * @return JSON: The API response from Azure 47 | */ 48 | public function create_completion($context) { 49 | if ($this->sourceoftruth) { 50 | $this->sourceoftruth = format_string($this->sourceoftruth, true, ['context' => $context]); 51 | $this->prompt .= get_string('sourceoftruthreinforcement', 'block_openai_chat'); 52 | } 53 | $this->prompt .= "\n\n"; 54 | 55 | $history_json = $this->format_history(); 56 | array_unshift($history_json, ["role" => "system", "content" => $this->prompt]); 57 | array_unshift($history_json, ["role" => "system", "content" => $this->sourceoftruth]); 58 | 59 | array_push($history_json, ["role" => "user", "content" => $this->message]); 60 | 61 | $response_data = $this->make_api_call($history_json); 62 | return $response_data; 63 | } 64 | 65 | /** 66 | * Make the actual API call to Azure 67 | * @return JSON: The response from Azure 68 | */ 69 | private function make_api_call($history) { 70 | 71 | $curlbody = [ 72 | "model" => $this->model, 73 | "messages" => $history, 74 | "temperature" => (float) $this->temperature, 75 | "max_tokens" => (int) $this->maxlength, 76 | "top_p" => (float) $this->topp, 77 | "frequency_penalty" => (float) $this->frequency, 78 | "presence_penalty" => (float) $this->presence, 79 | "stop" => $this->username . ":" 80 | ]; 81 | 82 | $curl = new \curl(); 83 | $curl->setopt(array( 84 | 'CURLOPT_HTTPHEADER' => array( 85 | 'api-key: ' . $this->apikey, 86 | 'Content-Type: application/json' 87 | ), 88 | )); 89 | 90 | $response = $curl->post( 91 | "https://" . $this->resourcename . ".openai.azure.com/openai/deployments/" . $this->deploymentid . "/chat/completions?api-version=" . $this->apiversion, 92 | json_encode($curlbody) 93 | ); 94 | $response = json_decode($response); 95 | 96 | $message = null; 97 | if (property_exists($response, 'error')) { 98 | $message = 'ERROR: ' . $response->error->message; 99 | } else { 100 | $message = $response->choices[0]->message->content; 101 | } 102 | 103 | return [ 104 | "id" => property_exists($response, 'id') ? $response->id : 'error', 105 | "message" => $message 106 | ]; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /classes/completion/chat.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Class providing completions for chat models (3.5 and up) 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat\completion; 26 | 27 | use block_openai_chat\completion; 28 | defined('MOODLE_INTERNAL') || die; 29 | 30 | class chat extends \block_openai_chat\completion { 31 | 32 | public function __construct($model, $message, $history, $block_settings, $thread_id = null) { 33 | parent::__construct($model, $message, $history, $block_settings); 34 | } 35 | 36 | /** 37 | * Given everything we know after constructing the parent, create a completion by constructing the prompt and making the api call 38 | * @return JSON: The API response from OpenAI 39 | */ 40 | public function create_completion($context) { 41 | if ($this->sourceoftruth) { 42 | $this->sourceoftruth = format_string($this->sourceoftruth, true, ['context' => $context]); 43 | $this->prompt .= get_string('sourceoftruthreinforcement', 'block_openai_chat'); 44 | } 45 | $this->prompt .= "\n\n"; 46 | 47 | $history_json = $this->format_history(); 48 | array_unshift($history_json, ["role" => "system", "content" => $this->prompt]); 49 | array_unshift($history_json, ["role" => "system", "content" => $this->sourceoftruth]); 50 | 51 | array_push($history_json, ["role" => "user", "content" => $this->message]); 52 | 53 | $response_data = $this->make_api_call($history_json); 54 | return $response_data; 55 | } 56 | 57 | /** 58 | * Format the history JSON into a string that we can pass in the prompt 59 | * @return string: The string representing the chat history to add to the prompt 60 | */ 61 | protected function format_history() { 62 | $history = []; 63 | foreach ($this->history as $index => $message) { 64 | $role = $index % 2 === 0 ? 'user' : 'assistant'; 65 | array_push($history, ["role" => $role, "content" => $message["message"]]); 66 | } 67 | return $history; 68 | } 69 | 70 | /** 71 | * Make the actual API call to OpenAI 72 | * @return JSON: The response from OpenAI 73 | */ 74 | private function make_api_call($history) { 75 | $curlbody = [ 76 | "model" => $this->model, 77 | "messages" => $history, 78 | "temperature" => (float) $this->temperature, 79 | "max_tokens" => (int) $this->maxlength, 80 | "top_p" => (float) $this->topp, 81 | "frequency_penalty" => (float) $this->frequency, 82 | "presence_penalty" => (float) $this->presence, 83 | "stop" => $this->username . ":" 84 | ]; 85 | 86 | $curl = new \curl(); 87 | $curl->setopt(array( 88 | 'CURLOPT_HTTPHEADER' => array( 89 | 'Authorization: Bearer ' . $this->apikey, 90 | 'Content-Type: application/json' 91 | ), 92 | )); 93 | 94 | $response = $curl->post("https://api.openai.com/v1/chat/completions", json_encode($curlbody)); 95 | $response = json_decode($response); 96 | 97 | $message = null; 98 | if (property_exists($response, 'error')) { 99 | $message = 'ERROR: ' . $response->error->message; 100 | } else { 101 | $message = $response->choices[0]->message->content; 102 | } 103 | 104 | return [ 105 | "id" => property_exists($response, 'id') ? $response->id : 'error', 106 | "message" => $message 107 | ]; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /classes/privacy/provider.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Privacy API Provider 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat\privacy; 26 | 27 | use \core_privacy\local\metadata\collection; 28 | use \core_privacy\local\request\writer; 29 | use \core_privacy\local\request\contextlist; 30 | use \core_privacy\local\request\approved_contextlist; 31 | use \core_privacy\local\request\userlist; 32 | use core_privacy\local\request\approved_userlist; 33 | 34 | defined('MOODLE_INTERNAL') || die(); 35 | 36 | class provider implements 37 | \core_privacy\local\metadata\provider, 38 | \core_privacy\local\request\plugin\provider, 39 | \core_privacy\local\request\core_userlist_provider { 40 | 41 | public static function get_metadata(collection $collection): collection { 42 | $collection->add_database_table( 43 | 'block_openai_chat_log', 44 | [ 45 | 'userid' => 'privacy:metadata:openai_chat_log:userid', 46 | 'usermessage' => 'privacy:metadata:openai_chat_log:usermessage', 47 | 'airesponse' => 'privacy:metadata:openai_chat_log:airesponse', 48 | 'timecreated' => 'privacy:metadata:openai_chat_log:timecreated' 49 | ], 50 | 'privacy:metadata:openai_chat_log' 51 | ); 52 | 53 | return $collection; 54 | } 55 | 56 | public static function get_contexts_for_userid(int $userid): contextlist { 57 | $contextlist = new \core_privacy\local\request\contextlist(); 58 | $sql = "SELECT id FROM {context} WHERE contextlevel = 30 AND instanceid = :userid"; 59 | $contextlist->add_from_sql($sql, ['userid' => $userid]); 60 | return $contextlist; 61 | } 62 | 63 | public static function get_users_in_context(userlist $userlist) { 64 | $context = $userlist->get_context(); 65 | if (!$context instanceof \context_user) { 66 | return; 67 | } 68 | 69 | if ($DB->record_exists('block_openai_chat_log', ['userid' => $context->instanceid])) { 70 | $userlist->add_user($context->instanceid); 71 | } 72 | } 73 | 74 | public static function export_user_data(approved_contextlist $contextlist) { 75 | global $DB; 76 | 77 | $context = $contextlist->current(); 78 | $user = $contextlist->get_user(); 79 | $userid = $user->id; 80 | 81 | // Sent messages. 82 | $sql = "SELECT id, userid, usermessage, airesponse, timecreated FROM {block_openai_chat_log} WHERE userid = :userid"; 83 | $records = $DB->get_records_sql($sql, ["userid" => $userid]); 84 | 85 | if (!empty($records)) { 86 | $messages = new \stdClass(); 87 | foreach ($records as $message) { 88 | $messages->{$message->id} = [ 89 | "userid" => $message->userid, 90 | "usermessage" => $message->usermessage, 91 | "airesponse" => $message->airesponse, 92 | "timecreated" => $message->timecreated 93 | ]; 94 | } 95 | 96 | writer::with_context($context)->export_data( 97 | [get_string('privacy:chatmessagespath', 'block_openai_chat')], 98 | $messages 99 | ); 100 | } 101 | } 102 | 103 | public static function delete_data_for_all_users_in_context(\context $context) { 104 | global $DB; 105 | // Only delete data for a user context. 106 | if ($context->contextlevel == CONTEXT_USER) { 107 | $DB->delete_records('block_openai_chat_log', ['userid' => $context->instanceid]); 108 | } 109 | } 110 | 111 | public static function delete_data_for_user(approved_contextlist $contextlist) { 112 | global $DB; 113 | foreach ($contextlist as $context) { 114 | // Let's be super certain that we have the right information for this user here. 115 | if ($context->contextlevel == CONTEXT_USER && $contextlist->get_user()->id == $context->instanceid) { 116 | $DB->delete_records('block_openai_chat_log', ['userid' => $context->instanceid]); 117 | } 118 | } 119 | } 120 | 121 | public static function delete_data_for_users(approved_userlist $userlist) { 122 | global $DB; 123 | $context = $userlist->get_context(); 124 | if ($context instanceof \context_user && in_array($context->instanceid, $userlist->get_userids())) { 125 | $DB->delete_records('block_openai_chat_log', ['userid' => $context->instanceid]); 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /classes/report.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Log table 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | namespace block_openai_chat; 26 | defined('MOODLE_INTERNAL') || die; 27 | 28 | class report extends \table_sql { 29 | function __construct($uniqueid) { 30 | parent::__construct($uniqueid); 31 | // Define the list of columns to show. 32 | $columns = array('userid', 'user_name', 'usermessage', 'airesponse', 'contextid', 'timecreated'); 33 | $this->define_columns($columns); 34 | $this->no_sorting('usermessage'); 35 | $this->no_sorting('airesponse'); 36 | 37 | // Define the titles of columns to show in header. 38 | $headers = array('User ID', 'User Name', 'User Message', 'AI Response', 'Context', 'Time'); 39 | $this->define_headers($headers); 40 | } 41 | 42 | function col_user_name($values) { 43 | global $DB; 44 | $user = $DB->get_record('user', ['id' => $values->userid]); 45 | 46 | if ($this->is_downloading()) { 47 | return "$user->firstname $user->lastname"; 48 | } else { 49 | return "$user->firstname $user->lastname"; 50 | } 51 | } 52 | 53 | function col_contextid($values) { 54 | $context = \context::instance_by_id($values->contextid); 55 | 56 | $coursecontext; 57 | try { 58 | $coursecontext = $context->get_course_context(); 59 | } catch (\Throwable $e) { 60 | $coursecontext = $context; 61 | } 62 | 63 | if ($this->is_downloading()) { 64 | return '=HYPERLINK("' . $context->get_url() . '","' . $context->get_context_name() . '")'; 65 | } else { 66 | return "" . $context->get_context_name() .""; 67 | } 68 | } 69 | 70 | function col_timecreated($values) { 71 | return userdate($values->timecreated); 72 | } 73 | } -------------------------------------------------------------------------------- /db/access.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Define capabilities 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2022 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | defined('MOODLE_INTERNAL') || die(); 26 | 27 | $capabilities = array( 28 | 29 | 'block/openai_chat:myaddinstance' => array( 30 | 'captype' => 'write', 31 | 'contextlevel' => CONTEXT_SYSTEM, 32 | 'archetypes' => array( 33 | 'user' => CAP_ALLOW 34 | ), 35 | 36 | 'clonepermissionsfrom' => 'moodle/my:manageblocks' 37 | ), 38 | 39 | 'block/openai_chat:addinstance' => array( 40 | 'riskbitmask' => RISK_SPAM | RISK_XSS, 41 | 42 | 'captype' => 'write', 43 | 'contextlevel' => CONTEXT_BLOCK, 44 | 'archetypes' => array( 45 | 'editingteacher' => CAP_ALLOW, 46 | 'manager' => CAP_ALLOW 47 | ), 48 | 49 | 'clonepermissionsfrom' => 'moodle/site:manageblocks' 50 | ), 51 | 52 | 'block/openai_chat:viewreport' => array( 53 | 'riskbitmask' => RISK_PERSONAL, 54 | 'captype' => 'read', 55 | 'contextlevel' => CONTEXT_COURSE, 56 | 'archetypes' => array( 57 | 'teacher' => CAP_ALLOW, 58 | 'editingteacher' => CAP_ALLOW, 59 | 'manager' => CAP_ALLOW 60 | ), 61 | 'clonepermissionsfrom' => 'coursereport/participation:view', 62 | ), 63 | ); 64 | -------------------------------------------------------------------------------- /db/install.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 |
26 |
27 | -------------------------------------------------------------------------------- /db/upgrade.php: -------------------------------------------------------------------------------- 1 | get_manager(); // Loads ddl manager and xmldb classes. 7 | 8 | if ($oldversion < 2024040800) { 9 | 10 | // Define table block_openai_chat_log to be created. 11 | $table = new xmldb_table('block_openai_chat_log'); 12 | 13 | // Adding fields to table block_openai_chat_log. 14 | $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); 15 | $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); 16 | $table->add_field('usermessage', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null); 17 | $table->add_field('airesponse', XMLDB_TYPE_TEXT, null, null, null, null, null); 18 | $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); 19 | $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); 20 | 21 | // Adding keys to table block_openai_chat_log. 22 | $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); 23 | $table->add_key('userid', XMLDB_KEY_FOREIGN, ['userid'], 'user', ['id']); 24 | 25 | // Adding indexes to table block_openai_chat_log. 26 | $table->add_index('timecreated', XMLDB_INDEX_NOTUNIQUE, ['timecreated']); 27 | $table->add_index('user-time', XMLDB_INDEX_NOTUNIQUE, ['userid', 'timecreated']); 28 | 29 | // Conditionally launch create table for block_openai_chat_log. 30 | if (!$dbman->table_exists($table)) { 31 | $dbman->create_table($table); 32 | } 33 | 34 | // Openai_chat savepoint reached. 35 | upgrade_block_savepoint(true, 2024040401, 'openai_chat'); 36 | } 37 | 38 | // Everything has succeeded to here. Return true. 39 | return true; 40 | } -------------------------------------------------------------------------------- /edit_form.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Per-block settings 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2022 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | require_once($CFG->dirroot .'/blocks/openai_chat/lib.php'); 26 | 27 | class block_openai_chat_edit_form extends block_edit_form { 28 | 29 | protected function specific_definition($mform) { 30 | $block_id = $this->_ajaxformdata["blockid"]; 31 | $type = get_type_to_display(); 32 | 33 | $mform->addElement('header', 'config_header', get_string('blocksettings', 'block')); 34 | 35 | $mform->addElement('text', 'config_title', get_string('blocktitle', 'block_openai_chat')); 36 | $mform->setDefault('config_title', 'OpenAI Chat'); 37 | $mform->setType('config_title', PARAM_TEXT); 38 | 39 | $mform->addElement('advcheckbox', 'config_showlabels', get_string('showlabels', 'block_openai_chat')); 40 | $mform->setDefault('config_showlabels', 1); 41 | 42 | if ($type === 'assistant') { 43 | // Assistant settings // 44 | 45 | if (get_config('block_openai_chat', 'allowinstancesettings') === "1") { 46 | $mform->addElement('select', 'config_assistant', get_string('assistant', 'block_openai_chat'), fetch_assistants_array($block_id)); 47 | $mform->setDefault('config_assistant', get_config('block_openai_chat', 'assistant')); 48 | $mform->setType('config_assistant', PARAM_TEXT); 49 | $mform->addHelpButton('config_assistant', 'config_assistant', 'block_openai_chat'); 50 | 51 | $mform->addElement('advcheckbox', 'config_persistconvo', get_string('persistconvo', 'block_openai_chat')); 52 | $mform->addHelpButton('config_persistconvo', 'config_persistconvo', 'block_openai_chat'); 53 | $mform->setDefault('config_persistconvo', 1); 54 | 55 | $mform->addElement('textarea', 'config_instructions', get_string('config_instructions', 'block_openai_chat')); 56 | $mform->setDefault('config_instructions', ''); 57 | $mform->setType('config_instructions', PARAM_TEXT); 58 | $mform->addHelpButton('config_instructions', 'config_instructions', 'block_openai_chat'); 59 | 60 | $mform->addElement('text', 'config_username', get_string('username', 'block_openai_chat')); 61 | $mform->setDefault('config_username', ''); 62 | $mform->setType('config_username', PARAM_TEXT); 63 | $mform->addHelpButton('config_username', 'config_username', 'block_openai_chat'); 64 | 65 | $mform->addElement('text', 'config_assistantname', get_string('assistantname', 'block_openai_chat')); 66 | $mform->setDefault('config_assistantname', ''); 67 | $mform->setType('config_assistantname', PARAM_TEXT); 68 | $mform->addHelpButton('config_assistantname', 'config_assistantname', 'block_openai_chat'); 69 | 70 | $mform->addElement('header', 'config_adv_header', get_string('advanced', 'block_openai_chat')); 71 | 72 | $mform->addElement('text', 'config_apikey', get_string('apikey', 'block_openai_chat')); 73 | $mform->setDefault('config_apikey', ''); 74 | $mform->setType('config_apikey', PARAM_TEXT); 75 | $mform->addHelpButton('config_apikey', 'config_apikey', 'block_openai_chat'); 76 | } 77 | 78 | } else { 79 | // Chat settings // 80 | 81 | $mform->addElement('textarea', 'config_sourceoftruth', get_string('sourceoftruth', 'block_openai_chat')); 82 | $mform->setDefault('config_sourceoftruth', ''); 83 | $mform->setType('config_sourceoftruth', PARAM_TEXT); 84 | $mform->addHelpButton('config_sourceoftruth', 'config_sourceoftruth', 'block_openai_chat'); 85 | 86 | if (get_config('block_openai_chat', 'allowinstancesettings') === "1") { 87 | $mform->addElement('textarea', 'config_prompt', get_string('prompt', 'block_openai_chat')); 88 | $mform->setDefault('config_prompt', ''); 89 | $mform->setType('config_prompt', PARAM_TEXT); 90 | $mform->addHelpButton('config_prompt', 'config_prompt', 'block_openai_chat'); 91 | 92 | $mform->addElement('text', 'config_username', get_string('username', 'block_openai_chat')); 93 | $mform->setDefault('config_username', ''); 94 | $mform->setType('config_username', PARAM_TEXT); 95 | $mform->addHelpButton('config_username', 'config_username', 'block_openai_chat'); 96 | 97 | $mform->addElement('text', 'config_assistantname', get_string('assistantname', 'block_openai_chat')); 98 | $mform->setDefault('config_assistantname', ''); 99 | $mform->setType('config_assistantname', PARAM_TEXT); 100 | $mform->addHelpButton('config_assistantname', 'config_assistantname', 'block_openai_chat'); 101 | 102 | $mform->addElement('header', 'config_adv_header', get_string('advanced', 'block_openai_chat')); 103 | 104 | $mform->addElement('text', 'config_apikey', get_string('apikey', 'block_openai_chat')); 105 | $mform->setDefault('config_apikey', ''); 106 | $mform->setType('config_apikey', PARAM_TEXT); 107 | $mform->addHelpButton('config_apikey', 'config_apikey', 'block_openai_chat'); 108 | 109 | $mform->addElement('select', 'config_model', get_string('model', 'block_openai_chat'), get_models()['models']); 110 | $mform->setDefault('config_model', get_config('block_openai_chat', 'model')); 111 | $mform->setType('config_model', PARAM_TEXT); 112 | $mform->addHelpButton('config_model', 'config_model', 'block_openai_chat'); 113 | 114 | $mform->addElement('text', 'config_temperature', get_string('temperature', 'block_openai_chat')); 115 | $mform->setDefault('config_temperature', 0.5); 116 | $mform->setType('config_temperature', PARAM_FLOAT); 117 | $mform->addHelpButton('config_temperature', 'config_temperature', 'block_openai_chat'); 118 | 119 | $mform->addElement('text', 'config_maxlength', get_string('maxlength', 'block_openai_chat')); 120 | $mform->setDefault('config_maxlength', 500); 121 | $mform->setType('config_maxlength', PARAM_INT); 122 | $mform->addHelpButton('config_maxlength', 'config_maxlength', 'block_openai_chat'); 123 | 124 | $mform->addElement('text', 'config_topp', get_string('topp', 'block_openai_chat')); 125 | $mform->setDefault('config_topp', 1); 126 | $mform->setType('config_topp', PARAM_FLOAT); 127 | $mform->addHelpButton('config_topp', 'config_topp', 'block_openai_chat'); 128 | 129 | $mform->addElement('text', 'config_frequency', get_string('frequency', 'block_openai_chat')); 130 | $mform->setDefault('config_frequency', 1); 131 | $mform->setType('config_frequency', PARAM_FLOAT); 132 | $mform->addHelpButton('config_frequency', 'config_frequency', 'block_openai_chat'); 133 | 134 | $mform->addElement('text', 'config_presence', get_string('presence', 'block_openai_chat')); 135 | $mform->setDefault('config_presence', 1); 136 | $mform->setType('config_presence', PARAM_FLOAT); 137 | $mform->addHelpButton('config_presence', 'config_presence', 'block_openai_chat'); 138 | } 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /lang/en/block_openai_chat.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Language strings 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | $string['pluginname'] = 'OpenAI Chat Block'; 26 | $string['openai_chat'] = 'OpenAI Chat'; 27 | $string['openai_chat_logs'] = 'OpenAI Chat Logs'; 28 | $string['openai_chat:addinstance'] = 'Add a new OpenAI Chat block'; 29 | $string['openai_chat:myaddinstance'] = 'Add a new OpenAI Chat block to the My Moodle page'; 30 | $string['openai_chat:viewreport'] = 'View OpenAI Chat log report'; 31 | $string['privacy:metadata:openai_chat_log'] = 'Logged user messages sent to OpenAI. This includes the user ID of the user that sent the message, the content of the message, the response from OpenAI, and the time that the message was sent.'; 32 | $string['privacy:metadata:openai_chat_log:userid'] = 'The ID of the user that sent the message.'; 33 | $string['privacy:metadata:openai_chat_log:usermessage'] = 'The content of the message.'; 34 | $string['privacy:metadata:openai_chat_log:airesponse'] = 'The response from OpenAI.'; 35 | $string['privacy:metadata:openai_chat_log:timecreated'] = 'The time the message was sent.'; 36 | $string['privacy:chatmessagespath'] = 'Sent AI chat messages'; 37 | $string['downloadfilename'] = 'block_openai_chat_logs'; 38 | 39 | $string['blocktitle'] = 'Block title'; 40 | 41 | $string['restrictusage'] = 'Restrict usage to logged-in users'; 42 | $string['restrictusagedesc'] = 'If this box is checked, only logged-in users will be able to use the chat box.'; 43 | $string['apikey'] = 'API Key'; 44 | $string['apikeydesc'] = 'The API Key for your OpenAI account or Azure API key'; 45 | $string['type'] = 'API Type'; 46 | $string['typedesc'] = 'The API type that the plugin should use'; 47 | $string['logging'] = 'Enable logging'; 48 | $string['loggingdesc'] = 'If this setting is active, all user messages and AI responses will be logged.'; 49 | 50 | $string['assistantheading'] = 'Assistant API Settings'; 51 | $string['assistantheadingdesc'] = 'These settings only apply to the Assistant API type.'; 52 | $string['assistant'] = 'Assistant'; 53 | $string['assistantdesc'] = 'The default assistant attached to your OpenAI account that you would like to use for the response'; 54 | $string['noassistants'] = 'You haven\'t created any assistants yet. You need to create one in your OpenAI account before you can select it here.'; 55 | $string['persistconvo'] = 'Persist conversations'; 56 | $string['persistconvodesc'] = 'If this box is checked, the assistant will remember the conversation between page loads. However, separate block instances will maintain separate conversations. For example, a user\'s conversation will be retained between page loads within the same course, but chatting with an assistant in a different course will not carry on the same conversation.'; 57 | 58 | $string['azureheading'] = 'Azure API Settings'; 59 | $string['azureheadingdesc'] = 'These settings only apply to the Azure API type.'; 60 | $string['resourcename'] = 'Resource name'; 61 | $string['resourcenamedesc'] = 'The name of your Azure OpenAI Resource.'; 62 | $string['deploymentid'] = 'Deployment ID'; 63 | $string['deploymentiddesc'] = 'The deployment name you chose when you deployed the model.'; 64 | $string['apiversion'] = 'API Version'; 65 | $string['apiversiondesc'] = 'The API version to use for this operation. This follows the YYYY-MM-DD format.'; 66 | $string['chatheading'] = 'Chat API Settings'; 67 | $string['chatheadingdesc'] = 'These settings only apply to the Chat API and Azure API types.'; 68 | $string['prompt'] = 'Completion prompt'; 69 | $string['promptdesc'] = 'The prompt the AI will be given before the conversation transcript'; 70 | $string['assistantname'] = 'Assistant name'; 71 | $string['assistantnamedesc'] = 'The name that the AI will use for itself internally. It is also used for the UI headings in the chat window.'; 72 | $string['username'] = 'User name'; 73 | $string['usernamedesc'] = 'The name that the AI will use for the user internally. It is also used for the UI headings in the chat window.'; 74 | $string['sourceoftruth'] = 'Source of truth'; 75 | $string['sourceoftruthdesc'] = 'Although the AI is very capable out-of-the-box, if it doesn\'t know the answer to a question, it is more likely to give incorrect information confidently than to refuse to answer. In this textbox, you can add common questions and their answers for the AI to pull from. Please put questions and answers in the following format:
Q: Question 1
A: Answer 1

Q: Question 2
A: Answer 2
'; 76 | $string['showlabels'] = 'Show labels'; 77 | $string['advanced'] = 'Advanced'; 78 | $string['advanceddesc'] = 'Advanced arguments sent to OpenAI. Don\'t touch unless you know what you\'re doing!'; 79 | $string['allowinstancesettings'] = 'Instance-level settings'; 80 | $string['allowinstancesettingsdesc'] = 'This setting will allow teachers, or anyone with the capability to add a block in a context, to adjust settings at a per-block level. Enabling this could incur additional charges by allowing non-admins to choose higher-cost models or other settings.'; 81 | $string['model'] = 'Model'; 82 | $string['modeldesc'] = 'The model which will generate the completion. Some models are suitable for natural language tasks, others specialize in code.'; 83 | $string['temperature'] = 'Temperature'; 84 | $string['temperaturedesc'] = 'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.'; 85 | $string['maxlength'] = 'Maximum length'; 86 | $string['maxlengthdesc'] = 'The maximum number of token to generate. Requests can use up to 2,048 or 4,000 tokens shared between prompt and completion. The exact limit varies by model. (One token is roughly 4 characters for normal English text)'; 87 | $string['topp'] = 'Top P'; 88 | $string['toppdesc'] = 'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered.'; 89 | $string['frequency'] = 'Frequency penalty'; 90 | $string['frequencydesc'] = 'How much to penalize new tokens based on their existing frequency in the text so far. Decreases the model\'s likelihood to repeat the same line verbatim.'; 91 | $string['presence'] = 'Presence penalty'; 92 | $string['presencedesc'] = 'How much to penalize new tokens based on whether they appear in the text so far. Increases the model\'s likelihood to talk about new topics.'; 93 | 94 | $string['config_assistant'] = "Assistant"; 95 | $string['config_assistant_help'] = "Choose the assistant you would like to use for this block. More assistants can be created in the OpenAI account that this block is configured to use."; 96 | $string['config_sourceoftruth'] = 'Source of truth'; 97 | $string['config_sourceoftruth_help'] = "You can add information here that the AI will pull from when answering questions. The information should be in question and answer format exactly like the following:\n\nQ: When is section 3 due?
A: Thursday, March 16.\n\nQ: When are office hours?
A: You can find Professor Shown in her office between 2:00 and 4:00 PM on Tuesdays and Thursdays."; 98 | $string['config_instructions'] = "Custom instructions"; 99 | $string['config_instructions_help'] = "You can override the assistant's default instructions here."; 100 | $string['config_prompt'] = "Completion prompt"; 101 | $string['config_prompt_help'] = "This is the prompt the AI will be given before the conversation transcript. You can influence the AI's personality by altering this description. By default, the prompt is \n\n\"Below is a conversation between a user and a support assistant for a Moodle site, where users go for online learning.\"\n\nIf blank, the site-wide prompt will be used."; 102 | $string['config_username'] = "User name"; 103 | $string['config_username_help'] = "This is the name that the AI will use for the user. If blank, the site-wide user name will be used. It is also used for the UI headings in the chat window."; 104 | $string['config_assistantname'] = "Assistant name"; 105 | $string['config_assistantname_help'] = "This is the name that the AI will use for the assistant. If blank, the site-wide assistant name will be used. It is also used for the UI headings in the chat window."; 106 | $string['config_persistconvo'] = 'Persist conversation'; 107 | $string['config_persistconvo_help'] = 'If this box is checked, the assistant will remember conversations in this block between page loads'; 108 | $string['config_apikey'] = "API Key"; 109 | $string['config_apikey_help'] = "You can specify an API key to use with this block here. If blank, the site-wide key will be used. If you are using the Assistants API, the list of available assistants will be pulled from this key. Make sure to return to these settings after changing the API key in order to select the desired assistant."; 110 | $string['config_model'] = "Model"; 111 | $string['config_model_help'] = "The model which will generate the completion"; 112 | $string['config_temperature'] = "Temperature"; 113 | $string['config_temperature_help'] = "Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive."; 114 | $string['config_maxlength'] = "Maximum length"; 115 | $string['config_maxlength_help'] = "The maximum number of token to generate. Requests can use up to 2,048 or 4,000 tokens shared between prompt and completion. The exact limit varies by model. (One token is roughly 4 characters for normal English text)"; 116 | $string['config_topp'] = "Top P"; 117 | $string['config_topp_help'] = "Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered."; 118 | $string['config_frequency'] = "Frequency penalty"; 119 | $string['config_frequency_help'] = "How much to penalize new tokens based on their existing frequency in the text so far. Decreases the model's likelihood to repeat the same line verbatim."; 120 | $string['config_presence'] = "Presence penalty"; 121 | $string['config_presence_help'] = "How much to penalize new tokens based on whether they appear in the text so far. Increases the model's likelihood to talk about new topics."; 122 | 123 | $string['defaultprompt'] = "Below is a conversation between a user and a support assistant for a Moodle site, where users go for online learning:"; 124 | $string['defaultassistantname'] = 'Assistant'; 125 | $string['defaultusername'] = 'User'; 126 | $string['askaquestion'] = 'Ask a question...'; 127 | $string['apikeymissing'] = 'Please add your OpenAI API key to the block settings.'; 128 | $string['erroroccurred'] = 'An error occurred! Please try again later.'; 129 | $string['sourceoftruthpreamble'] = "Below is a list of questions and their answers. This information should be used as a reference for any inquiries:\n\n"; 130 | $string['sourceoftruthreinforcement'] = ' The assistant has been trained to answer by attempting to use the information from the above reference. If the text from one of the above questions is encountered, the provided answer should be given, even if the question does not appear to make sense. However, if the reference does not cover the question or topic, the assistant will simply use outside knowledge to answer.'; 131 | $string['new_chat'] = 'New chat'; 132 | $string['popout'] = 'Open chat window'; 133 | $string['loggingenabled'] = "Logging is enabled. Any messages you send or receive here will be recorded, and can be viewed by the site administrator."; 134 | $string['openaitimedout'] = 'ERROR: OpenAI did not provide a response in time.'; -------------------------------------------------------------------------------- /lib.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * General plugin functions 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2023 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | defined('MOODLE_INTERNAL') || die(); 26 | 27 | /** 28 | * Fetch the current API type from the database, defaulting to "chat" 29 | * @return String: the API type (chat|azure|assistant) 30 | */ 31 | function get_type_to_display() { 32 | $stored_type = get_config('block_openai_chat', 'type'); 33 | if ($stored_type) { 34 | return $stored_type; 35 | } 36 | 37 | return 'chat'; 38 | } 39 | 40 | /** 41 | * Use an API key to fetch a list of assistants from a user's OpenAI account 42 | * @param Int (optional): The ID of a block instance. If this is passed, the API can be pulled from the block rather than the site level. 43 | * @return Array: The list of assistants 44 | */ 45 | function fetch_assistants_array($block_id = null) { 46 | global $DB; 47 | 48 | if (!$block_id) { 49 | $apikey = get_config('block_openai_chat', 'apikey'); 50 | } else { 51 | $instance_record = $DB->get_record('block_instances', ['blockname' => 'openai_chat', 'id' => $block_id], '*'); 52 | $instance = block_instance('openai_chat', $instance_record); 53 | $apikey = $instance->config->apikey ? $instance->config->apikey : get_config('block_openai_chat', 'apikey'); 54 | } 55 | 56 | if (!$apikey) { 57 | return []; 58 | } 59 | 60 | $curl = new \curl(); 61 | $curl->setopt(array( 62 | 'CURLOPT_HTTPHEADER' => array( 63 | 'Authorization: Bearer ' . $apikey, 64 | 'Content-Type: application/json', 65 | 'OpenAI-Beta: assistants=v2' 66 | ), 67 | )); 68 | 69 | $response = $curl->get("https://api.openai.com/v1/assistants?order=desc"); 70 | $response = json_decode($response); 71 | $assistant_array = []; 72 | if (property_exists($response, 'data')) { 73 | foreach ($response->data as $assistant) { 74 | $assistant_array[$assistant->id] = $assistant->name; 75 | } 76 | } 77 | 78 | return $assistant_array; 79 | } 80 | 81 | /** 82 | * Return a list of available models, and the type of each model. 83 | * (Type used to be relevant before OpenAI released the Assistant API. Currently it is no longer useful as all models are of type "chat," 84 | * but I left it here in case the API is changed significantly in the future) 85 | * @return Array: The list of model info 86 | */ 87 | function get_models() { 88 | return [ 89 | "models" => [ 90 | 'gpt-4o' => 'gpt-4o', 91 | 'gpt-4o-2024-11-20' => 'gpt-4o-2024-11-20', 92 | 'gpt-4o-2024-08-06' => 'gpt-4o-2024-08-06', 93 | 'gpt-4o-2024-05-13' => 'gpt-4o-2024-05-13', 94 | 'gpt-4o-mini-2024-07-18' => 'gpt-4o-mini-2024-07-18', 95 | 'gpt-4o-mini' => 'gpt-4o-mini', 96 | 'gpt-4-turbo-preview' => 'gpt-4-turbo-preview', 97 | 'gpt-4-turbo-2024-04-09' => 'gpt-4-turbo-2024-04-09', 98 | 'gpt-4-turbo' => 'gpt-4-turbo', 99 | 'gpt-4-32k-0314' => 'gpt-4-32k-0314', 100 | 'gpt-4-1106-preview' => 'gpt-4-1106-preview', 101 | 'gpt-4-0613' => 'gpt-4-0613', 102 | 'gpt-4-0314' => 'gpt-4-0314', 103 | 'gpt-4-0125-preview' => 'gpt-4-0125-preview', 104 | 'gpt-4' => 'gpt-4', 105 | 'gpt-3.5-turbo-16k-0613' => 'gpt-3.5-turbo-16k-0613', 106 | 'gpt-3.5-turbo-16k' => 'gpt-3.5-turbo-16k', 107 | 'gpt-3.5-turbo-1106' => 'gpt-3.5-turbo-1106', 108 | 'gpt-3.5-turbo-0125' => 'gpt-3.5-turbo-0125', 109 | 'gpt-3.5-turbo' => 'gpt-3.5-turbo' 110 | ], 111 | "types" => [ 112 | 'gpt-4o-2024-11-20' => 'chat', 113 | 'gpt-4o-2024-08-06' => 'chat', 114 | 'gpt-4o-2024-05-13' => 'chat', 115 | 'gpt-4o' => 'chat', 116 | 'gpt-4o-mini-2024-07-18' => 'chat', 117 | 'gpt-4o-mini' => 'chat', 118 | 'gpt-4-turbo-preview' => 'chat', 119 | 'gpt-4-turbo-2024-04-09' => 'chat', 120 | 'gpt-4-turbo' => 'chat', 121 | 'gpt-4-32k-0314' => 'chat', 122 | 'gpt-4-1106-preview' => 'chat', 123 | 'gpt-4-0613' => 'chat', 124 | 'gpt-4-0314' => 'chat', 125 | 'gpt-4-0125-preview' => 'chat', 126 | 'gpt-4' => 'chat', 127 | 'gpt-3.5-turbo-16k-0613' => 'chat', 128 | 'gpt-3.5-turbo-16k' => 'chat', 129 | 'gpt-3.5-turbo-1106' => 'chat', 130 | 'gpt-3.5-turbo-0125' => 'chat', 131 | 'gpt-3.5-turbo' => 'chat' 132 | ] 133 | ]; 134 | } 135 | 136 | /** 137 | * If setting is enabled, log the user's message and the AI response 138 | * @param string usermessage: The text sent from the user 139 | * @param string airesponse: The text returned by the AI 140 | */ 141 | function log_message($usermessage, $airesponse, $context) { 142 | global $USER, $DB; 143 | 144 | if (!get_config('block_openai_chat', 'logging')) { 145 | return; 146 | } 147 | 148 | $DB->insert_record('block_openai_chat_log', (object) [ 149 | 'userid' => $USER->id, 150 | 'usermessage' => $usermessage, 151 | 'airesponse' => $airesponse, 152 | 'contextid' => $context->id, 153 | 'timecreated' => time() 154 | ]); 155 | } 156 | 157 | function block_openai_chat_extend_navigation_course($nav, $course, $context) { 158 | if ($nav->get('coursereports')) { 159 | $nav->get('coursereports')->add( 160 | get_string('openai_chat_logs', 'block_openai_chat'), 161 | new moodle_url('/blocks/openai_chat/report.php', ['courseid' => $course->id]), 162 | navigation_node::TYPE_SETTING, 163 | null 164 | ); 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /pix/arrow-right.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pix/arrow-up-right-from-square.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pix/refresh.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /report.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Log report table 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | use \block_openai_chat\report; 26 | 27 | require_once('../../config.php'); 28 | require_once($CFG->libdir.'/tablelib.php'); 29 | global $DB; 30 | 31 | $courseid = required_param('courseid', PARAM_INT); 32 | $download = optional_param('download', '', PARAM_ALPHA); 33 | $user = optional_param('user', '', PARAM_TEXT); 34 | $starttime = optional_param('starttime', '', PARAM_TEXT); 35 | $endtime = optional_param('endtime', '', PARAM_TEXT); 36 | $tsort = optional_param('tsort', '', PARAM_TEXT); 37 | 38 | $pageurl = $CFG->wwwroot . "/blocks/openai_chat/report.php?courseid=$courseid" . 39 | "&user=$user" . 40 | "&starttime=$starttime" . 41 | "&endtime=$endtime"; 42 | $starttime_ts = strtotime($starttime); 43 | $endtime_ts = strtotime($endtime); 44 | $course = $DB->get_record('course', ['id' => $courseid]); 45 | 46 | $PAGE->set_url($pageurl); 47 | require_login($course); 48 | $context = context_course::instance($courseid); 49 | require_capability('block/openai_chat:viewreport', $context); 50 | 51 | $datetime = new DateTime(); 52 | $table = new \block_openai_chat\report(time()); 53 | $table->show_download_buttons_at(array(TABLE_P_BOTTOM)); 54 | $table->is_downloading( 55 | $download, 56 | get_string('downloadfilename', 'block_openai_chat') 57 | . '_' 58 | . $datetime->format(DateTime::ATOM) 59 | ); 60 | 61 | if (!$table->is_downloading()) { 62 | $PAGE->set_pagelayout('report'); 63 | $PAGE->set_title(get_string('openai_chat_logs', 'block_openai_chat')); 64 | $PAGE->set_heading(get_string('openai_chat_logs', 'block_openai_chat')); 65 | $PAGE->navbar->add($course->shortname, new moodle_url('/course/view.php', ['id' => $course->id])); 66 | $PAGE->navbar->add(get_string('openai_chat_logs', 'block_openai_chat'), new moodle_url($pageurl)); 67 | 68 | echo $OUTPUT->header(); 69 | echo $OUTPUT->render_from_template('block_openai_chat/report_page', [ 70 | "courseid" => $courseid, 71 | "user" => $user, 72 | "starttime" => $starttime, 73 | "endtime" => $endtime, 74 | "link" => (new moodle_url("/blocks/openai_chat/report.php"))->out() 75 | ]); 76 | } 77 | 78 | $where = "1=1"; 79 | $out = 10; 80 | 81 | // If courseid is 1, we're assuming this is an admin report wanting the entire log table 82 | // otherwise, we'll limit it to responses in the course context for this course 83 | if ($courseid !== 1) { 84 | $where = "c.contextlevel = 50 AND co.id = $courseid"; 85 | } 86 | 87 | // filter by user, starttime, endtime 88 | if ($user) { 89 | $where .= " AND CONCAT(u.firstname, ' ', u.lastname) like '%$user%'"; 90 | } 91 | if ($starttime_ts) { 92 | $where .= " AND ocl.timecreated > $starttime_ts"; 93 | } 94 | if ($endtime_ts) { 95 | $where .= " AND ocl.timecreated < $endtime_ts"; 96 | } 97 | 98 | if (!$tsort) { 99 | $where .= " ORDER BY ocl.timecreated DESC"; 100 | } 101 | 102 | $table->set_sql( 103 | "ocl.*, CONCAT(u.firstname, ' ', u.lastname) as user_name", 104 | "{block_openai_chat_log} ocl 105 | JOIN {user} u ON u.id = ocl.userid 106 | JOIN {context} c ON c.id = ocl.contextid 107 | LEFT JOIN {course} co ON co.id = c.instanceid", 108 | $where 109 | ); 110 | $table->define_baseurl($pageurl); 111 | $table->out($out, true); 112 | 113 | if (!$table->is_downloading()) { 114 | echo $OUTPUT->footer(); 115 | } -------------------------------------------------------------------------------- /settings.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Plugin settings 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2024 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | defined('MOODLE_INTERNAL') || die(); 26 | 27 | if ($hassiteconfig) { 28 | 29 | if (!defined('BEHAT_SITE_RUNNING')) { 30 | $ADMIN->add('reports', new admin_externalpage( 31 | 'openai_chat_report', 32 | get_string('openai_chat_logs', 'block_openai_chat'), 33 | new moodle_url("$CFG->wwwroot/blocks/openai_chat/report.php", ['courseid' => 1]), 34 | 'moodle/site:config' 35 | )); 36 | } 37 | 38 | if ($ADMIN->fulltree) { 39 | 40 | require_once($CFG->dirroot .'/blocks/openai_chat/lib.php'); 41 | 42 | $type = get_type_to_display(); 43 | $assistant_array = []; 44 | if ($type === 'assistant') { 45 | $assistant_array = fetch_assistants_array(); 46 | } 47 | 48 | global $PAGE; 49 | $PAGE->requires->js_call_amd('block_openai_chat/settings', 'init'); 50 | 51 | $settings->add(new admin_setting_configtext( 52 | 'block_openai_chat/apikey', 53 | get_string('apikey', 'block_openai_chat'), 54 | get_string('apikeydesc', 'block_openai_chat'), 55 | '', 56 | PARAM_TEXT 57 | )); 58 | 59 | $settings->add(new admin_setting_configselect( 60 | 'block_openai_chat/type', 61 | get_string('type', 'block_openai_chat'), 62 | get_string('typedesc', 'block_openai_chat'), 63 | 'chat', 64 | ['chat' => 'chat', 'assistant' => 'assistant', 'azure' => 'azure'] 65 | )); 66 | 67 | $settings->add(new admin_setting_configcheckbox( 68 | 'block_openai_chat/restrictusage', 69 | get_string('restrictusage', 'block_openai_chat'), 70 | get_string('restrictusagedesc', 'block_openai_chat'), 71 | 1 72 | )); 73 | 74 | $settings->add(new admin_setting_configtext( 75 | 'block_openai_chat/assistantname', 76 | get_string('assistantname', 'block_openai_chat'), 77 | get_string('assistantnamedesc', 'block_openai_chat'), 78 | 'Assistant', 79 | PARAM_TEXT 80 | )); 81 | 82 | $settings->add(new admin_setting_configtext( 83 | 'block_openai_chat/username', 84 | get_string('username', 'block_openai_chat'), 85 | get_string('usernamedesc', 'block_openai_chat'), 86 | 'User', 87 | PARAM_TEXT 88 | )); 89 | 90 | $settings->add(new admin_setting_configcheckbox( 91 | 'block_openai_chat/logging', 92 | get_string('logging', 'block_openai_chat'), 93 | get_string('loggingdesc', 'block_openai_chat'), 94 | 0 95 | )); 96 | 97 | // Assistant settings // 98 | 99 | if ($type === 'assistant') { 100 | $settings->add(new admin_setting_heading( 101 | 'block_openai_chat/assistantheading', 102 | get_string('assistantheading', 'block_openai_chat'), 103 | get_string('assistantheadingdesc', 'block_openai_chat') 104 | )); 105 | 106 | if (count($assistant_array)) { 107 | $settings->add(new admin_setting_configselect( 108 | 'block_openai_chat/assistant', 109 | get_string('assistant', 'block_openai_chat'), 110 | get_string('assistantdesc', 'block_openai_chat'), 111 | count($assistant_array) ? reset($assistant_array) : null, 112 | $assistant_array 113 | )); 114 | } else { 115 | $settings->add(new admin_setting_description( 116 | 'block_openai_chat/noassistants', 117 | get_string('assistant', 'block_openai_chat'), 118 | get_string('noassistants', 'block_openai_chat'), 119 | )); 120 | } 121 | 122 | $settings->add(new admin_setting_configcheckbox( 123 | 'block_openai_chat/persistconvo', 124 | get_string('persistconvo', 'block_openai_chat'), 125 | get_string('persistconvodesc', 'block_openai_chat'), 126 | 1 127 | )); 128 | 129 | } else { 130 | 131 | // Chat settings // 132 | 133 | if ($type === 'azure') { 134 | $settings->add(new admin_setting_heading( 135 | 'block_openai_chat/azureheading', 136 | get_string('azureheading', 'block_openai_chat'), 137 | get_string('azureheadingdesc', 'block_openai_chat') 138 | )); 139 | 140 | $settings->add(new admin_setting_configtext( 141 | 'block_openai_chat/resourcename', 142 | get_string('resourcename', 'block_openai_chat'), 143 | get_string('resourcenamedesc', 'block_openai_chat'), 144 | "", 145 | PARAM_TEXT 146 | )); 147 | 148 | $settings->add(new admin_setting_configtext( 149 | 'block_openai_chat/deploymentid', 150 | get_string('deploymentid', 'block_openai_chat'), 151 | get_string('deploymentiddesc', 'block_openai_chat'), 152 | "", 153 | PARAM_TEXT 154 | )); 155 | 156 | $settings->add(new admin_setting_configtext( 157 | 'block_openai_chat/apiversion', 158 | get_string('apiversion', 'block_openai_chat'), 159 | get_string('apiversiondesc', 'block_openai_chat'), 160 | "2023-09-01-preview", 161 | PARAM_TEXT 162 | )); 163 | } 164 | 165 | $settings->add(new admin_setting_heading( 166 | 'block_openai_chat/chatheading', 167 | get_string('chatheading', 'block_openai_chat'), 168 | get_string('chatheadingdesc', 'block_openai_chat') 169 | )); 170 | 171 | $settings->add(new admin_setting_configtextarea( 172 | 'block_openai_chat/prompt', 173 | get_string('prompt', 'block_openai_chat'), 174 | get_string('promptdesc', 'block_openai_chat'), 175 | "Below is a conversation between a user and a support assistant for a Moodle site, where users go for online learning.", 176 | PARAM_TEXT 177 | )); 178 | 179 | $settings->add(new admin_setting_configtextarea( 180 | 'block_openai_chat/sourceoftruth', 181 | get_string('sourceoftruth', 'block_openai_chat'), 182 | get_string('sourceoftruthdesc', 'block_openai_chat'), 183 | '', 184 | PARAM_TEXT 185 | )); 186 | } 187 | 188 | 189 | // Advanced Settings // 190 | 191 | $settings->add(new admin_setting_heading( 192 | 'block_openai_chat/advanced', 193 | get_string('advanced', 'block_openai_chat'), 194 | get_string('advanceddesc', 'block_openai_chat') 195 | )); 196 | 197 | $settings->add(new admin_setting_configcheckbox( 198 | 'block_openai_chat/allowinstancesettings', 199 | get_string('allowinstancesettings', 'block_openai_chat'), 200 | get_string('allowinstancesettingsdesc', 'block_openai_chat'), 201 | 0 202 | )); 203 | 204 | if ($type === 'assistant') { 205 | 206 | } else { 207 | $settings->add(new admin_setting_configselect( 208 | 'block_openai_chat/model', 209 | get_string('model', 'block_openai_chat'), 210 | get_string('modeldesc', 'block_openai_chat'), 211 | 'text-davinci-003', 212 | get_models()['models'] 213 | )); 214 | 215 | $settings->add(new admin_setting_configtext( 216 | 'block_openai_chat/temperature', 217 | get_string('temperature', 'block_openai_chat'), 218 | get_string('temperaturedesc', 'block_openai_chat'), 219 | 0.5, 220 | PARAM_FLOAT 221 | )); 222 | 223 | $settings->add(new admin_setting_configtext( 224 | 'block_openai_chat/maxlength', 225 | get_string('maxlength', 'block_openai_chat'), 226 | get_string('maxlengthdesc', 'block_openai_chat'), 227 | 500, 228 | PARAM_INT 229 | )); 230 | 231 | $settings->add(new admin_setting_configtext( 232 | 'block_openai_chat/topp', 233 | get_string('topp', 'block_openai_chat'), 234 | get_string('toppdesc', 'block_openai_chat'), 235 | 1, 236 | PARAM_FLOAT 237 | )); 238 | 239 | $settings->add(new admin_setting_configtext( 240 | 'block_openai_chat/frequency', 241 | get_string('frequency', 'block_openai_chat'), 242 | get_string('frequencydesc', 'block_openai_chat'), 243 | 1, 244 | PARAM_FLOAT 245 | )); 246 | 247 | $settings->add(new admin_setting_configtext( 248 | 'block_openai_chat/presence', 249 | get_string('presence', 'block_openai_chat'), 250 | get_string('presencedesc', 'block_openai_chat'), 251 | 1, 252 | PARAM_FLOAT 253 | )); 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | .block_openai_chat { 2 | position: relative; 3 | } 4 | 5 | .block_openai_chat #openai_chat_log { 6 | display: flex; 7 | flex-direction: column; 8 | max-height: 20rem; 9 | overflow-y: scroll; 10 | margin-bottom: 0.5rem; 11 | } 12 | 13 | .block_openai_chat #openai_chat_log p { 14 | margin: 0; 15 | } 16 | 17 | .block_openai_chat #openai_chat_log a { 18 | color: white; 19 | text-decoration: underline; 20 | } 21 | 22 | .block_openai_chat #control_bar { 23 | display: flex; 24 | gap: 0.5rem; 25 | } 26 | 27 | .block_openai_chat #control_bar button:hover { 28 | filter: brightness(0.8); 29 | } 30 | 31 | .block_openai_chat #control_bar #go { 32 | border-radius: 0 0.5rem 0.5rem 0; 33 | } 34 | 35 | .block_openai_chat #control_bar button { 36 | transition: filter 0.2s ease; 37 | border: none; 38 | border-radius: 0.5rem; 39 | width: 2.5rem; 40 | } 41 | 42 | .openai_input_submit_btn { 43 | background-color: var(--primary); 44 | color: var(--white); 45 | } 46 | 47 | .openai_input_refresh_btn { 48 | background-color: var(--secondary); 49 | color: black; 50 | } 51 | 52 | .block_openai_chat .openai_input_popout_btn { 53 | position: absolute; 54 | top: 0.75rem; 55 | right: 0.5rem; 56 | width: 2rem; 57 | height: 2rem; 58 | border-radius: 99rem; 59 | padding: 0.4rem; 60 | display: flex; 61 | border: none; 62 | z-index: 2; 63 | } 64 | .block_openai_chat .openai_input_popout_btn img { 65 | max-width: 1.25rem; 66 | pointer-events: none; 67 | } 68 | .drawercontent { 69 | position: unset; 70 | } 71 | 72 | .openai_input_submit_btn_icon, 73 | .openai_input_refresh_btn_icon { 74 | width: 80%; 75 | } 76 | 77 | .openai_input_bar { 78 | display: flex; 79 | width: 100%; 80 | } 81 | 82 | .block_openai_chat img { 83 | transform: scale(0.7); 84 | } 85 | 86 | .block_openai_chat #openai_input, 87 | .openai_input_bar input { 88 | padding: 0.5rem; 89 | border-radius: 0.5rem 0 0 0.5rem; 90 | border: 1px solid gray; 91 | width: 100%; 92 | transition: background 0.4s ease; 93 | } 94 | 95 | .block_openai_chat #openai_input.error { 96 | border: 1px solid red; 97 | } 98 | 99 | .block_openai_chat .openai_message { 100 | padding: 0.75rem 1rem; 101 | background: #f4f4f4; 102 | border-radius: 0.5rem; 103 | margin-bottom: 1.75rem; 104 | width: fit-content; 105 | max-width: 90%; 106 | animation: block_openai_chat_popup 0.4s cubic-bezier(0.87, 0, 0.13, 1); 107 | position: relative; 108 | } 109 | 110 | .block_openai_chat .openai_message:before { 111 | position: absolute; 112 | top: -1.5rem; 113 | left: 0; 114 | color: gray; 115 | opacity: 0; 116 | animation: block_openai_chat_fade-in 0.4s ease 0.4s forwards; 117 | } 118 | 119 | .block_openai_chat .openai_message.user { 120 | align-self: flex-end; 121 | text-align: right; 122 | } 123 | 124 | .block_openai_chat .openai_message.user:before { 125 | right: 0; 126 | left: unset; 127 | } 128 | 129 | .block_openai_chat .openai_message.bot { 130 | background: var(--blue); 131 | color: var(--white); 132 | } 133 | 134 | .block_openai_chat .openai_message.loading { 135 | animation: block_openai_chat_thinking 1s ease infinite; 136 | } 137 | 138 | .block_openai_chat .openai_message.loading:before { 139 | animation: none; 140 | opacity: 0; 141 | } 142 | 143 | .block_openai_chat.disabled, 144 | .block_openai_chat .disabled { 145 | opacity: 0.25; 146 | pointer-events: none; 147 | } 148 | 149 | .block_openai_chat.expanded { 150 | position: fixed; 151 | height: 70vh; 152 | width: 30rem; 153 | left: 50%; 154 | top: 50%; 155 | transform: translate(-50%, -50%); 156 | outline: 100vw solid #00000029; 157 | z-index: 2; 158 | background-color: white !important; 159 | } 160 | 161 | .block_openai_chat.expanded .card-body { 162 | overflow-y: auto; 163 | } 164 | 165 | .block_openai_chat.expanded #openai_chat_log { 166 | max-height: unset; 167 | overflow-y: unset; 168 | padding-bottom: 3rem !important; 169 | padding-top: 1rem; 170 | min-height: 2rem; 171 | } 172 | 173 | .block_openai_chat.expanded #control_bar { 174 | display: flex; 175 | gap: .5rem; 176 | position: fixed; 177 | bottom: 1rem; 178 | width: calc(100% - 2rem); 179 | } 180 | 181 | .block_openai_chat.expanded .openai_message { 182 | width: fit-content !important; 183 | } 184 | 185 | .block_openai_chat .recording { 186 | width: 0.5rem; 187 | height: 0.5rem; 188 | background: #ff0000; 189 | position: absolute; 190 | top: 1.5rem; 191 | right: 3rem; 192 | border-radius: 99rem; 193 | filter: opacity(0.5); 194 | animation: block_openai_chat_thinking 3s linear infinite; 195 | } 196 | 197 | .block_openai_chat input { 198 | padding: 0.5rem; 199 | border-radius: 0.5rem; 200 | border: 1px solid grey; 201 | } 202 | 203 | .block_openai_chat .report_container { 204 | display: flex; 205 | gap: 1rem; 206 | margin-bottom: 1rem; 207 | } 208 | 209 | /* dumbass remui styles */ 210 | .block_openai_chat.expanded .block-header-wrapper { 211 | padding: 1rem !important; 212 | } 213 | .block_openai_chat.expanded .edw-block-body { 214 | box-shadow: none !important; 215 | } 216 | .block_openai_chat .edw-block-body #popout { 217 | top: 0; 218 | } 219 | .block_openai_chat .edw-block-body .recording { 220 | top: 0.75rem; 221 | } 222 | .block_openai_chat.expanded .edw-block-body #popout { 223 | top: 0.75rem; 224 | } 225 | .block_openai_chat.expanded .edw-block-body .recording { 226 | top: 1.5rem; 227 | } 228 | .block_openai_chat.expanded .edw-block-body #control_bar { 229 | width: calc(100% - 4rem); 230 | } 231 | .block_openai_chat.expanded .block-body-wrapper { 232 | height: calc(100% - 4rem); 233 | overflow: auto; 234 | } 235 | #block-region-side-pre .block_openai_chat.expanded .block-body-wrapper { 236 | margin-left: 0; 237 | margin-right: 0; 238 | padding: 0 2rem; 239 | } 240 | .drawer { 241 | filter: unset !important; 242 | } 243 | 244 | @media screen and (max-width: 750px) { 245 | .drawerheader { 246 | pointer-events: none; 247 | } 248 | .drawerheader button { 249 | pointer-events: all; 250 | } 251 | .block_openai_chat.expanded { 252 | transform: unset; 253 | top: 0; 254 | left: 0; 255 | width: 100vw; 256 | height: 100vh; 257 | } 258 | .block_openai_chat.expanded .openai_input_popout_btn { 259 | right: 3rem; 260 | } 261 | .block_openai_chat.expanded .recording { 262 | right: 5.5rem; 263 | } 264 | .block_openai_chat .report_container { 265 | flex-direction: column; 266 | } 267 | } 268 | 269 | @keyframes block_openai_chat_popup { 270 | 0% { 271 | opacity: 0; 272 | transform: translateY(5px); 273 | } 274 | 275 | 70% { 276 | opacity: 1; 277 | transform: translateY(-2.5px); 278 | } 279 | 280 | 85% { 281 | transform: translateY(2.5px); 282 | } 283 | 284 | 100% { 285 | transform: translateY(0); 286 | } 287 | } 288 | 289 | @keyframes block_openai_chat_thinking { 290 | 0% { 291 | opacity: 1; 292 | } 293 | 294 | 50% { 295 | opacity: 0.25; 296 | } 297 | 298 | 100% { 299 | opacity: 1; 300 | } 301 | } 302 | 303 | @keyframes block_openai_chat_fade-in { 304 | from { 305 | opacity: 0; 306 | } 307 | 308 | to { 309 | opacity: 1; 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /templates/control_bar.mustache: -------------------------------------------------------------------------------- 1 | {{! 2 | This file is part of Moodle - http://moodle.org/ 3 | 4 | Moodle is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | Moodle is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with Moodle. If not, see . 16 | }} 17 | {{! 18 | @template block_openai_chat/control_bar 19 | 20 | This template renders the control_bar. 21 | 22 | Example context (json): 23 | { 24 | "logging_enabled": boolean, true if logging is enabled in the plugin settings 25 | "is_edit_mode": boolean; true if edit mode is active 26 | "pix_popout": relative url of the popout pix to the root of moodle 27 | "pix_arrow_right": relative url of the arrow right pix to the root of moodle 28 | "pix_refresh": relative url of the refresh pix to the root of moodle 29 | } 30 | }} 31 | 32 | {{^is_edit_mode}} 33 | {{#logging_enabled}} 34 |
35 | {{/logging_enabled}} 36 | 39 | {{/is_edit_mode}} 40 |
41 |
42 | 43 | 44 | 47 |
48 | 51 |
52 | -------------------------------------------------------------------------------- /templates/report_page.mustache: -------------------------------------------------------------------------------- 1 | {{! 2 | This file is part of Moodle - http://moodle.org/ 3 | 4 | Moodle is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | Moodle is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with Moodle. If not, see . 16 | }} 17 | {{! 18 | @template block_openai_chat/report_page 19 | 20 | This template renders the report page form 21 | 22 | Example context (json): 23 | { 24 | "courseid": int, the ID of the course we are looking at 25 | "link": string, the URL for the form action 26 | "user": string, the value of the user field 27 | "starttime": string, the value of the starttime field 28 | "endtime": string, the value of the endtime field 29 | } 30 | }} 31 | 32 |
33 | 34 |
35 |
36 | 37 | 38 |
39 |
40 | 41 | 42 |
43 |
44 | 45 | 46 |
47 |
48 | 49 |
50 |
-------------------------------------------------------------------------------- /version.php: -------------------------------------------------------------------------------- 1 | . 16 | 17 | /** 18 | * Version information 19 | * 20 | * @package block_openai_chat 21 | * @copyright 2022 Bryce Yoder 22 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 | */ 24 | 25 | defined('MOODLE_INTERNAL') || die(); 26 | 27 | $plugin->component = 'block_openai_chat'; 28 | $plugin->version = 2025021700; 29 | $plugin->requires = 2022041600; 30 | $plugin->maturity = MATURITY_STABLE; 31 | $plugin->release = '3.0.1'; 32 | --------------------------------------------------------------------------------