├── .env.example ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── pull_request_template.md ├── .gitignore ├── LICENSE ├── README.md ├── create_backlog_tickets_for_all.py ├── init_connections.py ├── oa ├── oa_cli.py ├── requirements.txt ├── src ├── agents │ ├── architect │ │ └── __init__.py │ ├── intern │ │ ├── __init__.py │ │ ├── generators │ │ │ └── diff_generator.py │ │ └── processors.py │ └── reviewer │ │ ├── __init__.py │ │ ├── generators │ │ └── code_review_generator.py │ │ └── processors.py ├── constants.py ├── helpers │ ├── board.py │ ├── github.py │ └── trello.py ├── language_models.py ├── lib │ ├── mistral_chat_completion.py │ ├── mistral_dspy.py │ ├── ported_clients.py │ ├── ported_exceptions.py │ └── terminal.py └── models.py ├── start_architecting.py ├── start_coding.py ├── test_gh_helper.py └── test_trello_helper.py /.env.example: -------------------------------------------------------------------------------- 1 | GITHUB_REPO_URL=MyOrg/myRepo 2 | GITHUB_TOKEN=github_pat_1234567890 3 | OPENAI_API_KEY=sample_openai_key 4 | TRELLO_API_KEY=1234 5 | TRELLO_API_SECRET=4321 6 | TRELLO_TOKEN=ABCD1234 7 | TRELLO_TOKEN_SECRET=abcd1234 8 | TRELLO_BOARD_ID=1234abcd 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Additional context** 24 | Add any other context about the problem here. 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Got a cool feature idea? Let us know! 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A description of what you want to happen. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | Please include a summary of the changes and the related issue. List any dependencies that are required for this change. 4 | 5 | Fixes # (issue) 6 | 7 | ## Type of change 8 | 9 | - [ ] Refactoring 10 | - [ ] Bug fix (non-breaking change which fixes an issue) 11 | - [ ] New feature (non-breaking change which adds functionality) 12 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 13 | - [ ] This change requires a documentation update 14 | 15 | # How Has This Been Tested? 16 | 17 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. 18 | 19 | # Checklist: 20 | 21 | - [ ] I have performed a self-review of my code 22 | - [ ] My commits are self contained changes with descriptive messages 23 | - [ ] I have commented my code, particularly in hard-to-understand areas 24 | - [ ] I have made corresponding changes to the documentation 25 | - [ ] My changes generate no new warnings 26 | - [ ] (If relevant) I have written a test for my change 27 | - [ ] New and existing tests pass 28 | - [ ] Any dependent changes have been merged and published in downstream modules 29 | - [ ] (If relevant) If there's a visual change, I added a screenshot to the PR 30 | 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Environments 2 | .env 3 | .venv 4 | *env/ 5 | ENV/ 6 | env.bak/ 7 | venv.bak/ 8 | 9 | # PyCharm 10 | .idea/ 11 | 12 | # Mac OS 13 | .DS_Store 14 | 15 | # PyCache 16 | **/__pycache__ 17 | 18 | # Private keys 19 | *.pem 20 | *.log 21 | creds.json 22 | *.txt 23 | *.ipynb -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Discord](https://dcbadge.vercel.app/api/server/WCNEFsrtjw)](https://discord.gg/WCNEFsrtjw) 2 | [![Stargazers][stars-shield]][stars-url] 3 | [![Issues][issues-shield]][issues-url] 4 | [![License][license-shield]][license-url] 5 | 6 |

Open Architect

7 | 8 |

9 | Orchestrate your fleet of AI software designers, engineers and reviewers! 10 | 11 | image 12 |
13 |
14 | Created at the MistralAI hackathon in SF 15 |
16 |

17 | 18 | Just create tickets (or have an AI architect assist you), and let the agents do the work. Your approval is required to merge PRs, so no bug or wrong code is ever introduced without your approval! 19 | 20 | ## Setup 21 | 22 | 1. Clone this repo 23 | 2. Install dependencies with `pip install -r requirements.txt` 24 | 3. Enter the infos related to the repository in which you want to work in `settings.json` or run `oa setup` 25 | 4. Profit 26 | 27 | ### How to connect to Github 28 | 29 | 1. Be part of the org of your repo 30 | 2. Go to https://github.com/settings/tokens?type=beta and create a personnal access token for the repo 31 | 3. Run the `init_connections.py` script and provide the URL to your repo and the access token 32 | 33 | ### Hot to connect to Trello 34 | 35 | 1. Connect to https://trello.com/ and log in. Navigate to your target Board. Save the Board ID. 36 | 2. Create a PowerUp for your Workspace at https://trello.com/power-ups/admin (you don't need the Iframe connector URL). Save your API Key and Secret 37 | 3. Run the `init_connections.py` script and provide the needed secrets 38 | 39 | ### Other requirement 40 | 41 | We currently use OpenAI for our inferences, so you'll need an [OpenAI API key](https://platform.openai.com/api-keys) with some credits (we currently use GPT3.5 Turbo and GPT4, see pricing [here](https://openai.com/pricing#:~:text=1M%20tokens-,GPT%2D3.5%20Turbo,-GPT%2D3.5%20Turbo)). 42 | 43 | Then run the `init_connections.py` script and provide your key 44 | 45 | 46 | ## How to run 47 | 48 | Design tickets and add them to your backlog with: 49 | - `streamlit run start_architecting.py` to spawn an architect running in a chatbot that will create code tickets with you. 50 | 51 | Run your fleet with: 52 | - `./oa start intern` to spawn a developer that will process tickets and open PRs with code. 53 | - `./oa start reviewer` to spawn a reviewer that will review PRs and ask for changes. 54 | 55 | You can also start multiple ones with `./oa start agent1 agent2` 56 | 57 | ## Contributing 58 | 59 | This is intended to be a collaborative project, and we'd love to take suggestions for new features, improvements, and fixes! 60 | 61 | - If there is something you'd like us to work on, feel free to open an **Issue** with the adequate tag and a good description. If it's a bug, please add steps to reproduce it. 62 | - If you have a contribution you'd like to make: first of all, thanks! You rock! Please open a PR and we'll review it as soon as we can! 63 | 64 | [stars-shield]: https://img.shields.io/github/stars/OpenArchitectAI/open-architect?style=for-the-badge 65 | [stars-url]: https://github.com/OpenArchitectAI/open-architect/stargazers 66 | [issues-shield]: https://img.shields.io/github/issues/OpenArchitectAI/open-architect?style=for-the-badge 67 | [issues-url]: https://github.com/OpenArchitectAI/open-architect/issues 68 | [license-shield]: https://img.shields.io/github/license/OpenArchitectAI/open-architect?style=for-the-badge 69 | [license-url]: https://github.com/OpenArchitectAI/open-architect/blob/main/LICENSE 70 | -------------------------------------------------------------------------------- /create_backlog_tickets_for_all.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | from random import randint 3 | import os 4 | 5 | from src.models import Ticket 6 | from src.helpers.trello import TrelloHelper 7 | 8 | load_dotenv() 9 | 10 | N_TICKETS = 10 11 | 12 | trello_api_key = os.getenv("TRELLO_API_KEY") 13 | trello_api_secret = os.getenv("TRELLO_API_SECRET") 14 | trello_token = os.getenv("TRELLO_TOKEN") 15 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 16 | 17 | th = TrelloHelper(trello_api_key, trello_token, trello_board_id) 18 | 19 | tickets = [ 20 | Ticket( 21 | title="Test Ticket " + str(randint(0, 10000)), 22 | description="This is a test ticket", 23 | ) 24 | for _ in range(N_TICKETS) 25 | ] 26 | th.push_tickets_to_backlog_and_assign(tickets) 27 | -------------------------------------------------------------------------------- /init_connections.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | 4 | from trello import create_oauth_token 5 | 6 | load_dotenv() 7 | 8 | gh_repo = os.getenv("GITHUB_REPO_URL") 9 | gh_api_token_intern = os.getenv("GITHUB_TOKEN_INTERN") 10 | gh_api_token_reviewer = os.getenv("GITHUB_TOKEN_REVIEWER") 11 | openai_api_key = os.getenv("OPENAI_API_KEY") 12 | trello_api_key = os.getenv("TRELLO_API_KEY") 13 | trello_api_secret = os.getenv("TRELLO_API_SECRET") 14 | trello_token = os.getenv("TRELLO_TOKEN") 15 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 16 | 17 | if gh_repo is None: 18 | gh_repo = input("Enter the GitHub repo URL: ") 19 | if gh_api_token_intern is None: 20 | gh_api_token_intern = input("Enter your GitHub Personnal Access token for the intern (https://github.com/settings/tokens): ") 21 | if gh_api_token_reviewer is None: 22 | gh_api_token_reviewer = input("Enter your GitHub Personnal Access token for the reviewer (https://github.com/settings/tokens): ") 23 | 24 | if trello_api_key is None: 25 | trello_api_key = input("Enter your Trello API key (https://trello.com/power-ups/admin): ") 26 | if trello_api_secret is None: 27 | trello_api_secret = input("Enter your Trello API secret (https://trello.com/power-ups/admin): ") 28 | if trello_token is None: 29 | auth_token = create_oauth_token(key=trello_api_key, secret=trello_api_secret, name='Trello API') 30 | trello_token = auth_token['oauth_token'] 31 | if trello_board_id is None: 32 | trello_board_id = input("Enter your Trello Board ID: ") 33 | 34 | if openai_api_key is None: 35 | openai_api_key = input("Enter your OpenAI API key (https://platform.openai.com/api-keys): ") 36 | 37 | 38 | # Write them back to the .env file 39 | with open(".env", "w") as f: 40 | f.write(f"GITHUB_REPO_URL={gh_repo}\n") 41 | f.write(f"GITHUB_TOKEN_INTERN={gh_api_token_intern}\n") 42 | f.write(f"GITHUB_TOKEN_REVIEWER={gh_api_token_reviewer}\n") 43 | f.write(f"OPENAI_API_KEY={openai_api_key}\n") 44 | f.write(f"TRELLO_API_KEY={trello_api_key}\n") 45 | f.write(f"TRELLO_API_SECRET={trello_api_secret}\n") 46 | f.write(f"TRELLO_TOKEN={trello_token}\n") 47 | f.write(f"TRELLO_BOARD_ID={trello_board_id}\n") 48 | 49 | print("Environment variables set up successfully") -------------------------------------------------------------------------------- /oa: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get the directory of the current script 4 | SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" 5 | 6 | # Run the Python script with the provided arguments 7 | python "${SCRIPT_DIR}/oa_cli.py" "$@" 8 | -------------------------------------------------------------------------------- /oa_cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from dotenv import load_dotenv 3 | from threading import Thread 4 | import os 5 | from src.helpers.github import GHHelper 6 | from src.helpers.trello import TrelloHelper 7 | from src.agents.intern import Intern 8 | from src.agents.reviewer import Reviewer 9 | 10 | 11 | def start_intern(gh_helper_intern, trello_helper): 12 | intern = Intern("Alex", gh_helper=gh_helper_intern, board_helper=trello_helper) 13 | intern_thread = Thread(target=intern.run) 14 | intern_thread.start() 15 | 16 | 17 | def start_reviewer(gh_helper_reviewer, trello_helper): 18 | reviewer = Reviewer( 19 | "Charlie", gh_helper=gh_helper_reviewer, board_helper=trello_helper 20 | ) 21 | reviewer_thread = Thread(target=reviewer.run) 22 | reviewer_thread.start() 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser(description="Open Architect CLI") 27 | parser.add_argument("command", choices=["run"], help="Command to execute") 28 | parser.add_argument( 29 | "agents", nargs="+", choices=["intern", "reviewer"], help="Agents to run" 30 | ) 31 | args = parser.parse_args() 32 | 33 | load_dotenv() 34 | 35 | gh_repo = os.getenv("GITHUB_REPO_URL") 36 | gh_api_token_intern = os.getenv("GITHUB_TOKEN_INTERN") 37 | gh_api_token_reviewer = os.getenv("GITHUB_TOKEN_REVIEWER") 38 | openai_api_key = os.getenv("OPENAI_API_KEY") 39 | trello_api_key = os.getenv("TRELLO_API_KEY") 40 | trello_api_secret = os.getenv("TRELLO_API_SECRET") 41 | trello_token = os.getenv("TRELLO_TOKEN") 42 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 43 | 44 | if ( 45 | gh_repo is None 46 | or gh_api_token_intern is None 47 | or gh_api_token_reviewer is None 48 | or openai_api_key is None 49 | or trello_api_key is None 50 | or trello_api_secret is None 51 | or trello_token is None 52 | or trello_board_id is None 53 | ): 54 | print( 55 | "Please run the init_connections.py script to set up the environment variables" 56 | ) 57 | return 58 | 59 | gh_helper_intern = GHHelper(gh_api_token_intern, gh_repo) 60 | gh_helper_reviewer = GHHelper(gh_api_token_reviewer, gh_repo) 61 | trello_helper = TrelloHelper(trello_api_key, trello_token, trello_board_id) 62 | 63 | if args.command == "run": 64 | for agent in args.agents: 65 | if agent == "intern": 66 | start_intern(gh_helper_intern, trello_helper) 67 | elif agent == "reviewer": 68 | start_reviewer(gh_helper_reviewer, trello_helper) 69 | 70 | 71 | if __name__ == "__main__": 72 | main() 73 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.9.3 2 | aiosignal==1.3.1 3 | alembic==1.13.1 4 | altair==5.2.0 5 | annotated-types==0.6.0 6 | anyio==4.3.0 7 | attrs==23.2.0 8 | backoff==2.2.1 9 | blinker==1.7.0 10 | cachetools==5.3.3 11 | certifi==2024.2.2 12 | cffi==1.16.0 13 | charset-normalizer==3.3.2 14 | click==8.1.7 15 | colorlog==6.8.2 16 | cryptography==42.0.5 17 | datasets==2.14.7 18 | Deprecated==1.2.14 19 | dill==0.3.7 20 | distro==1.9.0 21 | dspy-ai==2.4.0 22 | filelock==3.13.3 23 | frozenlist==1.4.1 24 | fsspec==2023.10.0 25 | gitdb==4.0.11 26 | GitPython==3.1.42 27 | h11==0.14.0 28 | httpcore==1.0.5 29 | httpx==0.27.0 30 | huggingface-hub==0.22.1 31 | idna==3.6 32 | Jinja2==3.1.3 33 | joblib==1.3.2 34 | jsonschema==4.21.1 35 | jsonschema-specifications==2023.12.1 36 | Mako==1.3.2 37 | markdown-it-py==3.0.0 38 | MarkupSafe==2.1.5 39 | mdurl==0.1.2 40 | multidict==6.0.5 41 | multiprocess==0.70.15 42 | numpy==1.26.4 43 | oauthlib==3.2.2 44 | openai==1.14.3 45 | optuna==3.6.0 46 | orjson==3.10.0 47 | packaging==23.2 48 | pandas==2.2.1 49 | pillow==10.2.0 50 | protobuf==4.25.3 51 | py-trello==0.19.0 52 | pyarrow==15.0.2 53 | pyarrow-hotfix==0.6 54 | pycparser==2.21 55 | pydantic==2.5.0 56 | pydantic_core==2.14.1 57 | pydeck==0.8.1b0 58 | PyGithub==2.3.0 59 | Pygments==2.17.2 60 | PyJWT==2.8.0 61 | PyNaCl==1.5.0 62 | python-dateutil==2.9.0.post0 63 | python-dotenv==1.0.1 64 | pytz==2024.1 65 | PyYAML==6.0.1 66 | referencing==0.34.0 67 | regex==2023.12.25 68 | requests==2.31.0 69 | requests-oauthlib==2.0.0 70 | rich==13.7.1 71 | rpds-py==0.18.0 72 | six==1.16.0 73 | smmap==5.0.1 74 | sniffio==1.3.1 75 | SQLAlchemy==2.0.29 76 | streamlit==1.32.2 77 | tenacity==8.2.3 78 | toml==0.10.2 79 | toolz==0.12.1 80 | tornado==6.4 81 | tqdm==4.66.2 82 | typing_extensions==4.10.0 83 | tzdata==2024.1 84 | ujson==5.9.0 85 | urllib3==2.2.1 86 | wrapt==1.16.0 87 | xxhash==3.4.1 88 | yarl==1.9.4 89 | -------------------------------------------------------------------------------- /src/agents/architect/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import Any, List 3 | 4 | from pydantic import BaseModel 5 | from openai import OpenAI 6 | import streamlit as st 7 | 8 | from src.helpers.github import GHHelper 9 | from src.helpers.board import BoardHelper 10 | from src.lib.terminal import colorize 11 | from src.models import Ticket 12 | 13 | 14 | class ArchitectAgentRequest(BaseModel): 15 | question: str 16 | history: Any 17 | 18 | class CreateTicketsRequest(BaseModel): 19 | question: str 20 | history: Any 21 | 22 | class CreateSubtasksRequest(BaseModel): 23 | question: str 24 | history: Any 25 | 26 | class AskFollowupQuestionsRequest(BaseModel): 27 | question: str 28 | history: Any 29 | 30 | class ReferenceExistingCodeRequest(BaseModel): 31 | question: str 32 | history: Any 33 | 34 | class Architect: 35 | def __init__(self, name, gh_helper: GHHelper, board_helper: BoardHelper): 36 | self.name = name 37 | self.gh_helper = gh_helper 38 | self.board_helper = board_helper 39 | self.log_name = colorize(f"[{self.name} the Architect]", bold=True, color="green") 40 | print( 41 | f"{self.log_name} Nice to meet you, I'm {self.name} the Architect! I'm here to help you break down your tasks into smaller tickets and create them for you! 🏗️🔨📝" 42 | ) 43 | 44 | def run(self): 45 | # Step 1: Create a chat interface 46 | st.title("Open Architect") 47 | 48 | if "messages" not in st.session_state: 49 | st.session_state.messages = [] 50 | st.session_state.messages.append({"role": "assistant", "content": "Hey! What new features would you like to add to your project " + str(self.gh_helper.repo.full_name) + " today? I'll help you break it down to subtasks, figure out how to integrate with your existing code and then set my crew of SWE agents to get it built out for you!"}) 51 | 52 | for message in st.session_state.messages: 53 | with st.chat_message(message["role"]): 54 | st.markdown(message["content"]) 55 | 56 | if prompt := st.chat_input("What do you want to build today?"): 57 | st.session_state.messages.append({"role": "user", "content": prompt}) 58 | with st.chat_message("user"): 59 | st.markdown(prompt) 60 | 61 | with st.chat_message("assistant"): 62 | architectureAgentReq = ArchitectAgentRequest( 63 | question=prompt, 64 | history=[ 65 | msg["content"] 66 | for msg in st.session_state.messages 67 | ], 68 | ) 69 | response = self.compute_response(architectureAgentReq) 70 | res = st.write(response) 71 | 72 | st.session_state.messages.append({"role": "assistant", "content": response}) 73 | 74 | def compute_response(self, architectAgentRequest: ArchitectAgentRequest): 75 | """ 76 | Routing logic for all tools supported by the feedback agent. 77 | """ 78 | messages = [ 79 | {"role": "system", "content": f"""You are a principal software engineer who is responsible for mentoring engineers and breaking down tasks into smaller tickets. 80 | 81 | Reference the existing codebase to determine how to build the features in the existing code. 82 | 83 | Once you know what to build, you can then break down the task into smaller tickets and then create those tickets. 84 | 85 | After you have all the subtasks proceed to creating the tasks - "Here are the subtasks that I have created for this task - are we good to create the tasks?". 86 | 87 | Create the tasks for the user. - "Creating your tasks". 88 | 89 | You have been given the following question: {architectAgentRequest.question}. Based on the conversation so far {architectAgentRequest.history}, do the following 90 | 91 | - if there is context about what the user is trying to build, reference their existing code 92 | - if there are references to their existing code, create subtasks 93 | - if there are subtasks, ask to create tasks 94 | 95 | """}, 96 | {"role": "user", "content": f"address the user's question: {architectAgentRequest.question}"}] 97 | 98 | tools = [ 99 | # { 100 | # "type": "function", 101 | # "function": { 102 | # "name": "ask_followup_questions", 103 | # "description": "Ask additional questions to better understand what the user wants to build. This will help you to better understand the project requirements and break the task down into smaller tickets. You should ask questions to clarify the project requirements and get a detailed description of the project. You should not create tickets until you have a clear understanding of the project requirements. Once you have all the details of the project, you can then break down the task into smaller tickets and create those tickets. After you have all the subtasks, proceed to creating the tasks. You should ask the user if they are good to create the tasks and then create the tasks for the user.", 104 | # "parameters": {"type": "object", "properties": {}, "required": []}, 105 | # }, 106 | # }, 107 | { 108 | "type": "function", 109 | "function": { 110 | "name": "create_subtasks", 111 | "description": "If the user asks to break it down into parts, then call create_subtasks. Based on the user's initial descriptions of the task, break the task down into detailed subtasks to accomplish the larger task. Each subtask should include a title and a detailed description of the subtask.", 112 | "parameters": {"type": "object", "properties": {}, "required": []}, 113 | }, 114 | }, 115 | { 116 | "type": "function", 117 | "function": { 118 | "name": "create_tasks", 119 | "description": "When the user asks to create tasks or create tickets in trello, call create tickets. Create tickets based on the subtasks that are generated for the task. This will actually take the subtasks generated and create the trello tickets for them.", 120 | "parameters": {"type": "object", "properties": {}, "required": []}, 121 | }, 122 | }, 123 | { 124 | "type": "function", 125 | "function": { 126 | "name": "reference_existing_code", 127 | "description": "If the user asks to implement in their codebase. Go through the existing code in order to better understand how to build the requested user feature in the codebase. Analyze the code files, and determine the best way to build out support for the new features in the existing code. ", 128 | "parameters": {"type": "object", "properties": {}, "required": []}, 129 | } 130 | }, 131 | ] 132 | 133 | openai_client = OpenAI() 134 | 135 | response = openai_client.chat.completions.create( 136 | model="gpt-3.5-turbo-1106", 137 | messages=messages, 138 | tools=tools, 139 | tool_choice="auto", 140 | ) 141 | response_message = response.choices[0].message 142 | tool_calls = response_message.tool_calls 143 | function_request_mapping = { 144 | # "ask_followup_questions": AskFollowupQuestionsRequest( 145 | # question=architectAgentRequest.question, 146 | # history=architectAgentRequest.history, 147 | # ), 148 | "create_tasks": CreateTicketsRequest( 149 | question=architectAgentRequest.question, 150 | history=architectAgentRequest.history, 151 | ), 152 | "create_subtasks": CreateSubtasksRequest( 153 | question=architectAgentRequest.question, 154 | history=architectAgentRequest.history, 155 | ), 156 | "reference_existing_code": ReferenceExistingCodeRequest( 157 | question=architectAgentRequest.question, 158 | history=architectAgentRequest.history, 159 | ) 160 | } 161 | 162 | if tool_calls: 163 | available_functions = { 164 | # "ask_followup_questions": ask_followup_questions, 165 | "create_tasks": self.create_tasks, 166 | "create_subtasks": self.create_subtasks, 167 | "reference_existing_code": self.reference_existing_code, 168 | } 169 | messages.append(response_message) 170 | for tool_call in tool_calls: 171 | function_name = tool_call.function.name 172 | print("Function called is: " + str(function_name)) 173 | function_to_call = available_functions[function_name] 174 | print("Function to call is: " + str(function_to_call)) 175 | function_args = function_request_mapping[function_name] 176 | print("Function args are: " + str(function_args)) 177 | return function_to_call(function_args) 178 | 179 | print("returning message: " + str(response_message.content)) 180 | return response_message.content 181 | 182 | 183 | def ask_followup_questions(self, askFollowupQuestionsRequest: AskFollowupQuestionsRequest): 184 | """ 185 | This function will be responsible for asking follow up questions to better understand what the user wants to build. 186 | """ 187 | try: 188 | questionPrompt = f"""Given the description of the project so far {askFollowupQuestionsRequest.history} and the user's latest question {askFollowupQuestionsRequest.question}, come up with additional follow up questions to further deepen your understanding of what the user is trying to build. Ask more questions about the front end, backend, or hosting requirements. Understand the details of the product features. Ask questions until you are confident that you are able to generate a detailed execution plan for the project. The response should be a list of questions that you can ask the user to better understand the project requirements. Limit to 2-3 questions at a time. 189 | """ 190 | 191 | openai_client = OpenAI() 192 | response = openai_client.chat.completions.create( 193 | model="gpt-3.5-turbo-1106", 194 | messages=[ 195 | { 196 | "role": "system", 197 | "content": "You are a senior staff engineer, who is responsible for asking in depth follow up questions to deepen your understanding of a problem before you determine a plan to build it.", 198 | }, 199 | {"role": "user", "content": questionPrompt}, 200 | ], 201 | ) 202 | response = response.choices[0].message.content 203 | 204 | return response 205 | 206 | except Exception as e: 207 | print("Failed to generate subtasks with error " + str(e)) 208 | return "Failed to generate subtasks with error " + str(e) 209 | 210 | 211 | def reference_existing_code(self, referenceExistingCodeRequest: ReferenceExistingCodeRequest): 212 | """ 213 | This method should take the user's question and search the current codebase for all references to that question. It should then summarize the current code and how the user's request can be built within that codebase. 214 | """ 215 | # First get the codebase dict 216 | codebase_dict = self.gh_helper.get_entire_codebase() 217 | 218 | # Now search the codebase for the user's question 219 | codebase = codebase_dict.files 220 | 221 | try: 222 | questionPrompt = f"""Given the description of the project so far {referenceExistingCodeRequest.history} and the user's latest question {referenceExistingCodeRequest.question}, figure out which files in the codebase are most relevant for the user in order to best design a solution to the feature requests. You have this codebase to reference {codebase}. If the feature is completely irrelevant to the user's existing code, let the user know that the feature request seems to be unrelated to the existing codebase and ask them to verify if they do indeed want to build that feature in the current codebase. 223 | 224 | If the feature request seems relevant, your response should be something like 225 | 226 | Going through your existing codebase, I would suggest that we build out _feature_ by modifying the following files _files_ and adding the following functionality to them _functionality description_. Happy to break this down into granular subtasks for you next on how I'm planning to approach this execution. 227 | """ 228 | openai_client = OpenAI() 229 | 230 | response = openai_client.chat.completions.create( 231 | model="gpt-3.5-turbo-1106", 232 | messages=[ 233 | { 234 | "role": "system", 235 | "content": "You are a senior staff engineer, who is responsible for going through the codebase in detail and coming up with an execution plan of how to build out certain features. You need to reference the codebase to determine which files are most relevant for the user to build out the feature requests and then come up with an execution plan to build it out across several subtasks.", 236 | }, 237 | {"role": "user", "content": questionPrompt}, 238 | ], 239 | ) 240 | response = response.choices[0].message.content 241 | 242 | return response 243 | 244 | except Exception as e: 245 | print("Failed to generate subtasks with error " + str(e)) 246 | return "Failed to generate subtasks with error " + str(e) 247 | 248 | def create_tasks(self, createTicketsRequest: CreateTicketsRequest): 249 | """ 250 | This function will be responsible for creating multiple tickets in parallel. 251 | """ 252 | # Given the conversation history, create tickets for each subtask 253 | try: 254 | questionPrompt = f"""Given the following subtask information {createTicketsRequest.history}, generate a list of tasks in the following json format 255 | {{ 256 | "subtasks": [ 257 | {{ 258 | "title": "title of the ticket" 259 | "description": "description of the ticket" 260 | }}, 261 | ] 262 | }} 263 | 264 | Take each subtask and generate a title and description. Each one should correspond with a list element in the subtask list. You need to cover all of the subtasks that are mentioned and create a ticket for each one. Each ticket should include the title and description of the subtask. The response should be a list of these json objects for each subtask. 265 | """ 266 | 267 | openai_client = OpenAI() 268 | response = openai_client.chat.completions.create( 269 | model="gpt-3.5-turbo-1106", 270 | messages=[ 271 | { 272 | "role": "system", 273 | "content": "You are a senior staff engineer, who is responsible for breaking up large complex tasks into small, granular subtasks that more junior engineers can easily work through and execute on.", 274 | }, 275 | {"role": "user", "content": questionPrompt}, 276 | ], 277 | 278 | response_format={ "type": "json_object" } 279 | ) 280 | 281 | subtasks = response.choices[0].message.content 282 | print("The tasks created are: " + str(subtasks)) 283 | subtask_json = json.loads(subtasks)["subtasks"] 284 | 285 | # Create a list of ticket objects from the subtasks and call create 286 | tickets = [] 287 | ticket_titles = [] 288 | for subtask in subtask_json: 289 | ticket = Ticket(title=subtask["title"], description=subtask["description"]) 290 | tickets.append(ticket) 291 | ticket_titles.append(ticket.title) 292 | 293 | createdTickets = self.board_helper.push_tickets_to_backlog_and_assign(tickets) 294 | 295 | ticketMarkdown = generate_ticket_markdown(createdTickets) 296 | 297 | return "Great! I've just created the following tickets and assigned them to our agents to get started on immediately \n" + ticketMarkdown 298 | 299 | # response = client.chat.completions.create( 300 | # model="gpt-3.5-turbo-1106", 301 | # messages=[ 302 | # { 303 | # "role": "system", 304 | # "content": "You are a senior staff engineer, who has just created several tasks for a project. You now need to let the user know which tasks have been created so that they can be worked on. Let them know the titles of the tasks that have been created and say that you will get to working on them right away.", 305 | # }, 306 | # { 307 | # "role": "user", 308 | # "content": f"I've just created the following tickets {createdTickets}", 309 | # }, 310 | # ], 311 | # ) 312 | # finalResponse = response.choices[0].message.content 313 | # return finalResponse 314 | 315 | except Exception as e: 316 | print("Failed to generate subtasks with error " + str(e)) 317 | return "Failed to generate subtasks with error " + str(e) 318 | 319 | # Define the tool for breaking up the overall project description into multiple smaller tasks and then getting user feedback on them 320 | def create_subtasks(self, project_description): 321 | """ 322 | This function will be responsible for breaking up the overall project description into multiple smaller tasks and then getting user feedback on them. 323 | """ 324 | try: 325 | questionPrompt = f"""Given the following project description {project_description}, please break it down into smaller tasks that can be accomplished to complete the project. Each task should include a title and a detailed description of the task. The subtasks should all be small enough to be completed in a single day and should represent a micro chunk of work that a user can do to build up to solving the overall task. Focus only on engineering tasks, don't include design or user testing etc. The response should be in the following format 326 | 327 | Brief description of the task and breakdown. Don't include 'Title of the task' in the output, replace it with the actual title - 328 | 329 | 330 | Here is a break down of your task into a list of more manageable subtasks - 331 | 332 | 1. Title of the task 333 | Detailed description of the task with a breakdown of the steps that need to be taken to complete the task 334 | 2. Title of the task 335 | Detailed description of the task with a breakdown of the steps that need to be taken to complete the task 336 | 3. Title of the task 337 | Detailed description of the task with a breakdown of the steps that need to be taken to complete the task 338 | """ 339 | openai_client = OpenAI() 340 | response = openai_client.chat.completions.create( 341 | model="gpt-3.5-turbo-1106", 342 | messages=[ 343 | { 344 | "role": "system", 345 | "content": "You are a senior staff engineer, who is responsible for breaking up large complex tasks into small, granular subtasks that more junior engineers can easily work through and execute on.", 346 | }, 347 | {"role": "user", "content": questionPrompt}, 348 | ], 349 | ) 350 | subtasks = response.choices[0].message.content 351 | return subtasks 352 | except Exception as e: 353 | print("Failed to generate subtasks with error " + str(e)) 354 | return "Failed to generate subtasks with error " + str(e) 355 | 356 | 357 | def generate_ticket_markdown(tickets: List[Ticket]): 358 | markdown = "" 359 | for ticket in tickets: 360 | markdown += f"- **{ticket.title}**: {ticket.description}\n" 361 | return markdown 362 | 363 | 364 | -------------------------------------------------------------------------------- /src/agents/intern/__init__.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | import time 3 | from threading import Thread 4 | from typing import List 5 | 6 | from src.lib.terminal import colorize 7 | from src.agents.intern.processors import better_code_change, generate_code_change 8 | from src.models import Ticket 9 | from src.helpers.github import GHHelper 10 | from src.helpers.board import BoardHelper 11 | 12 | REFRESH_EVERY = 5 13 | PROCESS_EVERY = 5 14 | MAX_REFRESH_CYCLES_WITHOUT_WORK = 50000 15 | MAX_PROCESS_CYCLES_WITHOUT_WORK = 10000 16 | 17 | 18 | class Intern: 19 | def __init__(self, name, gh_helper: GHHelper, board_helper: BoardHelper): 20 | self.name = name 21 | self.id = choice(board_helper.get_intern_list()) 22 | self.ticket_todo_list: List[Ticket] = [] 23 | self.pr_backlog = [] 24 | self.gh_helper = gh_helper 25 | self.board_helper = board_helper 26 | self.fetch_thread = Thread(target=self.refresh_loop) 27 | self.process_thread = Thread(target=self.process_loop) 28 | self.log_name = colorize(f"[{self.name} the intern]", bold=True, color="red") 29 | print( 30 | f"{self.log_name} Hey! I'm {self.name} the software dev intern 😁, excited to start working! I'll look for tickets to code!" 31 | ) 32 | 33 | def refresh_ticket_todo_list(self): 34 | # for ticket in self.trello_helper.get_backlog_tickets(): 35 | # print(f"Ticket ID: {ticket.id}, Title: {ticket.title}, Description: {ticket.description}, Assignee: {ticket.assignee_id}, Label: {ticket}") 36 | # next_tickets = [ 37 | # t 38 | # for t in self.trello_helper.get_backlog_tickets() 39 | # if t not in self.ticket_backlog and t.assignee_id == self.id 40 | # ] 41 | # print(f"[INTERN {self.name}] Looking on Trello for new assigned tickets") 42 | next_tickets = [ 43 | t 44 | for t in self.board_helper.get_tickets_todo_list() 45 | if t not in self.ticket_todo_list 46 | ] 47 | self.ticket_todo_list.extend(next_tickets) 48 | return len(next_tickets) != 0 49 | 50 | def refresh_pr_backlog(self): 51 | return False # Not implemented yet 52 | print(f"[INTERN {self.name}] Looking on GitHub for reviewed PRs") 53 | next_prs = [ 54 | pr 55 | for pr in self.gh_helper.list_open_prs() 56 | if pr not in self.pr_backlog and pr.assignee_id == self.id 57 | ] 58 | self.pr_backlog.extend(next_prs) 59 | return len(next_prs) != 0 60 | 61 | def process_pr(self): 62 | pr = self.pr_backlog.pop(0) 63 | self.board_helper.move_to_wip(pr.ticket_id) 64 | comment = self.gh_helper.get_comments(pr) 65 | # Do some processing with LLMs, create a new code_change 66 | code_change = generate_code_change("", comment) 67 | self.gh_helper.push_changes(code_change, pr.ticket_id, pr.assignee_id) 68 | print(f"[{self.log_name}] Moving card to waiting for review") 69 | self.board_helper.move_to_waiting_for_review(pr.ticket_id) 70 | 71 | def process_ticket(self): 72 | # Get the first ticket from the backlog 73 | # Process it (Trello + GH) 74 | ticket = self.ticket_todo_list.pop(0) 75 | 76 | print(f'{self.log_name} Starting to work on ticket "{ticket.title:.30}..."') 77 | 78 | # Move ticket to WIP 79 | self.board_helper.move_to_wip(ticket.id) 80 | 81 | # There should not be some PRs already assigned to this ticket (for now) 82 | # Call an agent to create a PR 83 | new_files, body = generate_code_change( 84 | ticket, self.gh_helper.get_entire_codebase() 85 | ) 86 | 87 | print(f"{self.log_name} Finished coding! Pushing changes to a PR...") 88 | # Push the changes to the PR 89 | branch_name = f"{ticket.id}_{ticket.title.lower().replace(' ', '_')}" 90 | self.gh_helper.push_changes( 91 | branch_name=branch_name, 92 | pr_title=ticket.title, 93 | pr_body=body, 94 | new_files=new_files, 95 | ticket_id=ticket.id, 96 | author_id=ticket.assignee_id, 97 | ) 98 | 99 | self.board_helper.move_to_waiting_for_review(ticket_id=ticket.id) 100 | print(f"{self.log_name} PR Created! Feel free to review it!") 101 | 102 | def refresh_loop(self): 103 | cycles_without_work = 0 104 | while True: 105 | if not self.refresh_pr_backlog() and not self.refresh_ticket_todo_list(): 106 | cycles_without_work += 1 107 | if cycles_without_work == MAX_REFRESH_CYCLES_WITHOUT_WORK: 108 | print(f"{self.log_name} No more work to do, bye bye!") 109 | break 110 | else: 111 | cycles_without_work = 0 112 | time.sleep(REFRESH_EVERY) 113 | self.process_thread.join() 114 | self.fetch_thread.join() 115 | 116 | def process_loop(self): 117 | number_of_attempts = 0 118 | while True: 119 | if len(self.pr_backlog) > 0: 120 | self.process_pr() 121 | number_of_attempts = 0 122 | elif len(self.ticket_todo_list) > 0: 123 | self.process_ticket() 124 | number_of_attempts = 0 125 | else: 126 | # print(f"[INTERN {self.name}] No tickets to process, idling...") 127 | number_of_attempts += 1 128 | if number_of_attempts == MAX_PROCESS_CYCLES_WITHOUT_WORK: 129 | print(f"{self.log_name} No more work to do, bye bye!") 130 | break 131 | time.sleep(10) 132 | 133 | self.fetch_thread.join() 134 | self.process_thread.join() 135 | 136 | def run(self): 137 | # Two threads are created running in an infinite loop 138 | # The first one listens to refresh commands and refreshes the backlogs 139 | # The second one consumes the backlogs and processes the tickets and PRs 140 | self.fetch_thread.start() 141 | self.process_thread.start() 142 | -------------------------------------------------------------------------------- /src/agents/intern/generators/diff_generator.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List 2 | import dspy 3 | import json 4 | 5 | from src.models import Codebase, Ticket 6 | 7 | 8 | class RelevantFileSelectionSignature(dspy.Signature): 9 | files_in_codebase = dspy.InputField() 10 | ticket = dspy.InputField() 11 | relevant_files: List[str] = dspy.OutputField( 12 | desc="Give the relevant files for you to observe to complete the ticket. They must be keys of the codebase dict." 13 | ) 14 | 15 | 16 | # Define the agent 17 | class DiffGeneratorSignature(dspy.Signature): 18 | relevant_codebase = dspy.InputField() 19 | ticket = dspy.InputField() 20 | git_diff = dspy.OutputField(desc="Give ONLY the git diff") 21 | explanations = dspy.OutputField(desc="Give explanations for the diff generated") 22 | 23 | 24 | class NewFilesGeneratorSignature(dspy.Signature): 25 | relevant_codebase = dspy.InputField() 26 | ticket = dspy.InputField() 27 | new_files: Dict[str, str] = dspy.OutputField( 28 | desc="Generate the entire files that need to be update or created complete the ticket, with all of their content post update. The key is the path of the file and the value is the content of the file." 29 | ) 30 | explanations = dspy.OutputField( 31 | desc="Give explanations for the new files generated. Use Markdown to format the text." 32 | ) 33 | 34 | 35 | class DiffGenerator(dspy.Module): 36 | def __init__(self): 37 | super().__init__() 38 | 39 | self.diff_generator = dspy.ChainOfThought(DiffGeneratorSignature) 40 | self.relevant_file_selector = dspy.TypedChainOfThought( 41 | RelevantFileSelectionSignature 42 | ) 43 | self.new_files_generator = dspy.TypedChainOfThought(NewFilesGeneratorSignature) 44 | 45 | def forward(self, codebase: Codebase, ticket: Ticket): 46 | relevant_files = self.relevant_file_selector( 47 | files_in_codebase=json.dumps(list(codebase.files.keys())), 48 | ticket=json.dumps(ticket.model_dump()), 49 | ) 50 | 51 | subset_codebase = { 52 | file: codebase.files[file] for file in relevant_files.relevant_files 53 | } 54 | 55 | relevant_codebase = Codebase(files=subset_codebase) 56 | 57 | new_files = self.new_files_generator( 58 | relevant_codebase=json.dumps(relevant_codebase.model_dump()), 59 | ticket=json.dumps(ticket.model_dump()), 60 | ) 61 | 62 | return new_files.new_files, new_files.explanations 63 | -------------------------------------------------------------------------------- /src/agents/intern/processors.py: -------------------------------------------------------------------------------- 1 | from src.agents.intern.generators.diff_generator import DiffGenerator 2 | from src.language_models import gpt4, mistral 3 | import dspy 4 | 5 | from src.models import Codebase, Ticket 6 | 7 | 8 | def better_code_change(previous_code_change, pr, comments): 9 | # This function will be called from Intern.process_pr 10 | # It will take the previous code_change, the pr and the comments 11 | # and will return a new code_change 12 | # The previous code_change will be the last code_change that was pushed to the PR 13 | # The pr will be the PR that is being processed 14 | # The comments will be the comments that were made on the PR since the last code_change 15 | # The function will return a new code_change that will be pushed to the PR 16 | return "new_code_change" 17 | 18 | 19 | def generate_code_change(ticket: Ticket, code_base: Codebase): 20 | # This function will be called from Intern.process_ticket 21 | # It will take the ticket and the code_base 22 | # and will return a new code_change 23 | dspy.configure(lm=gpt4) 24 | 25 | diff_generator = DiffGenerator() 26 | 27 | new_files, explanations = diff_generator(code_base, ticket) 28 | 29 | return new_files, explanations 30 | -------------------------------------------------------------------------------- /src/agents/reviewer/__init__.py: -------------------------------------------------------------------------------- 1 | import time 2 | from typing import List 3 | 4 | from src.lib.terminal import colorize 5 | from src.agents.reviewer.generators.code_review_generator import GeneratedCodeReview 6 | from src.agents.reviewer.processors import review_code 7 | from src.models import PR 8 | from src.helpers.board import BoardHelper 9 | from src.helpers.github import GHHelper 10 | 11 | 12 | class Reviewer: 13 | def __init__(self, name, gh_helper: GHHelper, board_helper: BoardHelper): 14 | self.name = name 15 | self.pr_backlog: List[PR] = [] 16 | self.gh_helper = gh_helper 17 | self.board_helper = board_helper 18 | self.log_name = colorize(f"[{self.name} the reviewer]", bold=True, color="cyan") 19 | print( 20 | f"{self.log_name} Hi, my name is {self.name} and I'm an experienced code reviewer. I'm ready to review some bad code 🧐." 21 | ) 22 | 23 | def refresh_pr_backlog(self): 24 | next_prs = [ 25 | pr for pr in self.gh_helper.list_open_prs() if pr not in self.pr_backlog 26 | ] 27 | self.pr_backlog.extend(next_prs) 28 | 29 | # def simplify_pr(self, raw_pr: PullRequest, ticket: Ticket) -> PR: 30 | # files_changed = raw_pr.get_files() 31 | 32 | # files_changed_with_diffs: List[ModifiedFile] = [] 33 | # for file in files_changed: 34 | # files_changed_with_diffs.append( 35 | # ModifiedFile( 36 | # filename=file.filename, 37 | # status=file.status, 38 | # additions=file.additions, 39 | # deletions=file.deletions, 40 | # changes=file.changes, 41 | # patch=file.patch, # This contains the diff for the file 42 | # ) 43 | # ) 44 | 45 | # pr: PR = PR( 46 | # id=raw_pr.number, 47 | # ticket_id=ticket.id, 48 | # assignee_id=ticket.assignee_id, 49 | # title=raw_pr.title, 50 | # description=raw_pr.body if raw_pr.body is not None else "", 51 | # files_changed=files_changed_with_diffs, 52 | # ) 53 | 54 | # return pr 55 | 56 | def submit_code_review(self, generated_code_review: GeneratedCodeReview): 57 | for comment in generated_code_review.code_review.comments: 58 | if not "position" in comment: 59 | comment["position"] = 0 60 | 61 | self.gh_helper.submit_code_review(generated_code_review.code_review) 62 | 63 | trello_ticket_id = generated_code_review.code_review.pr.ticket_id 64 | if ( 65 | generated_code_review.is_valid_code 66 | and generated_code_review.resolves_ticket 67 | ): 68 | self.board_helper.move_to_approved(ticket_id=trello_ticket_id) 69 | else: 70 | self.board_helper.move_to_reviewed(ticket_id=trello_ticket_id) 71 | 72 | def process_pr(self): 73 | codebase = self.gh_helper.get_entire_codebase() 74 | 75 | # Get first open PR from GH that hasn't been approved yet 76 | pr = self.pr_backlog.pop(0) 77 | 78 | # Fetch the Trello ticket that corresponds to this PR 79 | ticket = self.board_helper.get_ticket(ticket_id=pr.ticket_id) 80 | 81 | print( 82 | f'{self.log_name} I am reviewing the PR for this ticket: "{ticket.title:.30}..."' 83 | ) 84 | generated_code_review = review_code(codebase=codebase, ticket=ticket, pr=pr) 85 | self.submit_code_review(generated_code_review=generated_code_review) 86 | print( 87 | f"{self.log_name} Finished reviewing the PR! Check it out on Github: {pr.url}" 88 | ) 89 | 90 | def run(self): 91 | while True: 92 | self.refresh_pr_backlog() 93 | if len(self.pr_backlog) > 0: 94 | self.process_pr() 95 | time.sleep(10) 96 | -------------------------------------------------------------------------------- /src/agents/reviewer/generators/code_review_generator.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import dspy 3 | 4 | from src.models import Codebase, Ticket, PR, CodeReview 5 | 6 | 7 | class GeneratedCodeReview: 8 | is_valid_code: bool 9 | resolves_ticket: bool 10 | code_review: CodeReview 11 | 12 | 13 | class ReviewerSignature(dspy.Signature): 14 | # Inputs 15 | # codebase: Codebase = dspy.InputField() 16 | ticket: Ticket = dspy.InputField() 17 | pr: PR = dspy.InputField() 18 | # Outputs 19 | is_valid_code: bool = dspy.OutputField(desc="Check if the code is actually valid.") 20 | resolves_ticket: bool = dspy.OutputField( 21 | desc="Does this code actually resolve the ticket? Is it changing the right files?" 22 | ) 23 | code_review: CodeReview = dspy.OutputField( 24 | desc="If valid, provide a brief comment saying that it looks good. If not valid, provide comments for changes that are needed along with exact line numbers and/or start and end line number. If adding comments, make it different from the main body text." 25 | ) 26 | 27 | 28 | class ReviewerAgent(dspy.Module): 29 | def __init__(self): 30 | super().__init__() 31 | self.code_review_generator = dspy.TypedPredictor(signature=ReviewerSignature) 32 | 33 | def forward( 34 | self, codebase: Codebase, pr: PR, ticket: Ticket 35 | ) -> GeneratedCodeReview: 36 | # Get the review 37 | generated_review = self.code_review_generator( 38 | codebase=codebase, ticket=ticket, pr=pr 39 | ) 40 | 41 | return generated_review 42 | -------------------------------------------------------------------------------- /src/agents/reviewer/processors.py: -------------------------------------------------------------------------------- 1 | import dspy 2 | 3 | from src.agents.reviewer.generators.code_review_generator import ( 4 | GeneratedCodeReview, 5 | ReviewerAgent, 6 | ) 7 | 8 | from src.language_models import gpt4 9 | from src.models import Codebase, Ticket, PR 10 | 11 | 12 | def fix_code(codebase: Codebase, ticket: Ticket, pr: PR): 13 | # Note this function will most likely be implemented by the intern 14 | # This function is responsible for fixing the code 15 | # It should take the codebase, the ticket and the PR 16 | # It should update the codebase that is passed in and return that codebase 17 | updatedCodebase = codebase 18 | return updatedCodebase 19 | 20 | 21 | def review_code(codebase: Codebase, ticket: Ticket, pr: PR) -> GeneratedCodeReview: 22 | # This function is responsible for reviewing the code 23 | # It should take each of the PR comments, the associated code chunks 24 | # It should update comment on the PR and either approve or request changes 25 | dspy.configure(lm=gpt4) 26 | 27 | reviewer_agent = ReviewerAgent() 28 | 29 | code_review = reviewer_agent(codebase=codebase, ticket=ticket, pr=pr) 30 | 31 | return code_review 32 | -------------------------------------------------------------------------------- /src/constants.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class TicketStatus(Enum): 5 | BACKLOG = "Backlog" 6 | TODO = "To Do" 7 | WIP = "WIP" 8 | READY_FOR_REVIEW = "Ready for Review" 9 | REVIEWED = "Reviewed" 10 | APPROVED = "Approved" 11 | -------------------------------------------------------------------------------- /src/helpers/board.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from src.models import Ticket 3 | 4 | 5 | class BoardHelper: 6 | def __init__(self): 7 | raise NotImplementedError("This is an interface class") 8 | 9 | def get_ticket(self, ticket_id) -> Ticket: 10 | raise NotImplementedError("This is an interface class") 11 | 12 | def get_tickets_todo_list(self) -> List[Ticket]: 13 | raise NotImplementedError("This is an interface class") 14 | 15 | def get_waiting_for_review_tickets(self) -> List[Ticket]: 16 | raise NotImplementedError("This is an interface class") 17 | 18 | def move_to_waiting_for_review(self, ticket_id): 19 | raise NotImplementedError("This is an interface class") 20 | 21 | def move_to_reviewed(self, ticket_id): 22 | raise NotImplementedError("This is an interface class") 23 | 24 | def move_to_approved(self, ticket_id): 25 | pass 26 | 27 | def move_to_wip(self, ticket_id): 28 | raise NotImplementedError("This is an interface class") 29 | 30 | def move_to_backlog(self, ticket_id): 31 | raise NotImplementedError("This is an interface class") 32 | 33 | def push_tickets_to_backlog_and_assign(self, tickets: List[Ticket]) -> List[Ticket]: 34 | raise NotImplementedError("This is an interface class") 35 | 36 | def assign_ticket(self, ticket_id, assignee_id): 37 | raise NotImplementedError("This is an interface class") 38 | 39 | def get_intern_list(self): 40 | raise NotImplementedError("This is an interface class") 41 | 42 | def create_intern(self, name): 43 | raise NotImplementedError("This is an interface class") 44 | -------------------------------------------------------------------------------- /src/helpers/github.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from github import Auth, Github, InputGitTreeElement, InputGitAuthor 4 | 5 | from src.models import CodeReview, Codebase, ModifiedFile, Ticket, PR 6 | 7 | TICKET_DELIMITER = "Ticket: " 8 | AUTHOR_DELIMITER = "Author: " 9 | 10 | 11 | def add_ticket_info_to_pr_body(ticket_id, author_id, pr_body): 12 | return f"{TICKET_DELIMITER}{ticket_id}\n{AUTHOR_DELIMITER}{author_id}\n{pr_body}" 13 | 14 | 15 | def extract_ticket_info_from_pr_body(pr_body): 16 | ticket_id = None 17 | author_id = None 18 | lines = pr_body.split("\n") 19 | for line in lines: 20 | if line.startswith(TICKET_DELIMITER): 21 | ticket_id = line.replace(TICKET_DELIMITER, "") 22 | if line.startswith(AUTHOR_DELIMITER): 23 | author_id = line.replace(AUTHOR_DELIMITER, "") 24 | 25 | return ticket_id, author_id 26 | 27 | 28 | class GHHelper: 29 | def __init__(self, gh_api_token, gh_repo): 30 | auth = Auth.Token(gh_api_token) 31 | self.gh = Github(auth=auth) 32 | 33 | try: 34 | self.repo = self.gh.get_repo(gh_repo) 35 | print(f"Selected repo: {self.repo.name}") 36 | except Exception as e: 37 | print(f"Error: {e}") 38 | 39 | def list_open_prs(self) -> List[PR]: 40 | open_prs = [] 41 | for pr in self.repo.get_pulls(state="open"): 42 | # Check if PR is not approved or not changes requested 43 | if not any( 44 | review.state in ["APPROVED", "CHANGES_REQUESTED"] 45 | for review in pr.get_reviews() 46 | ): 47 | files_changed = pr.get_files() 48 | files_changed_with_diffs = [] 49 | for file in files_changed: 50 | files_changed_with_diffs.append( 51 | ModifiedFile( 52 | filename=file.filename, 53 | status=file.status, 54 | additions=file.additions, 55 | deletions=file.deletions, 56 | changes=file.changes, 57 | patch=file.patch, # This contains the diff for the file 58 | ) 59 | ) 60 | ticket_id, assignee_id = extract_ticket_info_from_pr_body(pr.body) 61 | open_prs.append( 62 | PR( 63 | id=pr.number, 64 | title=pr.title, 65 | description=pr.body, 66 | assignee_id=assignee_id, 67 | ticket_id=ticket_id, 68 | files_changed=files_changed_with_diffs, 69 | raw_pr=pr, 70 | url=pr.html_url, 71 | ) 72 | ) 73 | return open_prs 74 | 75 | def get_pr(self, pr_number): 76 | try: 77 | pr = self.repo.get_pull(pr_number) 78 | return pr 79 | except Exception as e: 80 | print(f"Error fetching PR #{pr_number}: {e}") 81 | return None 82 | 83 | def get_comments(self, pr): 84 | pr = self.repo.get_pull(pr) 85 | return pr.get_issue_comments() 86 | 87 | def add_comment(self, pr, comment): 88 | pr = self.repo.get_pull(pr) 89 | pr.create_issue_comment(comment) 90 | 91 | def mark_pr_as_approved(self, pr): 92 | pr = self.repo.get_pull(pr) 93 | pr.create_review(event="APPROVE") 94 | 95 | def submit_code_review(self, code_review: CodeReview): 96 | pr = self.repo.get_pull(number=code_review.pr.id) 97 | pr.create_review( 98 | event=code_review.event, 99 | body=code_review.body, 100 | comments=code_review.comments, 101 | ) 102 | 103 | def push_changes( 104 | self, branch_name, pr_title, pr_body, new_files, ticket_id, author_id 105 | ): 106 | # Parse the diff and create blobs for each modified file 107 | # Hoping that the diff is properly formatted 108 | 109 | modified_files = [] 110 | for file_path, file_content in new_files.items(): 111 | blob = self.repo.create_git_blob(file_content, "utf-8") 112 | modified_files.append( 113 | InputGitTreeElement( 114 | path=file_path, mode="100644", type="blob", sha=blob.sha 115 | ) 116 | ) 117 | 118 | # Get the current commit's tree 119 | base_tree = self.repo.get_git_tree(sha=self.repo.get_commits()[0].sha) 120 | 121 | # Create a new tree with the modified files 122 | new_tree = self.repo.create_git_tree(modified_files, base_tree) 123 | 124 | # Create a new branch 125 | ref = self.repo.create_git_ref( 126 | f"refs/heads/{branch_name}", self.repo.get_commits()[0].sha 127 | ) 128 | 129 | # Create a new commit with the new tree on the new branch 130 | author = InputGitAuthor("Open Architect", "openarchitect@gmail.com") 131 | 132 | commit_message = "Apply diff to multiple files" 133 | new_commit = self.repo.create_git_commit( 134 | commit_message, 135 | new_tree, 136 | [self.repo.get_git_commit(self.repo.get_commits()[0].sha)], 137 | author, 138 | ) 139 | 140 | # Update the branch reference to point to the new commit 141 | ref.edit(sha=new_commit.sha) 142 | 143 | # Create a new pull request 144 | base_branch = "main" # Replace with the target branch for the pull request 145 | head = f"{self.repo.owner.login}:{branch_name}" # Update the head parameter 146 | self.repo.create_pull( 147 | title=pr_title, 148 | body=add_ticket_info_to_pr_body(ticket_id, author_id, pr_body), 149 | head=head, 150 | base=base_branch, 151 | ) 152 | 153 | def get_entire_codebase(self) -> Codebase: 154 | contents = self.repo.get_contents("") 155 | if not isinstance(contents, list): 156 | contents = [contents] 157 | 158 | codebase_dict = {} 159 | for file in contents: 160 | try: 161 | codebase_dict[file.path] = file.decoded_content.decode("utf-8") 162 | except Exception as e: 163 | pass 164 | 165 | codebase = Codebase(files=codebase_dict) 166 | 167 | return codebase 168 | 169 | def get_file_content(self, file): 170 | contents = self.repo.get_contents(file) 171 | if isinstance(contents, list): 172 | contents = contents[0] 173 | 174 | return contents.decoded_content.decode("utf-8") 175 | -------------------------------------------------------------------------------- /src/helpers/trello.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import List 3 | from random import choice 4 | import requests 5 | 6 | from trello import TrelloClient 7 | 8 | from src.helpers.board import BoardHelper 9 | from src.constants import TicketStatus 10 | from src.models import Ticket 11 | 12 | HEADERS = { 13 | "Accept": "application/json", 14 | "Content-Type": "application/json", 15 | } 16 | 17 | COLORS = ["green", "yellow", "orange", "red", "purple", "blue", "sky", "lime", "pink", "black"] 18 | 19 | class CustomTrelloClient(TrelloClient): 20 | # Patch, because the base one is not working 21 | def __init__(self, api_key, token): 22 | self.api_key = api_key 23 | self.token = token 24 | 25 | def add_card(self, name, desc, list_id, label_id): 26 | url = f"https://api.trello.com/1/cards" 27 | query_params = { 28 | "key": self.api_key, 29 | "token": self.token, 30 | "name": name, 31 | "desc": desc, 32 | "idList": list_id, 33 | "idLabels": [label_id], 34 | } 35 | res = requests.post(url, headers=HEADERS, params=query_params) 36 | # print("Response from adding card to trello board: " + str(res.json())) 37 | 38 | def fetch_json( 39 | self, 40 | uri_path, 41 | http_method="GET", 42 | headers=None, 43 | query_params=None, 44 | post_args=None, 45 | files=None, 46 | ): 47 | if headers is None: 48 | headers = HEADERS 49 | if post_args is None: 50 | post_args = {} 51 | if query_params is None: 52 | query_params = {} 53 | if http_method in ("POST", "PUT", "DELETE") and not files: 54 | headers["Content-Type"] = "application/json; charset=utf-8" 55 | 56 | data = None 57 | if post_args: 58 | data = json.dumps(post_args) 59 | 60 | query_params["key"] = self.api_key 61 | query_params["token"] = self.token 62 | 63 | url = f"https://api.trello.com/1/{uri_path}" 64 | response = requests.request( 65 | http_method, url, headers=headers, params=query_params, data=data 66 | ) 67 | return response.json() 68 | 69 | 70 | class TrelloHelper(BoardHelper): 71 | def __init__(self, trello_api_key, trello_token, trello_board_id): 72 | self.client = CustomTrelloClient( 73 | api_key=trello_api_key, 74 | token=trello_token, 75 | ) 76 | 77 | board = self.client.get_board(trello_board_id) 78 | self.board_id = trello_board_id 79 | self.list_ids = {list.name: list.id for list in board.list_lists()} 80 | expected_values = [v.value for v in TicketStatus] 81 | for val in expected_values: 82 | if val not in self.list_ids: 83 | print( 84 | f"Error: List {val} not found. Make sure you have the correct list names {expected_values}." 85 | ) 86 | exit(1) 87 | 88 | def get_ticket(self, ticket_id) -> Ticket: 89 | card = self.client.get_card(ticket_id) 90 | return Ticket( 91 | id=card.id, 92 | title=card.name, 93 | description=card.description, 94 | assignee_id=card.labels[0].id if card.labels else None, 95 | ) 96 | 97 | def get_tickets_todo_list(self) -> List[Ticket]: 98 | cards = self.client.get_list( 99 | self.list_ids[TicketStatus.TODO.value] 100 | ).list_cards() 101 | if not cards: 102 | return [] 103 | 104 | return [ 105 | Ticket( 106 | id=card.id, 107 | title=card.name, 108 | description=card.description, 109 | assignee_id=card.labels[0].id if card.labels else "unassigned", 110 | ) 111 | for card in cards 112 | ] 113 | 114 | def get_waiting_for_review_tickets(self) -> List[Ticket]: 115 | cards = self.client.get_list( 116 | self.list_ids[TicketStatus.READY_FOR_REVIEW.value] 117 | ).list_cards() 118 | if not cards: 119 | return [] 120 | 121 | return [ 122 | Ticket( 123 | id=card.id, 124 | title=card.name, 125 | description=card.description, 126 | assignee_id=card.labels[0].id if card.labels else "unassigned", 127 | ) 128 | for card in cards 129 | ] 130 | 131 | def move_to_waiting_for_review(self, ticket_id): 132 | ticket = self.client.get_card(ticket_id) 133 | ticket.change_list(self.list_ids[TicketStatus.READY_FOR_REVIEW.value]) 134 | 135 | def move_to_reviewed(self, ticket_id): 136 | ticket = self.client.get_card(ticket_id) 137 | ticket.change_list(self.list_ids[TicketStatus.REVIEWED.value]) 138 | 139 | def move_to_approved(self, ticket_id): 140 | ticket = self.client.get_card(ticket_id) 141 | ticket.change_list(self.list_ids[TicketStatus.APPROVED.value]) 142 | 143 | def move_to_wip(self, ticket_id): 144 | ticket = self.client.get_card(ticket_id) 145 | ticket.change_list(self.list_ids[TicketStatus.WIP.value]) 146 | 147 | def push_tickets_to_backlog_and_assign(self, tickets: List[Ticket]) -> List[Ticket]: 148 | interns = self.get_intern_list() 149 | ticket_list = [] 150 | for ticket in tickets: 151 | assignee = choice(interns) 152 | print(f"Assigning {ticket.title} to {assignee}") 153 | ticket.assignee_id = assignee 154 | ticket.status = TicketStatus.BACKLOG 155 | print(f"Adding card to list {self.list_ids[TicketStatus.BACKLOG.value]}") 156 | # Create a card in the backlog 157 | self.client.add_card( 158 | ticket.title, 159 | ticket.description, 160 | self.list_ids[TicketStatus.BACKLOG.value], 161 | assignee, 162 | ) 163 | ticket_list.append(ticket) 164 | 165 | return ticket_list 166 | 167 | def get_intern_list(self): 168 | return [label.id for label in self.client.get_board(self.board_id).get_labels()] 169 | 170 | def create_intern(self, name): 171 | label = self.client.get_board(self.board_id).add_label(name, color=choice(COLORS)) 172 | return label.id 173 | 174 | # TESTING METHODS 175 | 176 | def move_to_todo(self, ticket_id): 177 | ticket = self.client.get_card(ticket_id) 178 | ticket.change_list(self.list_ids[TicketStatus.TODO.value]) 179 | 180 | def get_last_ticket(self): 181 | return self.client.get_list(self.list_ids[TicketStatus.BACKLOG.value]).list_cards()[-1] 182 | 183 | def delete_ticket(self, ticket_id): 184 | self.client.get_board(self.board_id).get_card(ticket_id).delete() 185 | 186 | def fire_intern(self, intern_id): 187 | self.client.get_board(self.board_id).delete_label(intern_id) 188 | -------------------------------------------------------------------------------- /src/language_models.py: -------------------------------------------------------------------------------- 1 | import dspy 2 | import json 3 | from src.lib.mistral_dspy import Mistral 4 | 5 | mistral_key = json.load(open("creds.json"))["mistral"] 6 | 7 | turbo = dspy.OpenAI(model="gpt-3.5-turbo-0125", max_tokens=4096) 8 | gpt4 = dspy.OpenAI(model="gpt-4-0125-preview", max_tokens=4096) 9 | mistral_7b = dspy.OllamaLocal(model="mistral") 10 | mistral = Mistral(model="mistral-large-latest", api_key=mistral_key, max_tokens=4096) 11 | -------------------------------------------------------------------------------- /src/lib/mistral_chat_completion.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import List, Optional, Union 3 | 4 | from pydantic import BaseModel 5 | 6 | class UsageInfo(BaseModel): 7 | prompt_tokens: int 8 | total_tokens: int 9 | completion_tokens: Optional[int] 10 | 11 | class Function(BaseModel): 12 | name: str 13 | description: str 14 | parameters: dict 15 | 16 | 17 | class ToolType(str, Enum): 18 | function = "function" 19 | 20 | 21 | class FunctionCall(BaseModel): 22 | name: str 23 | arguments: str 24 | 25 | 26 | class ToolCall(BaseModel): 27 | id: str = "null" 28 | type: ToolType = ToolType.function 29 | function: FunctionCall 30 | 31 | 32 | class ResponseFormats(str, Enum): 33 | text: str = "text" 34 | json_object: str = "json_object" 35 | 36 | 37 | class ToolChoice(str, Enum): 38 | auto: str = "auto" 39 | any: str = "any" 40 | none: str = "none" 41 | 42 | 43 | class ResponseFormat(BaseModel): 44 | type: ResponseFormats = ResponseFormats.text 45 | 46 | 47 | class ChatMessage(BaseModel): 48 | role: str 49 | content: Union[str, List[str]] 50 | name: Optional[str] = None 51 | tool_calls: Optional[List[ToolCall]] = None 52 | 53 | 54 | class FinishReason(str, Enum): 55 | stop = "stop" 56 | length = "length" 57 | error = "error" 58 | tool_calls = "tool_calls" 59 | 60 | 61 | class ChatCompletionResponseChoice(BaseModel): 62 | index: int 63 | message: ChatMessage 64 | finish_reason: Optional[FinishReason] 65 | 66 | 67 | class ChatCompletionResponse(BaseModel): 68 | id: str 69 | object: str 70 | created: int 71 | model: str 72 | choices: List[ChatCompletionResponseChoice] 73 | usage: UsageInfo 74 | -------------------------------------------------------------------------------- /src/lib/mistral_dspy.py: -------------------------------------------------------------------------------- 1 | from typing import Any, List, Optional, Union 2 | 3 | import backoff 4 | 5 | from dsp.modules.lm import LM 6 | from pydantic import BaseModel 7 | 8 | from src.lib.ported_exceptions import MistralAPIException 9 | from src.lib.ported_clients import MistralClient 10 | 11 | class ChatMessage(BaseModel): 12 | role: str 13 | content: Union[str, List[str]] 14 | 15 | def backoff_hdlr(details): 16 | """Handler from https://pypi.org/project/backoff/""" 17 | print( 18 | "Backing off {wait:0.1f} seconds after {tries} tries " 19 | "calling function {target} with kwargs " 20 | "{kwargs}".format(**details), 21 | ) 22 | 23 | 24 | def giveup_hdlr(details): 25 | """wrapper function that decides when to give up on retry""" 26 | if "rate limits" in details.message: 27 | return False 28 | return True 29 | 30 | 31 | class Mistral(LM): 32 | """Wrapper around Mistral AI's API. 33 | 34 | Currently supported models include `mistral-small-latest`, `mistral-medium-latest`, `mistral-large-latest`. 35 | """ 36 | 37 | def __init__( 38 | self, 39 | model: str = "mistral-medium-latest", 40 | api_key: Optional[str] = None, 41 | **kwargs, 42 | ): 43 | """ 44 | Parameters 45 | ---------- 46 | model : str 47 | Which pre-trained model from Mistral AI to use? 48 | Choices are [`mistral-small-latest`, `mistral-medium-latest`, `mistral-large-latest`] 49 | api_key : str 50 | The API key for Mistral AI. 51 | **kwargs: dict 52 | Additional arguments to pass to the API provider. 53 | """ 54 | super().__init__(model) 55 | 56 | self.client = MistralClient(api_key=api_key) 57 | 58 | self.provider = "mistral" 59 | self.kwargs = { 60 | "model": model, 61 | "temperature": 0.17, 62 | "max_tokens": 150, 63 | **kwargs, 64 | } 65 | 66 | self.history: list[dict[str, Any]] = [] 67 | 68 | def basic_request(self, prompt: str, **kwargs): 69 | """Basic request to Mistral AI's API.""" 70 | raw_kwargs = kwargs 71 | kwargs = { 72 | **self.kwargs, 73 | "messages": [ChatMessage(role="user", content=prompt)], 74 | **kwargs, 75 | } 76 | 77 | # Mistral disallows "n" arguments 78 | n = kwargs.pop("n", None) 79 | if n is not None and n > 1 and kwargs["temperature"] == 0.0: 80 | kwargs["temperature"] = 0.7 81 | 82 | response = self.client.chat(**kwargs) 83 | 84 | history = { 85 | "prompt": prompt, 86 | "response": response, 87 | "kwargs": kwargs, 88 | "raw_kwargs": raw_kwargs, 89 | } 90 | self.history.append(history) 91 | 92 | return response 93 | 94 | @backoff.on_exception( 95 | backoff.expo, 96 | MistralAPIException, 97 | max_time=1000, 98 | on_backoff=backoff_hdlr, 99 | giveup=giveup_hdlr, 100 | ) 101 | def request(self, prompt: str, **kwargs): 102 | """Handles retrieval of completions from Mistral AI whilst handling API errors.""" 103 | prompt = prompt + "Follow the format only once !" 104 | return self.basic_request(prompt, **kwargs) 105 | 106 | def __call__( 107 | self, 108 | prompt: str, 109 | only_completed: bool = True, 110 | return_sorted: bool = False, 111 | **kwargs, 112 | ): 113 | 114 | assert only_completed, "for now" 115 | assert return_sorted is False, "for now" 116 | 117 | n = kwargs.pop("n", 1) 118 | 119 | completions = [] 120 | for _ in range(n): 121 | response = self.request(prompt, **kwargs) 122 | completions.append(response.choices[0].message.content) 123 | 124 | return completions 125 | -------------------------------------------------------------------------------- /src/lib/ported_clients.py: -------------------------------------------------------------------------------- 1 | from json import JSONDecodeError 2 | import logging 3 | import os 4 | from abc import ABC 5 | import posixpath 6 | import time 7 | from typing import Any, Dict, Iterator, List, Optional, Union 8 | from httpx import Client, ConnectError, HTTPTransport, RequestError, Response 9 | 10 | import orjson 11 | 12 | from src.lib.ported_exceptions import ( 13 | MistralAPIException, 14 | MistralAPIStatusException, 15 | MistralConnectionException, 16 | MistralException, 17 | ) 18 | from src.lib.mistral_chat_completion import ChatCompletionResponse, ChatMessage, Function, ResponseFormat, ToolChoice 19 | 20 | logging.basicConfig( 21 | format="%(asctime)s %(levelname)s %(name)s: %(message)s", 22 | level=os.getenv("LOG_LEVEL", "ERROR"), 23 | ) 24 | 25 | RETRY_STATUS_CODES = {429, 500, 502, 503, 504} 26 | 27 | ENDPOINT = "https://api.mistral.ai" 28 | 29 | class ClientBase(ABC): 30 | def __init__( 31 | self, 32 | endpoint: str, 33 | api_key: Optional[str] = None, 34 | max_retries: int = 5, 35 | timeout: int = 120, 36 | ): 37 | self._max_retries = max_retries 38 | self._timeout = timeout 39 | 40 | self._endpoint = endpoint 41 | self._api_key = api_key 42 | self._logger = logging.getLogger(__name__) 43 | 44 | # For azure endpoints, we default to the mistral model 45 | if "inference.azure.com" in self._endpoint: 46 | self._default_model = "mistral" 47 | 48 | # This should be automatically updated by the deploy script 49 | self._version = "0.1.8" 50 | 51 | def _parse_tools(self, tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]: 52 | parsed_tools: List[Dict[str, Any]] = [] 53 | for tool in tools: 54 | if tool["type"] == "function": 55 | parsed_function = {} 56 | parsed_function["type"] = tool["type"] 57 | if isinstance(tool["function"], Function): 58 | parsed_function["function"] = tool["function"].model_dump(exclude_none=True) 59 | else: 60 | parsed_function["function"] = tool["function"] 61 | 62 | parsed_tools.append(parsed_function) 63 | 64 | return parsed_tools 65 | 66 | def _parse_tool_choice(self, tool_choice: Union[str, ToolChoice]) -> str: 67 | if isinstance(tool_choice, ToolChoice): 68 | return tool_choice.value 69 | return tool_choice 70 | 71 | def _parse_response_format(self, response_format: Union[Dict[str, Any], ResponseFormat]) -> Dict[str, Any]: 72 | if isinstance(response_format, ResponseFormat): 73 | return response_format.model_dump(exclude_none=True) 74 | return response_format 75 | 76 | def _parse_messages(self, messages: List[Any]) -> List[Dict[str, Any]]: 77 | parsed_messages: List[Dict[str, Any]] = [] 78 | for message in messages: 79 | if isinstance(message, ChatMessage): 80 | parsed_messages.append(message.model_dump(exclude_none=True)) 81 | else: 82 | parsed_messages.append(message) 83 | 84 | return parsed_messages 85 | 86 | def _make_chat_request( 87 | self, 88 | messages: List[Any], 89 | model: Optional[str] = None, 90 | tools: Optional[List[Dict[str, Any]]] = None, 91 | temperature: Optional[float] = None, 92 | max_tokens: Optional[int] = None, 93 | top_p: Optional[float] = None, 94 | random_seed: Optional[int] = None, 95 | stream: Optional[bool] = None, 96 | safe_prompt: Optional[bool] = False, 97 | tool_choice: Optional[Union[str, ToolChoice]] = None, 98 | response_format: Optional[Union[Dict[str, str], ResponseFormat]] = None, 99 | ) -> Dict[str, Any]: 100 | request_data: Dict[str, Any] = { 101 | "messages": self._parse_messages(messages), 102 | "safe_prompt": safe_prompt, 103 | } 104 | 105 | if model is not None: 106 | request_data["model"] = model 107 | else: 108 | if self._default_model is None: 109 | raise MistralException(message="model must be provided") 110 | request_data["model"] = self._default_model 111 | 112 | if tools is not None: 113 | request_data["tools"] = self._parse_tools(tools) 114 | if temperature is not None: 115 | request_data["temperature"] = temperature 116 | if max_tokens is not None: 117 | request_data["max_tokens"] = max_tokens 118 | if top_p is not None: 119 | request_data["top_p"] = top_p 120 | if random_seed is not None: 121 | request_data["random_seed"] = random_seed 122 | if stream is not None: 123 | request_data["stream"] = stream 124 | 125 | if tool_choice is not None: 126 | request_data["tool_choice"] = self._parse_tool_choice(tool_choice) 127 | if response_format is not None: 128 | request_data["response_format"] = self._parse_response_format(response_format) 129 | 130 | self._logger.debug(f"Chat request: {request_data}") 131 | 132 | return request_data 133 | 134 | def _process_line(self, line: str) -> Optional[Dict[str, Any]]: 135 | if line.startswith("data: "): 136 | line = line[6:].strip() 137 | if line != "[DONE]": 138 | json_streamed_response: Dict[str, Any] = orjson.loads(line) 139 | return json_streamed_response 140 | return None 141 | 142 | 143 | class MistralClient(ClientBase): 144 | """ 145 | Synchronous wrapper around the async client 146 | """ 147 | 148 | def __init__( 149 | self, 150 | api_key: Optional[str] = os.environ.get("MISTRAL_API_KEY", None), 151 | endpoint: str = ENDPOINT, 152 | max_retries: int = 5, 153 | timeout: int = 120, 154 | ): 155 | super().__init__(endpoint, api_key, max_retries, timeout) 156 | 157 | self._client = Client( 158 | follow_redirects=True, timeout=self._timeout, transport=HTTPTransport(retries=self._max_retries) 159 | ) 160 | 161 | def __del__(self) -> None: 162 | self._client.close() 163 | 164 | def _check_response_status_codes(self, response: Response) -> None: 165 | if response.status_code in RETRY_STATUS_CODES: 166 | raise MistralAPIStatusException.from_response( 167 | response, 168 | message=f"Status: {response.status_code}. Message: {response.text}", 169 | ) 170 | elif 400 <= response.status_code < 500: 171 | if response.stream: 172 | response.read() 173 | raise MistralAPIException.from_response( 174 | response, 175 | message=f"Status: {response.status_code}. Message: {response.text}", 176 | ) 177 | elif response.status_code >= 500: 178 | if response.stream: 179 | response.read() 180 | raise MistralException( 181 | message=f"Status: {response.status_code}. Message: {response.text}", 182 | ) 183 | 184 | def _check_streaming_response(self, response: Response) -> None: 185 | self._check_response_status_codes(response) 186 | 187 | def _check_response(self, response: Response) -> Dict[str, Any]: 188 | self._check_response_status_codes(response) 189 | 190 | json_response: Dict[str, Any] = response.json() 191 | 192 | if "object" not in json_response: 193 | raise MistralException(message=f"Unexpected response: {json_response}") 194 | if "error" == json_response["object"]: # has errors 195 | raise MistralAPIException.from_response( 196 | response, 197 | message=json_response["message"], 198 | ) 199 | 200 | return json_response 201 | 202 | def _request( 203 | self, 204 | method: str, 205 | json: Dict[str, Any], 206 | path: str, 207 | attempt: int = 1, 208 | ) -> Iterator[Dict[str, Any]]: 209 | accept_header = "application/json" 210 | headers = { 211 | "Accept": accept_header, 212 | "User-Agent": f"mistral-client-python/{self._version}", 213 | "Authorization": f"Bearer {self._api_key}", 214 | "Content-Type": "application/json", 215 | } 216 | 217 | url = posixpath.join(self._endpoint, path) 218 | 219 | self._logger.debug(f"Sending request: {method} {url} {json}") 220 | 221 | new_json = json.copy() 222 | new_json['messages'] = [] 223 | 224 | for message in json['messages']: 225 | new_json["messages"].append(message.model_dump(exclude_none=True)) 226 | 227 | response: Response 228 | 229 | try: 230 | response = self._client.request( 231 | method, 232 | url, 233 | headers=headers, 234 | json=new_json, 235 | ) 236 | 237 | yield self._check_response(response) 238 | 239 | except ConnectError as e: 240 | raise MistralConnectionException(str(e)) from e 241 | except RequestError as e: 242 | raise MistralException(f"Unexpected exception ({e.__class__.__name__}): {e}") from e 243 | except JSONDecodeError as e: 244 | raise MistralAPIException.from_response( 245 | response, 246 | message=f"Failed to decode json body: {response.text}", 247 | ) from e 248 | except MistralAPIStatusException as e: 249 | attempt += 1 250 | if attempt > self._max_retries: 251 | raise MistralAPIStatusException.from_response(response, message=str(e)) from e 252 | backoff = 2.0**attempt # exponential backoff 253 | time.sleep(backoff) 254 | 255 | # Retry as a generator 256 | for r in self._request(method, json, path, attempt=attempt): 257 | yield r 258 | 259 | def chat( 260 | self, 261 | messages: List[Any], 262 | model: Optional[str] = None, 263 | tools: Optional[List[Dict[str, Any]]] = None, 264 | temperature: Optional[float] = None, 265 | max_tokens: Optional[int] = None, 266 | top_p: Optional[float] = None, 267 | random_seed: Optional[int] = None, 268 | safe_mode: bool = False, 269 | safe_prompt: bool = False, 270 | tool_choice: Optional[Union[str, ToolChoice]] = None, 271 | response_format: Optional[Union[Dict[str, str], ResponseFormat]] = None, 272 | ) -> ChatCompletionResponse: 273 | """A chat endpoint that returns a single response. 274 | 275 | Args: 276 | model (str): model the name of the model to chat with, e.g. mistral-tiny 277 | messages (List[Any]): messages an array of messages to chat with, e.g. 278 | [{role: 'user', content: 'What is the best French cheese?'}] 279 | tools (Optional[List[Function]], optional): a list of tools to use. 280 | temperature (Optional[float], optional): temperature the temperature to use for sampling, e.g. 0.5. 281 | max_tokens (Optional[int], optional): the maximum number of tokens to generate, e.g. 100. Defaults to None. 282 | top_p (Optional[float], optional): the cumulative probability of tokens to generate, e.g. 0.9. 283 | Defaults to None. 284 | random_seed (Optional[int], optional): the random seed to use for sampling, e.g. 42. Defaults to None. 285 | safe_mode (bool, optional): deprecated, use safe_prompt instead. Defaults to False. 286 | safe_prompt (bool, optional): whether to use safe prompt, e.g. true. Defaults to False. 287 | 288 | Returns: 289 | ChatCompletionResponse: a response object containing the generated text. 290 | """ 291 | request = self._make_chat_request( 292 | messages, 293 | model, 294 | tools=tools, 295 | temperature=temperature, 296 | max_tokens=max_tokens, 297 | top_p=top_p, 298 | random_seed=random_seed, 299 | stream=False, 300 | safe_prompt=safe_mode or safe_prompt, 301 | tool_choice=tool_choice, 302 | response_format=response_format, 303 | ) 304 | 305 | single_response = self._request("post", request, "v1/chat/completions") 306 | 307 | for response in single_response: 308 | return ChatCompletionResponse(**response) 309 | 310 | raise MistralException("No response received") -------------------------------------------------------------------------------- /src/lib/ported_exceptions.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from typing import Any, Dict, Optional 4 | 5 | from httpx import Response 6 | 7 | 8 | class MistralException(Exception): 9 | """Base Exception class, returned when nothing more specific applies""" 10 | 11 | def __init__(self, message: Optional[str] = None) -> None: 12 | super(MistralException, self).__init__(message) 13 | 14 | self.message = message 15 | 16 | def __str__(self) -> str: 17 | msg = self.message or "" 18 | return msg 19 | 20 | def __repr__(self) -> str: 21 | return f"{self.__class__.__name__}(message={str(self)})" 22 | 23 | 24 | class MistralAPIException(MistralException): 25 | """Returned when the API responds with an error message""" 26 | 27 | def __init__( 28 | self, 29 | message: Optional[str] = None, 30 | http_status: Optional[int] = None, 31 | headers: Optional[Dict[str, Any]] = None, 32 | ) -> None: 33 | super().__init__(message) 34 | self.http_status = http_status 35 | self.headers = headers or {} 36 | 37 | @classmethod 38 | def from_response( 39 | cls, response: Response, message: Optional[str] = None 40 | ) -> MistralAPIException: 41 | return cls( 42 | message=message or response.text, 43 | http_status=response.status_code, 44 | headers=dict(response.headers), 45 | ) 46 | 47 | def __repr__(self) -> str: 48 | return f"{self.__class__.__name__}(message={str(self)}, http_status={self.http_status})" 49 | 50 | class MistralAPIStatusException(MistralAPIException): 51 | """Returned when we receive a non-200 response from the API that we should retry""" 52 | 53 | class MistralConnectionException(MistralException): 54 | """Returned when the SDK can not reach the API server for any reason""" 55 | -------------------------------------------------------------------------------- /src/lib/terminal.py: -------------------------------------------------------------------------------- 1 | def colorize(text, color, bold=False): 2 | colors = { 3 | "red": "\033[91m", 4 | "green": "\033[92m", 5 | "yellow": "\033[93m", 6 | "blue": "\033[94m", 7 | "magenta": "\033[95m", 8 | "cyan": "\033[96m", 9 | "white": "\033[97m", 10 | "reset": "\033[0m", 11 | } 12 | 13 | bold_code = "\033[1m" if bold else "" 14 | color_code = colors.get(color.lower(), "") 15 | 16 | return f"{bold_code}{color_code}{text}{colors['reset']}" 17 | 18 | 19 | # # Example usage 20 | # print(colorize("Hello, World!", "red", bold=True)) 21 | # print(colorize("This is a green text.", "green")) 22 | # print(colorize("This is a bold blue text.", "blue", bold=True)) 23 | -------------------------------------------------------------------------------- /src/models.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List, Literal, Optional 2 | from pydantic import BaseModel 3 | 4 | from github.PullRequest import ReviewComment 5 | 6 | ticket_stages = ["backlog", "todo", "wip", "review", "done"] 7 | 8 | 9 | class Ticket(BaseModel): 10 | id: Optional[str] = None 11 | title: str 12 | description: str 13 | status: Optional[str] = None 14 | assignee_id: Optional[str] = None 15 | 16 | 17 | class ModifiedFile(BaseModel): 18 | filename: str 19 | status: str 20 | additions: int 21 | deletions: int 22 | changes: int 23 | patch: str 24 | 25 | 26 | # Todo: Use github.PullRequest class instead of this 27 | class PR(BaseModel): 28 | id: int 29 | ticket_id: Optional[str] = None 30 | assignee_id: Optional[str] = None 31 | title: str 32 | description: str 33 | files_changed: List[ModifiedFile] = [] 34 | url: Optional[str] = None 35 | 36 | 37 | class CodeReview(BaseModel): 38 | pr: PR 39 | body: str 40 | event: Literal["APPROVE", "REQUEST_CHANGES", "COMMENT"] 41 | comments: List[ReviewComment] = [] 42 | 43 | 44 | class Codebase(BaseModel): 45 | files: Dict[str, str] 46 | -------------------------------------------------------------------------------- /start_architecting.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | 4 | from src.helpers.github import GHHelper 5 | from src.helpers.trello import TrelloHelper 6 | 7 | from src.agents.architect import Architect 8 | 9 | load_dotenv() 10 | 11 | gh_repo = os.getenv("GITHUB_REPO_URL") 12 | gh_api_token_reviewer = os.getenv("GITHUB_TOKEN_REVIEWER") 13 | openai_api_key = os.getenv("OPENAI_API_KEY") 14 | trello_api_key = os.getenv("TRELLO_API_KEY") 15 | trello_api_secret = os.getenv("TRELLO_API_SECRET") 16 | trello_token = os.getenv("TRELLO_TOKEN") 17 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 18 | 19 | if ( 20 | gh_repo is None 21 | or gh_api_token_reviewer is None 22 | or openai_api_key is None 23 | or trello_api_key is None 24 | or trello_api_secret is None 25 | or trello_token is None 26 | or trello_board_id is None 27 | ): 28 | print( 29 | "Please run the init_connections.py script to set up the environment variables" 30 | ) 31 | 32 | gh_helper = GHHelper(gh_api_token_reviewer, gh_repo) 33 | trello_helper = TrelloHelper(trello_api_key, trello_token, trello_board_id) 34 | 35 | architect = Architect( 36 | "Sophia", 37 | gh_helper=gh_helper, 38 | board_helper=trello_helper, 39 | ) 40 | 41 | architect.run() -------------------------------------------------------------------------------- /start_coding.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | from threading import Thread 3 | import os 4 | 5 | from src.helpers.github import GHHelper 6 | from src.helpers.trello import TrelloHelper 7 | 8 | from src.agents.intern import Intern 9 | from src.agents.reviewer import Reviewer 10 | 11 | load_dotenv() 12 | 13 | gh_repo = os.getenv("GITHUB_REPO_URL") 14 | gh_api_token_intern = os.getenv("GITHUB_TOKEN_INTERN") 15 | gh_api_token_reviewer = os.getenv("GITHUB_TOKEN_REVIEWER") 16 | trello_api_key = os.getenv("TRELLO_API_KEY") 17 | trello_api_secret = os.getenv("TRELLO_API_SECRET") 18 | trello_token = os.getenv("TRELLO_TOKEN") 19 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 20 | 21 | if ( 22 | gh_repo is None 23 | or gh_api_token_intern is None 24 | or gh_api_token_reviewer is None 25 | or trello_api_key is None 26 | or trello_api_secret is None 27 | or trello_token is None 28 | or trello_board_id is None 29 | ): 30 | print( 31 | "Please run the init_connections.py script to set up the environment variables" 32 | ) 33 | 34 | gh_helper_intern = GHHelper(gh_api_token_intern, gh_repo) 35 | gh_helper_reviewer = GHHelper(gh_api_token_reviewer, gh_repo) 36 | trello_helper = TrelloHelper(trello_api_key, trello_token, trello_board_id) 37 | 38 | intern = Intern("alex", gh_helper=gh_helper_intern, board_helper=trello_helper) 39 | reviewer = Reviewer( 40 | "charlie", 41 | gh_helper=gh_helper_reviewer, 42 | board_helper=trello_helper, 43 | ) 44 | 45 | intern_thread = Thread(target=intern.run) 46 | reviewer_thread = Thread(target=reviewer.run) 47 | 48 | # Step 1: With User input (streamit), define tickets, push to Trello's Backlog 49 | 50 | while True: 51 | # Step 2: Let's get to work (n + 1 threads) 52 | intern_thread.start() 53 | reviewer_thread.start() 54 | -------------------------------------------------------------------------------- /test_gh_helper.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | 4 | from gh_helper import GHHelper 5 | 6 | load_dotenv() 7 | 8 | gh_repo = os.getenv("GITHUB_REPO_URL") 9 | gh_api_token = os.getenv("GITHUB_TOKEN") 10 | if gh_repo is None or gh_api_token is None: 11 | print("Please run the start.py script to set up the environment variables") 12 | 13 | gh = GHHelper(gh_api_token, gh_repo) 14 | 15 | gh.list_open_prs() 16 | 17 | print(gh.get_entire_codebase()) 18 | -------------------------------------------------------------------------------- /test_trello_helper.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | 4 | from src.models import Ticket 5 | from src.helpers.trello import TrelloHelper 6 | 7 | load_dotenv() 8 | 9 | trello_api_key = os.getenv("TRELLO_API_KEY") 10 | trello_token = os.getenv("TRELLO_TOKEN") 11 | trello_board_id = os.getenv("TRELLO_BOARD_ID") 12 | 13 | if trello_api_key is None or trello_token is None or trello_board_id is None: 14 | print("Please run the start.py script to set up the environment variables") 15 | 16 | trello_helper = TrelloHelper(trello_api_key, trello_token, trello_board_id) 17 | 18 | ## Step 0: Create an intern 19 | new_intern = trello_helper.create_intern("Test Intern") 20 | 21 | ## Step 1: Get the available "candidates" (interns) from Trello 22 | interns = trello_helper.get_intern_list() 23 | print("ok" if interns[-1] else "not ok") 24 | 25 | ## Step 2: Create a ticket and assign it to an intern 26 | new_ticket = Ticket( 27 | title="Test Ticket", 28 | description="This is a test ticket", 29 | assignee_id=new_intern, 30 | ) 31 | created_ticket = trello_helper.push_tickets_to_backlog_and_assign([new_ticket])[-1] 32 | print("ok" if created_ticket.title == new_ticket.title else "not ok") 33 | trello_helper.move_to_todo(trello_helper.get_last_ticket().id) 34 | 35 | ## Step 3: Get the tickets from the To Do list 36 | tickets = trello_helper.get_tickets_todo_list() 37 | print("ok" if tickets[-1] else "not ok") 38 | 39 | ## Step 4: Cleanup 40 | trello_helper.delete_ticket(tickets[-1].id) 41 | trello_helper.fire_intern(new_intern) 42 | print("Done!") 43 | --------------------------------------------------------------------------------