├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE ├── README.md ├── create_har.py ├── integuru ├── __init__.py ├── __main__.py ├── agent.py ├── graph_builder.py ├── main.py ├── models │ ├── DAGManager.py │ ├── agent_state.py │ └── request.py └── util │ ├── LLM.py │ ├── har_processing.py │ └── print.py ├── integuru_demo.gif ├── main.ipynb ├── poetry.lock ├── pyproject.toml └── tests └── test_integration_agent.py /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | test: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | 19 | - name: Set up Python 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.12 23 | 24 | - name: Install dependencies 25 | run: | 26 | curl -sSL https://install.python-poetry.org | python3 - 27 | poetry install 28 | 29 | - name: Run tests 30 | run: poetry run pytest 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | .DS_Store 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # poetry 99 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 100 | # This is especially recommended for binary packages to ensure reproducibility, and is more 101 | # commonly ignored for libraries. 102 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 103 | #poetry.lock 104 | 105 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 106 | __pypackages__/ 107 | 108 | # Celery stuff 109 | celerybeat-schedule 110 | celerybeat.pid 111 | 112 | # SageMath parsed files 113 | *.sage.py 114 | 115 | # Environments 116 | .env 117 | .venv 118 | env/ 119 | venv/ 120 | ENV/ 121 | env.bak/ 122 | venv.bak/ 123 | 124 | # Spyder project settings 125 | .spyderproject 126 | .spyproject 127 | 128 | # Rope project settings 129 | .ropeproject 130 | 131 | # mkdocs documentation 132 | /site 133 | 134 | # mypy 135 | .mypy_cache/ 136 | .dmypy.json 137 | dmypy.json 138 | 139 | # Pyre type checker 140 | .pyre/ 141 | 142 | # pytype static type analyzer 143 | .pytype/ 144 | 145 | # Cython debug symbols 146 | cython_debug/ 147 | 148 | # PyCharm 149 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 150 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 151 | # and can be added to the global gitignore or merged into this file. For a more nuclear 152 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 153 | #.idea/ 154 | 155 | *.har 156 | *.json 157 | *.png 158 | # Temporary files 159 | temp* 160 | 161 | generated_code.txt 162 | generated_code.py 163 | 164 | saved_files/ 165 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Integuru 2 | 3 | An AI agent that generates integration code by reverse-engineering platforms' internal APIs. 4 | 5 | ## Integuru in Action 6 | 7 | ![Integuru in action](./integuru_demo.gif) 8 | 9 | ## What Integuru Does 10 | 11 | You use ```create_har.py``` to generate a file containing all browser network requests, a file with the cookies, and write a prompt describing the action triggered in the browser. The agent outputs runnable Python code that hits the platform's internal endpoints to perform the desired action. 12 | 13 | ## How It Works 14 | 15 | Let's assume we want to download utility bills: 16 | 17 | 1. The agent identifies the request that downloads the utility bills. 18 | For example, the request URL might look like this: 19 | ``` 20 | https://www.example.com/utility-bills?accountId=123&userId=456 21 | ``` 22 | 2. It identifies parts of the request that depend on other requests. 23 | The above URL contains dynamic parts (accountId and userId) that need to be obtained from other requests. 24 | ``` 25 | accountId=123 userId=456 26 | ``` 27 | 3. It finds the requests that provide these parts and makes the download request dependent on them. It also attaches these requests to the original request to build out a dependency graph. 28 | ``` 29 | GET https://www.example.com/get_account_id 30 | GET https://www.example.com/get_user_id 31 | ``` 32 | 4. This process repeats until the request being checked depends on no other request and only requires the authentication cookies. 33 | 5. The agent traverses up the graph, starting from nodes (requests) with no outgoing edges until it reaches the master node while converting each node to a runnable function. 34 | 35 | ## Features 36 | 37 | - Generate a dependency graph of requests to make the final request that performs the desired action. 38 | - Allow input variables (for example, choosing the YEAR to download a document from). This is currently only supported for graph generation. Input variables for code generation coming soon! 39 | - Generate code to hit all requests in the graph to perform the desired action. 40 | 41 | ## Setup 42 | 43 | 1. Set up your OpenAI [API Keys](https://platform.openai.com/account/api-keys) and add the `OPENAI_API_KEY` environment variable. (We recommend using an account with access to models that are at least as capable as OpenAI o1-mini. Models on par with OpenAI o1-preview are ideal.) 44 | 2. Install Python requirements via poetry: 45 | ``` 46 | poetry install 47 | ``` 48 | 3. Open a poetry shell: 49 | ``` 50 | poetry shell 51 | ``` 52 | 4. Register the Poetry virtual environment with Jupyter: 53 | ``` 54 | poetry run ipython kernel install --user --name=integuru 55 | ``` 56 | 5. Run the following command to spawn a browser: 57 | ``` 58 | poetry run python create_har.py 59 | ``` 60 | Log into your platform and perform the desired action (such as downloading a utility bill). 61 | 6. Run Integuru: 62 | ``` 63 | poetry run integuru --prompt "download utility bills" --model 64 | ``` 65 | You can also run it via Jupyter Notebook `main.ipynb` 66 | 67 | **Recommended to use gpt-4o as the model for graph generation as it supports function calling. Integuru will automatically switch to o1-preview for code generation if available in the user's OpenAI account.** 68 | 69 | ## Usage 70 | 71 | After setting up the project, you can use Integuru to analyze and reverse-engineer API requests for external platforms. Simply provide the appropriate .har file and a prompt describing the action that you want to trigger. 72 | 73 | ``` 74 | poetry run integuru --help 75 | Usage: integuru [OPTIONS] 76 | 77 | Options: 78 | --model TEXT The LLM model to use (default is gpt-4o) 79 | --prompt TEXT The prompt for the model [required] 80 | --har-path TEXT The HAR file path (default is 81 | ./network_requests.har) 82 | --cookie-path TEXT The cookie file path (default is 83 | ./cookies.json) 84 | --max_steps INTEGER The max_steps (default is 20) 85 | --input_variables ... 86 | Input variables in the format key value 87 | --generate-code Whether to generate the full integration 88 | code 89 | --help Show this message and exit. 90 | ``` 91 | 92 | 93 | ## Running Unit Tests 94 | 95 | To run unit tests using `pytest`, use the following command: 96 | 97 | ``` 98 | poetry run pytest 99 | ``` 100 | 101 | ## Continuous Integration (CI) Workflow 102 | 103 | This repository includes a CI workflow using GitHub Actions. The workflow is defined in the `.github/workflows/ci.yml` file and is triggered on each push and pull request to the `main` branch. The workflow performs the following steps: 104 | 105 | 1. Checks out the code. 106 | 2. Sets up Python 3.12. 107 | 3. Installs dependencies using `poetry`. 108 | 4. Runs tests using `pytest`. 109 | 110 | ## Note on 2FA 111 | 112 | When the destination site uses two-factor authentication (2FA), the workflow remains the same. Ensure that you complete the 2FA process and obtain the cookies/auth tokens/session tokens after 2FA. These tokens will be used in the workflow. 113 | 114 | 115 | ## Demo 116 | 117 | [![Demo Video](http://markdown-videos-api.jorgenkh.no/youtube/7OJ4w5BCpQ0)](https://www.youtube.com/watch?v=7OJ4w5BCpQ0) 118 | 119 | ## Contributing 120 | 121 | Contributions to improve Integuru are welcome. Please feel free to submit issues or pull requests on the project's repository. 122 | 123 | ## Info 124 | 125 | Integuru is built by Integuru.ai. Besides our work on the agent, we take custom requests for new integrations or additional features for existing supported platforms. We also offer hosting and authentication services. If you have requests or want to work with us, reach out at richard@integuru.ai. 126 | 127 | We open-source unofficial APIs that we've built already. You can find them [here](https://github.com/Integuru-AI/APIs-by-Integuru). 128 | 129 | ## Privacy Policy 130 | 131 | ### Data Storage 132 | Collected data is stored locally in the `network_requests.har` and `cookies.json` files. 133 | 134 | ### LLM Usage 135 | The tool uses a cloud-based LLM (OpenAI's GPT-4o and o1-preview models). 136 | 137 | ### LLM Training 138 | The LLM is not trained or improved by the usage of this tool. 139 | -------------------------------------------------------------------------------- /create_har.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from playwright.async_api import async_playwright 4 | 5 | 6 | async def open_browser_and_wait(): 7 | async with async_playwright() as p: 8 | browser = await p.chromium.launch(headless=False) 9 | 10 | context = await browser.new_context( 11 | record_har_path="network_requests.har", # Path to save the HAR file 12 | record_har_content="embed", # Omit content to make the HAR file smaller 13 | # TODO record_har_url_filter="*", # Optional URL filter 14 | ) 15 | 16 | page = await context.new_page() 17 | 18 | print( 19 | "Browser is open. Press Enter in the terminal when you're ready to close the browser and save cookies..." 20 | ) 21 | 22 | input("Press Enter to continue and close the browser...") 23 | 24 | # Ensure 2FA is completed before saving cookies 25 | cookies = await context.cookies() 26 | 27 | with open("cookies.json", "w") as f: 28 | json.dump(cookies, f, indent=4) 29 | 30 | await context.close() 31 | 32 | await browser.close() 33 | 34 | asyncio.run(open_browser_and_wait()) 35 | -------------------------------------------------------------------------------- /integuru/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Integuru-AI/Integuru/a31446f9453cab892f48005cf5e0b0674699f9b5/integuru/__init__.py -------------------------------------------------------------------------------- /integuru/__main__.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import time # Add this import 3 | 4 | load_dotenv() 5 | 6 | from integuru.main import call_agent 7 | import asyncio 8 | import click 9 | 10 | @click.command() 11 | @click.option( 12 | "--model", default="gpt-4o", help="The LLM model to use (default is gpt-4o)" 13 | ) 14 | @click.option("--prompt", required=True, help="The prompt for the model") 15 | @click.option( 16 | "--har-path", 17 | default="./network_requests.har", 18 | help="The HAR file path (default is ./network_requests.har)", 19 | ) 20 | @click.option( 21 | "--cookie-path", 22 | default="./cookies.json", 23 | help="The cookie file path (default is ./cookies.json)", 24 | ) 25 | @click.option( 26 | "--max_steps", default=20, type=int, help="The max_steps (default is 20)" 27 | ) 28 | @click.option( 29 | "--input_variables", 30 | multiple=True, 31 | type=(str, str), 32 | help="Input variables in the format key value", 33 | ) 34 | @click.option( 35 | "--generate-code", 36 | is_flag=True, 37 | default=False, 38 | help="Whether to generate the full integration code", 39 | ) 40 | def cli( 41 | model, prompt, har_path, cookie_path, max_steps, input_variables, generate_code 42 | ): 43 | input_vars = dict(input_variables) 44 | asyncio.run( 45 | call_agent( 46 | model, 47 | prompt, 48 | har_path, 49 | cookie_path, 50 | input_variables=input_vars, 51 | max_steps=max_steps, 52 | to_generate_code=generate_code, 53 | ) 54 | ) 55 | 56 | if __name__ == "__main__": 57 | cli() 58 | -------------------------------------------------------------------------------- /integuru/agent.py: -------------------------------------------------------------------------------- 1 | import json 2 | import urllib 3 | import os 4 | from datetime import datetime 5 | from typing import List, Dict, Any, Optional, Set 6 | 7 | from integuru.util.LLM import llm 8 | from integuru.models.DAGManager import DAGManager 9 | from integuru.util.har_processing import * 10 | from integuru.models.request import Request 11 | from integuru.models.agent_state import AgentState 12 | 13 | class IntegrationAgent: 14 | ACTION_URL_KEY: str = "action_url" 15 | IN_PROCESS_NODE_KEY: str = "in_process_node" 16 | TO_BE_PROCESSED_NODES_KEY: str = "to_be_processed_nodes" 17 | IN_PROCESS_NODE_DYNAMIC_PARTS_KEY: str = "in_process_node_dynamic_parts" 18 | MASTER_NODE_KEY: str = "master_node" 19 | INPUT_VARIABLES_KEY: str = "input_variables" 20 | 21 | def __init__( 22 | self, 23 | prompt: str, 24 | har_file_path: str, 25 | cookie_path: str, 26 | ): 27 | self.prompt: str = prompt 28 | self.duplicate_part_set: Set[str] = set() 29 | self.global_master_node: Optional[str] = None 30 | self.req_to_res_map: Dict[Request, str] = parse_har_file(har_file_path) 31 | self.url_to_res_req_dict: Dict[str, Dict[str, Any]] = build_url_to_req_res_map(self.req_to_res_map) 32 | self.har_urls: List[Tuple[str, str, str, str]] = get_har_urls(har_file_path) 33 | self.cookie_dict: Dict[str, Dict[str, Any]] = parse_cookie_file_to_dict(cookie_path) 34 | self.curl_to_id_dict: Dict[str, str] = {} 35 | self.cookie_to_id_dict: Dict[str, str] = {} 36 | self.dag_manager: DAGManager = DAGManager() 37 | 38 | def end_url_identify_agent(self, state: AgentState) -> AgentState: 39 | """ 40 | Identify the URL responsible for a specific action 41 | """ 42 | function_def = { 43 | "name": "identify_end_url", 44 | "description": "Identify the URL responsible for a specific action", 45 | "parameters": { 46 | "type": "object", 47 | "properties": { 48 | "url": { 49 | "type": "string", 50 | "description": f"The URL responsible for {self.prompt}" 51 | } 52 | }, 53 | "required": ["url"] 54 | } 55 | } 56 | 57 | prompt = f""" 58 | {self.har_urls} 59 | Task: 60 | Given the above list of URLs, request types, and response formats, find the URL responsible for the action below: 61 | {self.prompt} 62 | """ 63 | 64 | response = llm.get_instance().invoke( 65 | prompt, 66 | functions=[function_def], 67 | function_call={"name": "identify_end_url"} 68 | ) 69 | 70 | function_call = response.additional_kwargs['function_call'] 71 | end_url = json.loads(function_call['arguments'])['url'] 72 | 73 | state[self.ACTION_URL_KEY] = end_url 74 | return state 75 | 76 | def input_variables_identifying_agent(self, state: AgentState) -> AgentState: 77 | """ 78 | Identify input variables present in the cURL command 79 | """ 80 | in_process_node_id = state[self.IN_PROCESS_NODE_KEY] 81 | curl = self.dag_manager.graph.nodes[in_process_node_id]["content"]["key"].to_curl_command() 82 | input_variables = state[self.INPUT_VARIABLES_KEY] 83 | if not input_variables: 84 | return state 85 | 86 | function_def = { 87 | "name": "identify_input_variables", 88 | "description": "Identify input variables present in the cURL command.", 89 | "parameters": { 90 | "type": "object", 91 | "properties": { 92 | "identified_variables": { 93 | "type": "array", 94 | "items": { 95 | "type": "object", 96 | "properties": { 97 | "variable_name": {"type": "string", "description": "The original key of the variable"}, 98 | "variable_value": {"type": "string", "description": "The exact version of the variable that is present in the cURL command. This should closely match the value in the provided Input Variables."} 99 | }, 100 | "required": ["variable_name", "variable_value"] 101 | }, 102 | "description": "A list of identified variables and their values." 103 | } 104 | }, 105 | "required": ["identified_variables"] 106 | } 107 | } 108 | 109 | 110 | prompt = f""" 111 | cURL: {curl} 112 | Input Variables: {input_variables} 113 | 114 | Task: 115 | Identify which input variables (the value in the key-value pair) from the Input Variables provided above are present in the cURL command. 116 | 117 | Important: 118 | - If an input variable is found in the cURL, include it in the output. 119 | - Do not include variables that are not provided above. 120 | - The key of the input variable is a description of the variable. 121 | - The value is the value that should closely match the value in the cURL command. No substitutions. 122 | 123 | """ 124 | 125 | 126 | response = llm.get_instance().invoke( 127 | prompt, 128 | functions=[function_def], 129 | function_call={"name": "identify_input_variables"} 130 | ) 131 | 132 | function_call = response.additional_kwargs.get('function_call', {}) 133 | arguments = json.loads(function_call.get('arguments', '{}')) 134 | identified_variables = arguments.get('identified_variables', []) 135 | 136 | if identified_variables: 137 | # Convert the identified_variables format 138 | converted_variables = {item['variable_name']: item['variable_value'] for item in identified_variables} 139 | 140 | current_dynamic_parts = self.dag_manager.graph.nodes[in_process_node_id].get("dynamic_parts", []) 141 | updated_dynamic_parts = [part for part in current_dynamic_parts if part not in converted_variables.values()] 142 | self.dag_manager.update_node(in_process_node_id, dynamic_parts=updated_dynamic_parts, input_variables=converted_variables) 143 | 144 | return state 145 | 146 | def dynamic_part_identifying_agent(self, state: AgentState) -> AgentState: 147 | """ 148 | Identify dynamic parts present in the cURL command 149 | """ 150 | in_process_node_id = state[self.TO_BE_PROCESSED_NODES_KEY].pop() 151 | request = self.dag_manager.graph.nodes[in_process_node_id]["content"]["key"] 152 | curl = request.to_minified_curl_command() 153 | if curl.endswith(".js'"): 154 | self.dag_manager.update_node(in_process_node_id, dynamic_parts=[]) 155 | state[self.IN_PROCESS_NODE_DYNAMIC_PARTS_KEY] = [] 156 | state[self.IN_PROCESS_NODE_KEY] = in_process_node_id 157 | return state 158 | 159 | 160 | input_variables = state[self.INPUT_VARIABLES_KEY] 161 | 162 | function_def = { 163 | "name": "identify_dynamic_parts", 164 | "description": ( 165 | "Given the above cURL command, identify which parts are dynamic and validated by the server " 166 | "for correctness (e.g., IDs, tokens, session variables). Exclude any parameters that represent " 167 | "arbitrary user input or general data that can be hardcoded (e.g., amounts, notes, messages)." 168 | ), 169 | "parameters": { 170 | "type": "object", 171 | "properties": { 172 | "dynamic_parts": { 173 | "type": "array", 174 | "items": {"type": "string"}, 175 | "description": ( 176 | "List of dynamic parts identified in the cURL command. Do not include duplicates. " 177 | "Only strictly include the dynamic values (not the keys or any not extra part in front and after the value) of parts that are unique to a user or session " 178 | "and, if incorrect, will cause the request to fail." 179 | "Do not include the keys, only the values." 180 | ), 181 | } 182 | }, 183 | "required": ["dynamic_parts"], 184 | }, 185 | } 186 | 187 | prompt = f""" 188 | URL: {curl} 189 | 190 | Task: 191 | 192 | Use your best judgment to identify which parts of the cURL command are dynamic, specific to a user or session, and are checked by the server for validity. These include tokens, IDs, session variables, or any other values that are unique to a user or session and, if incorrect, will cause the request to fail. 193 | 194 | Important: 195 | - IGNORE THE COOKIE HEADER 196 | - Ignore common headers like user-agent, sec-ch-ua, accept-encoding, referer, etc. 197 | - Exclude parameters that represent arbitrary user input or general data that can be hardcoded, such as amounts, notes, messages, actions, etc. 198 | - Only output the variable values and not the keys. 199 | - Only include dynamic parts that are unique identifiers, tokens, or session variables. 200 | 201 | """ 202 | 203 | response = llm.get_instance().invoke( 204 | prompt, 205 | functions=[function_def], 206 | function_call={"name": "identify_dynamic_parts"} 207 | ) 208 | 209 | function_call = response.additional_kwargs['function_call'] 210 | dynamic_parts = json.loads(function_call['arguments'])['dynamic_parts'] 211 | 212 | self.dag_manager.update_node(in_process_node_id, dynamic_parts=dynamic_parts) 213 | 214 | # to detect if input_variables are in the request 215 | present_variables = [variable for variable in input_variables if variable in curl] 216 | if present_variables: 217 | for variable in present_variables: 218 | if variable in dynamic_parts: 219 | dynamic_parts.remove(variable) 220 | self.dag_manager.update_node(in_process_node_id, input_variables=present_variables) 221 | 222 | 223 | state[self.IN_PROCESS_NODE_DYNAMIC_PARTS_KEY] = dynamic_parts 224 | state[self.IN_PROCESS_NODE_KEY] = in_process_node_id 225 | return state 226 | 227 | def url_to_curl(self, state: AgentState) -> AgentState: 228 | """ 229 | Identify the master cURL command responsible for the action 230 | """ 231 | request = self.url_to_res_req_dict[state["action_url"]]["request"] 232 | curl = request.to_curl_command() 233 | if curl in self.curl_to_id_dict: 234 | master_node_id = self.curl_to_id_dict[curl] 235 | else: 236 | master_node_id = self.dag_manager.add_node( 237 | node_type="master_curl", # Specify node type 238 | content={ 239 | "key": request, 240 | "value": self.req_to_res_map[request] 241 | }, 242 | dynamic_parts=["None"], 243 | extracted_parts=["None"] 244 | ) 245 | self.curl_to_id_dict[curl] = master_node_id 246 | state[self.MASTER_NODE_KEY] = master_node_id 247 | state[self.TO_BE_PROCESSED_NODES_KEY].append(master_node_id) 248 | self.global_master_node_id = master_node_id 249 | return state 250 | 251 | def get_simplest_request(self, request_list: List[Request]) -> Request: 252 | """ 253 | Find the index of the simplest cURL command from a list 254 | """ 255 | function_def = { 256 | "name": "get_simplest_curl_index", 257 | "description": "Find the index of the simplest cURL command from a list", 258 | "parameters": { 259 | "type": "object", 260 | "properties": { 261 | "index": { 262 | "type": "integer", 263 | "description": "The index of the simplest cURL command in the list" 264 | } 265 | }, 266 | "required": ["index"] 267 | } 268 | } 269 | # convert request objects to strings 270 | serializable_list = [str(req) for req in request_list] 271 | 272 | prompt = f""" 273 | {json.dumps(serializable_list)} 274 | Task: 275 | Given the above list of cURL commands, find the index of the curl that has the least number of dependencies and variables. 276 | The index should be 0-based (i.e., the first item has index 0). 277 | """ 278 | 279 | response = llm.get_instance().invoke( 280 | prompt, 281 | functions=[function_def], 282 | function_call={"name": "get_simplest_curl_index"} 283 | ) 284 | 285 | function_call = response.additional_kwargs['function_call'] 286 | simplest_curl_index = json.loads(function_call['arguments'])['index'] 287 | 288 | # Retrieve the actual cURL command using the index 289 | simplest_curl = request_list[simplest_curl_index] 290 | return simplest_curl 291 | 292 | def find_curl_from_content(self, state: AgentState) -> AgentState: 293 | """ 294 | Find the cURL command that contains the dynamic parts 295 | """ 296 | search_string_list = state[self.IN_PROCESS_NODE_DYNAMIC_PARTS_KEY] 297 | search_string_list_leftovers = search_string_list.copy() 298 | 299 | in_process_node_id = state[self.IN_PROCESS_NODE_KEY] 300 | new_to_be_processed_nodes = [] 301 | 302 | # Handle cookies 303 | for search_string in search_string_list_leftovers[:]: 304 | cookie_key = self.find_key_by_string_in_value( 305 | self.cookie_dict, search_string 306 | ) 307 | if cookie_key: 308 | search_string_list_leftovers.remove(search_string) 309 | if cookie_key in self.cookie_to_id_dict: 310 | cookie_node_id = self.cookie_to_id_dict[cookie_key] 311 | else: 312 | cookie_node_id = self.dag_manager.add_node( 313 | node_type="cookie", # Specify node type 314 | content={ 315 | "key": cookie_key, 316 | "value": search_string 317 | }, 318 | extracted_parts=[search_string] 319 | ) 320 | self.cookie_to_id_dict[cookie_key] = cookie_node_id 321 | #dont need to add node to to_be_processed_nodes because cookies dont need further processing 322 | self.dag_manager.add_edge(in_process_node_id, cookie_node_id) 323 | 324 | # Handle curls 325 | if search_string_list_leftovers: 326 | for search_string in search_string_list_leftovers[:]: 327 | requests_with_search_string = [] 328 | 329 | for request, response in self.req_to_res_map.items(): 330 | curl = str(request) 331 | if ( 332 | ( 333 | isinstance(curl, str) 334 | and search_string.lower() in response["text"].lower() 335 | ) 336 | and (search_string.lower() not in curl.lower()) 337 | ) or ( 338 | urllib.parse.unquote(search_string) in curl 339 | and (urllib.parse.unquote(search_string) not in curl) 340 | ): 341 | requests_with_search_string.append(request) 342 | simplest_request = "" 343 | 344 | # Get simplest curl to reduce number of dependencies 345 | if len(requests_with_search_string) > 1: 346 | simplest_request = self.get_simplest_request(requests_with_search_string) 347 | elif len(requests_with_search_string) == 1: 348 | simplest_request = requests_with_search_string[0] 349 | else: 350 | print(f"Could not find curl with search string: {search_string} in response") 351 | not_found_node_id = self.dag_manager.add_node( 352 | node_type="not found", 353 | content={ 354 | "key": search_string 355 | }, 356 | ) 357 | self.dag_manager.add_edge(in_process_node_id, not_found_node_id) 358 | search_string_list_leftovers.remove(search_string) 359 | 360 | continue 361 | 362 | 363 | if simplest_request.url.endswith(".js") or "text/html" in self.req_to_res_map[simplest_request]["type"]: 364 | current_dynamic_parts = self.dag_manager.graph.nodes[in_process_node_id].get("dynamic_parts", []) 365 | updated_dynamic_parts = [part for part in current_dynamic_parts if part != search_string] 366 | self.dag_manager.update_node(in_process_node_id, dynamic_parts=updated_dynamic_parts) 367 | search_string_list_leftovers.remove(search_string) 368 | continue 369 | 370 | 371 | 372 | 373 | if simplest_request not in self.curl_to_id_dict: 374 | if simplest_request.url.endswith(".js"): 375 | self.dag_manager.update_node(in_process_node_id, dynamic_parts=[]) 376 | continue 377 | 378 | curl_node_id = self.dag_manager.add_node( 379 | node_type="curl", # Specify node type 380 | content={ 381 | "key": simplest_request, 382 | "value": self.req_to_res_map[simplest_request] 383 | }, 384 | extracted_parts=[search_string] 385 | ) 386 | self.curl_to_id_dict[simplest_request] = curl_node_id 387 | new_to_be_processed_nodes.append(curl_node_id) 388 | else: 389 | # append new extracted part to existing curl node 390 | curl_node_id = self.curl_to_id_dict[simplest_request] 391 | node = self.dag_manager.get_node(curl_node_id) 392 | new_extracted_parts = node.get("extracted_parts", []) 393 | new_extracted_parts.append(search_string) 394 | # Remove duplicates from new_extracted_parts 395 | new_extracted_parts = list(dict.fromkeys(new_extracted_parts)) 396 | 397 | self.dag_manager.update_node(curl_node_id, extracted_parts=new_extracted_parts) 398 | 399 | self.dag_manager.add_edge(in_process_node_id, curl_node_id) 400 | 401 | state[self.TO_BE_PROCESSED_NODES_KEY].extend(new_to_be_processed_nodes) 402 | state[self.IN_PROCESS_NODE_DYNAMIC_PARTS_KEY] = [] 403 | return state 404 | 405 | @staticmethod 406 | def find_key_by_string_in_value(dictionary: Dict[str, Dict[str, Any]], search_string: str) -> Optional[str]: 407 | for key, value in dictionary.items(): 408 | if search_string in value.get("value", ""): 409 | return key 410 | return None 411 | 412 | -------------------------------------------------------------------------------- /integuru/graph_builder.py: -------------------------------------------------------------------------------- 1 | from langgraph.graph import END, StateGraph 2 | from integuru.models.agent_state import AgentState 3 | from integuru.agent import IntegrationAgent 4 | from functools import partial # To pass extra arguments to functions 5 | from integuru.util.print import print_dag, visualize_dag, print_dag_in_reverse 6 | 7 | def check_end_condition(state, agent, to_generate_code): 8 | agent.dag_manager.detect_cycles() 9 | 10 | if len(state.get("to_be_processed_nodes", [])) == 0: 11 | print("------------------------Successfully analyzed!!!-------------------------------", flush=True) 12 | print_dag(agent.dag_manager.graph, agent.global_master_node_id) 13 | visualize_dag(agent.dag_manager.graph) 14 | print_dag_in_reverse(agent.dag_manager.graph, to_generate_code=to_generate_code) 15 | return "end" 16 | else: 17 | print("Continuing execution", flush=True) 18 | print(f"Generated graph at current step: {print_dag(agent.dag_manager.graph, agent.global_master_node_id)}", flush=True) 19 | return "continue" 20 | 21 | 22 | def build_graph(prompt, har_file_path="network_requests.har", cookie_path="cookies.json", to_generate_code=False): 23 | agent = IntegrationAgent(prompt, har_file_path, cookie_path) 24 | 25 | graph_builder = StateGraph(AgentState) 26 | 27 | # Add nodes using the agent's methods 28 | graph_builder.add_node("IntegrationAgent", agent.end_url_identify_agent) 29 | graph_builder.set_entry_point("IntegrationAgent") 30 | 31 | graph_builder.add_node("urlTocurl", agent.url_to_curl) 32 | graph_builder.add_edge("IntegrationAgent", "urlTocurl") 33 | 34 | graph_builder.add_node( 35 | "dynamicurlDataIdentifyingAgent", agent.dynamic_part_identifying_agent 36 | ) 37 | graph_builder.add_edge("urlTocurl", "dynamicurlDataIdentifyingAgent") 38 | 39 | graph_builder.add_node("inputVariablesIdentifyingAgent", agent.input_variables_identifying_agent) 40 | graph_builder.add_edge("dynamicurlDataIdentifyingAgent", "inputVariablesIdentifyingAgent") 41 | 42 | graph_builder.add_node("findcurlFromContent", agent.find_curl_from_content) 43 | graph_builder.add_edge("inputVariablesIdentifyingAgent", "findcurlFromContent") 44 | 45 | # Add conditional edges 46 | graph_builder.add_conditional_edges( 47 | "findcurlFromContent", 48 | partial(check_end_condition, agent=agent, to_generate_code=to_generate_code), 49 | {"end": END, "continue": "dynamicurlDataIdentifyingAgent"}, 50 | ) 51 | 52 | graph = graph_builder.compile() 53 | return graph, agent 54 | -------------------------------------------------------------------------------- /integuru/main.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from integuru.graph_builder import build_graph 3 | from integuru.util.LLM import llm 4 | 5 | agent = None 6 | 7 | async def call_agent( 8 | model: str, 9 | prompt: str, 10 | har_file_path: str, 11 | cookie_path: str, 12 | input_variables: dict = None, 13 | max_steps: int = 15, 14 | to_generate_code: bool = False, 15 | ): 16 | 17 | llm.set_default_model(model) 18 | 19 | global agent 20 | graph, agent = build_graph(prompt, har_file_path, cookie_path, to_generate_code) 21 | event_stream = graph.astream( 22 | { 23 | "master_node": None, 24 | "in_process_node": None, 25 | "to_be_processed_nodes": [], 26 | "in_process_node_dynamic_parts": [], 27 | "action_url": "", 28 | "input_variables": input_variables or {}, 29 | }, 30 | { 31 | "recursion_limit": max_steps, 32 | }, 33 | ) 34 | async for event in event_stream: 35 | # print("+++", event) 36 | pass 37 | -------------------------------------------------------------------------------- /integuru/models/DAGManager.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, Literal, Dict # Import Literal for type enforcement 2 | import networkx as nx 3 | import uuid 4 | 5 | 6 | class DAGManager: 7 | NODE_TYPES = {"cookie", "master", "cURL"} 8 | 9 | def __init__(self): 10 | self.graph = nx.DiGraph() 11 | self.root_id = None 12 | def add_node( 13 | self, 14 | node_type: Literal["cookie", "master", "cURL", "not found"], 15 | content: Optional[dict] = None, 16 | dynamic_parts: Optional[List[str]] = None, 17 | extracted_parts: Optional[List[str]] = None, 18 | input_variables: Optional[Dict[str, str]] = None, 19 | ): 20 | node_id = str(uuid.uuid4()) 21 | self.graph.add_node(node_id, node_type=node_type, content=content, dynamic_parts=dynamic_parts, extracted_parts=extracted_parts, input_variables=input_variables) 22 | return node_id 23 | 24 | def update_node( 25 | self, 26 | node_id: str, 27 | **attributes: Optional[List[str]]): 28 | 29 | for attr, value in attributes.items(): 30 | if value is not None: 31 | self.graph.nodes[node_id][attr] = value 32 | 33 | def detect_cycles(self): 34 | """ 35 | Detects if there are cycles in the DAG managed by this class. 36 | If a cycle is found, it returns the list of nodes involved in the cycle. 37 | If no cycle is found, it returns None. 38 | 39 | Returns: 40 | - A list of nodes forming a cycle, or None if no cycles are found. 41 | """ 42 | try: 43 | cycle = list(nx.find_cycle(self.graph, orientation='original')) 44 | print("Cycle detected:") 45 | return cycle 46 | except nx.exception.NetworkXNoCycle: 47 | return None 48 | 49 | def get_node(self, node_id: str) -> Optional[Dict]: 50 | """ 51 | Retrieves the attributes of the specified node. 52 | 53 | :param node_id: ID of the node to retrieve. 54 | :return: Dictionary of node attributes or None if the node does not exist. 55 | """ 56 | return self.graph.nodes.get(node_id, None) 57 | 58 | def add_edge(self, from_node_id: str, to_node_id: str): 59 | self.graph.add_edge(from_node_id, to_node_id) 60 | 61 | def __str__(self): 62 | nodes_info = [] 63 | for node_id in self.graph.nodes: 64 | attrs = self.graph.nodes[node_id] 65 | nodes_info.append(f"{node_id}: {attrs}") 66 | return "\n".join(nodes_info) 67 | -------------------------------------------------------------------------------- /integuru/models/agent_state.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, TypedDict, Dict 2 | 3 | class AgentState(TypedDict): 4 | master_node: str 5 | in_process_node: str 6 | to_be_processed_nodes: List[str] 7 | in_process_node_dynamic_parts: List[str] 8 | action_url: str 9 | input_variables: Dict[str, str] 10 | -------------------------------------------------------------------------------- /integuru/models/request.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict, Optional, Any 2 | import json 3 | 4 | class Request: 5 | def __init__(self, method: str, url: str, headers: Dict[str, str], 6 | query_params: Optional[Dict[str, str]] = None, body: Optional[Any] = None): 7 | self.method = method 8 | self.url = url 9 | self.headers = headers 10 | self.query_params = query_params 11 | self.body = body 12 | 13 | def to_curl_command(self) -> str: 14 | curl_parts = [f"curl -X {self.method}"] 15 | 16 | for name, value in self.headers.items(): 17 | curl_parts.append(f"-H '{name}: {value}'") 18 | 19 | if self.query_params: 20 | query_string = "&".join([f"{k}={v}" for k, v in self.query_params.items()]) 21 | self.url += f"?{query_string}" 22 | 23 | if self.body: 24 | content_type = None 25 | for k in self.headers: 26 | if k.lower() == 'content-type': 27 | content_type = self.headers[k] 28 | break 29 | 30 | if isinstance(self.body, dict): 31 | # Add Content-Type header if not present 32 | if not content_type: 33 | curl_parts.append(f"-H 'Content-Type: application/json'") 34 | curl_parts.append(f"--data '{json.dumps(self.body)}'") 35 | elif isinstance(self.body, str): 36 | curl_parts.append(f"--data '{self.body}'") 37 | 38 | curl_parts.append(f"'{self.url}'") 39 | 40 | return " ".join(curl_parts) 41 | 42 | def to_minified_curl_command(self) -> str: 43 | """ 44 | Minifies the curl command by removing referer and cookie headers. 45 | This is done to reduce LLM hallucinations. 46 | """ 47 | curl_parts = [f"curl -X {self.method}"] 48 | 49 | for name, value in self.headers.items(): 50 | if name.lower() not in ['referer', 'cookie']: 51 | curl_parts.append(f"-H '{name}: {value}'") 52 | 53 | if self.query_params: 54 | query_string = "&".join([f"{k}={v}" for k, v in self.query_params.items()]) 55 | self.url += f"?{query_string}" 56 | 57 | if self.body: 58 | content_type = None 59 | for k in self.headers: 60 | if k.lower() == 'content-type': 61 | content_type = self.headers[k] 62 | break 63 | 64 | if isinstance(self.body, dict): 65 | if not content_type: 66 | curl_parts.append(f"-H 'Content-Type: application/json'") 67 | curl_parts.append(f"--data '{json.dumps(self.body)}'") 68 | elif isinstance(self.body, str): 69 | curl_parts.append(f"--data '{self.body}'") 70 | 71 | curl_parts.append(f"'{self.url}'") 72 | 73 | return " ".join(curl_parts) 74 | 75 | def __str__(self) -> str: 76 | return self.to_curl_command() 77 | -------------------------------------------------------------------------------- /integuru/util/LLM.py: -------------------------------------------------------------------------------- 1 | from langchain_openai import ChatOpenAI 2 | 3 | class LLMSingleton: 4 | _instance = None 5 | _default_model = "gpt-4o" 6 | _alternate_model = "o1-preview" 7 | 8 | @classmethod 9 | def get_instance(cls, model: str = None): 10 | if model is None: 11 | model = cls._default_model 12 | 13 | if cls._instance is None: 14 | cls._instance = ChatOpenAI(model=model, temperature=1) 15 | return cls._instance 16 | 17 | @classmethod 18 | def set_default_model(cls, model: str): 19 | """Set the default model to use when no specific model is requested""" 20 | cls._default_model = model 21 | cls._instance = None # Reset instance to force recreation with new model 22 | 23 | @classmethod 24 | def revert_to_default_model(cls): 25 | """Set the default model to use when no specific model is requested""" 26 | print("Reverting to default model: ", cls._default_model, "Performance will be degraded as Integuru is using non O1 model") 27 | cls._alternate_model = cls._default_model 28 | 29 | @classmethod 30 | def switch_to_alternate_model(cls): 31 | """Returns a ChatOpenAI instance configured for o1-miniss""" 32 | # Create a new instance only if we don't have one yet 33 | cls._instance = ChatOpenAI(model=cls._alternate_model, temperature=1) 34 | 35 | return cls._instance 36 | 37 | llm = LLMSingleton() 38 | 39 | -------------------------------------------------------------------------------- /integuru/util/har_processing.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from urllib.parse import urlparse 4 | from integuru.models.request import Request 5 | from typing import Tuple, Dict, Optional, Any, List 6 | 7 | excluded_keywords = ( 8 | "google", 9 | "taboola", 10 | "datadog", 11 | "sentry", 12 | # "relic" 13 | ) 14 | 15 | excluded_header_keywords = ( 16 | "cookie", 17 | "sec-", 18 | "accept", 19 | "user-agent", 20 | "referer", 21 | "relic", 22 | "sentry", 23 | "datadog", 24 | "amplitude", 25 | "mixpanel", 26 | "segment", 27 | "heap", 28 | "hotjar", 29 | "fullstory", 30 | "pendo", 31 | "optimizely", 32 | "adobe", 33 | "analytics", 34 | "tracking", 35 | "telemetry", 36 | "clarity", # Microsoft Clarity 37 | "matomo", 38 | "plausible", 39 | ) 40 | 41 | def format_request(har_request: Dict[str, Any]) -> Request: 42 | """ 43 | Formats a HAR request into a Request object. 44 | """ 45 | method = har_request.get("method", "GET") 46 | url = har_request.get("url", "") 47 | 48 | # Store headers as a dictionary, excluding headers containing excluded keywords 49 | headers = { 50 | header.get("name", ""): header.get("value", "") 51 | for header in har_request.get("headers", []) 52 | if not any(keyword.lower() in header.get("name", "").lower() 53 | for keyword in excluded_header_keywords) 54 | } 55 | 56 | query_params_list = har_request.get("queryString", []) 57 | query_params = {param["name"]: param["value"] for param in query_params_list} if query_params_list else None 58 | 59 | post_data = har_request.get("postData", {}) 60 | body = post_data.get("text") if post_data else None 61 | 62 | # Try to parse body as JSON if Content-Type is application/json 63 | if body: 64 | headers_lower = {k.lower(): v for k, v in headers.items()} 65 | content_type = headers_lower.get('content-type') 66 | if content_type and 'application/json' in content_type.lower(): 67 | try: 68 | body = json.loads(body) 69 | except json.JSONDecodeError: 70 | pass # Keep body as is if not valid JSON 71 | 72 | return Request( 73 | method=method, 74 | url=url, 75 | headers=headers, 76 | query_params=query_params, 77 | body=body 78 | ) 79 | 80 | 81 | def format_response(har_response: Dict[str, Any]) -> Dict[str, str]: 82 | """ 83 | Extracts and returns the content text and content type from a HAR response. 84 | """ 85 | content = har_response.get("content", {}) 86 | return { 87 | "text": content.get("text", ""), 88 | "type": content.get("mimeType", "") 89 | } 90 | 91 | 92 | def parse_har_file(har_file_path: str) -> Dict[Request, Dict[str, str]]: 93 | """ 94 | Parses the HAR file and returns a dictionary mapping Request objects to response dictionaries. 95 | """ 96 | req_res_dict = {} 97 | 98 | with open(har_file_path, 'r', encoding='utf-8') as file: 99 | har_data = json.load(file) 100 | 101 | entries = har_data.get("log", {}).get("entries", []) 102 | 103 | for entry in entries: 104 | request_data = entry.get("request", {}) 105 | response_data = entry.get("response", {}) 106 | 107 | formatted_request = format_request(request_data) 108 | response_dict = format_response(response_data) 109 | 110 | req_res_dict[formatted_request] = response_dict 111 | 112 | return req_res_dict 113 | 114 | 115 | def build_url_to_req_res_map(req_res_dict: Dict[Request, Dict[str, str]]) -> Dict[str, Dict[str, Any]]: 116 | """ 117 | Builds a dictionary mapping URLs to {'request': formatted_request, 'response': response_dict} 118 | """ 119 | url_to_req_res_dict = {} 120 | 121 | for request, response in req_res_dict.items(): 122 | url = request.url 123 | # If multiple requests to the same URL, you can choose to overwrite or store all 124 | url_to_req_res_dict[url] = { 125 | 'request': request, 126 | 'response': response 127 | } 128 | 129 | return url_to_req_res_dict 130 | 131 | 132 | def get_har_urls(har_file_path: str) -> List[Tuple[str, str, str, str]]: 133 | """ 134 | Extracts and returns a list of tuples containing method, URL, response format, and response preview 135 | from a HAR file, excluding certain file types and keywords. 136 | """ 137 | # List to store tuples of URLs, request methods, response file formats, and response preview 138 | urls_with_details = [] 139 | 140 | # Define a tuple of file extensions to exclude 141 | excluded_extensions = ( 142 | ".png", 143 | ".jpg", 144 | ".jpeg", 145 | ".gif", 146 | ".webp", 147 | ".svg", 148 | ".ico", # Image files 149 | ".css", # Stylesheets 150 | # ".js", 151 | # ".map", # JavaScript files 152 | ".woff", 153 | ".woff2", 154 | ".ttf", 155 | ".otf", 156 | ".eot", # Font files 157 | ".mp3", 158 | ".mp4", 159 | ".wav", 160 | ".avi", 161 | ".mov", 162 | ".flv", 163 | ".wmv", 164 | ".webm", # Media files 165 | # ".pdf", 166 | # ".zip", 167 | ".rar", 168 | ".7z", 169 | ".tar", 170 | ".gz", 171 | ".exe", 172 | ".dmg", # Other non-text files 173 | ) 174 | 175 | # Read the HAR file 176 | with open(har_file_path, "r", encoding="utf-8") as file: 177 | har_data = json.load(file) 178 | 179 | # Extract entries from the HAR data 180 | entries = har_data.get("log", {}).get("entries", []) 181 | for entry in entries: 182 | request = entry.get("request", {}) 183 | response = entry.get("response", {}) 184 | url = request.get("url") 185 | method = request.get("method", "GET") # Default to 'GET' if method is missing 186 | response_format = response.get("content", {}).get("mimeType", "") 187 | response_text = response.get("content", {}).get("text", "") 188 | response_preview = response_text[:30] if response_text else "" 189 | 190 | if url: 191 | parsed_url = urlparse(url) 192 | path = parsed_url.path.lower() 193 | 194 | _, extension = os.path.splitext(path) 195 | 196 | request_text = url.lower() 197 | 198 | headers = request.get("headers", []) 199 | for header in headers: 200 | request_text += header.get("name", "").lower() 201 | request_text += header.get("value", "").lower() 202 | 203 | postData = request.get("postData", {}).get("text", "").lower() 204 | request_text += postData 205 | 206 | # Exclude URLs with the specified extensions or if keywords are in the request 207 | # this is done to reduce the number of requests we send to the LLM 208 | if extension not in excluded_extensions and not any( 209 | keyword.lower() in request_text for keyword in excluded_keywords 210 | ): 211 | urls_with_details.append((method, url, response_format, response_preview)) 212 | 213 | return urls_with_details 214 | 215 | 216 | def parse_cookie_file_to_dict(cookie_file_path: str) -> Dict[str, Dict[str, Any]]: 217 | """ 218 | Parses a JSON cookie file and returns a dictionary of cookie data. 219 | """ 220 | parsed_data = {} 221 | 222 | with open(cookie_file_path, "r") as file: 223 | cookies = json.load(file) 224 | 225 | for cookie in cookies: 226 | name = cookie.get("name") 227 | value = cookie.get("value") 228 | domain = cookie.get("domain") 229 | path = cookie.get("path") 230 | 231 | if name: 232 | parsed_data[name] = { 233 | "value": value, 234 | "domain": domain, 235 | "path": path, 236 | "expires": cookie.get("expires"), 237 | "httpOnly": cookie.get("httpOnly"), 238 | "secure": cookie.get("secure"), 239 | "sameSite": cookie.get("sameSite"), 240 | } 241 | 242 | return parsed_data 243 | -------------------------------------------------------------------------------- /integuru/util/print.py: -------------------------------------------------------------------------------- 1 | from platform import node 2 | import matplotlib.pyplot as plt 3 | import networkx as nx 4 | from typing import Dict, Set, Optional, Any 5 | from integuru.util.LLM import llm 6 | import json 7 | from langchain_openai import ChatOpenAI 8 | from typing import List 9 | from openai import NotFoundError # Add this import 10 | 11 | def print_dag( 12 | graph: nx.DiGraph, 13 | current_node_id: str, 14 | prefix: str = "", 15 | is_last: bool = True, 16 | visited: Optional[Set[str]] = None, 17 | depth: int = 0, 18 | max_depth: Optional[int] = None, 19 | ) -> None: 20 | """ 21 | Recursively prints the DAG structure with visual connectors and cUrl. 22 | """ 23 | if visited is None: 24 | visited = set() 25 | 26 | connector = "└── " if is_last else "├── " 27 | new_prefix = prefix + (" " if is_last else "│ ") 28 | 29 | node_attrs = graph.nodes[current_node_id] 30 | dynamic_parts = node_attrs.get("dynamic_parts", []) 31 | key = node_attrs.get("content", "").get("key", "") 32 | extracted_parts = node_attrs.get("extracted_parts", []) 33 | input_variables = node_attrs.get("input_variables", []) 34 | node_type = node_attrs.get("node_type", "") # Get node type 35 | 36 | node_label = f"[{node_type}] [node_id: {current_node_id}]" 37 | if input_variables: 38 | node_label += f"\n{new_prefix} [input_variables: {input_variables}]" 39 | node_label += f"\n{new_prefix} [dynamic_parts: {dynamic_parts}]" 40 | node_label += f"\n{new_prefix} [extracted_parts: {extracted_parts}]" 41 | node_label += f"\n{new_prefix} [{key}]" 42 | 43 | print(f"{prefix}{connector}{node_label}") 44 | 45 | visited.add(current_node_id) 46 | 47 | if max_depth is not None and depth >= max_depth: 48 | return 49 | 50 | children = list(graph.successors(current_node_id)) 51 | child_count = len(children) 52 | 53 | for i, child_id in enumerate(children): 54 | is_last_child = i == child_count - 1 55 | 56 | if child_id in visited: 57 | loop_connector = "└── " if is_last_child else "├── " 58 | print(f"{new_prefix}{loop_connector}(Already visited) [node_id: {child_id}]") 59 | else: 60 | print_dag( 61 | graph, 62 | child_id, 63 | prefix=new_prefix, 64 | is_last=is_last_child, 65 | visited=visited, 66 | depth=depth + 1, 67 | max_depth=max_depth, 68 | ) 69 | 70 | 71 | def visualize_dag(graph: nx.DiGraph) -> None: 72 | """ 73 | Visualizes the DAG using Matplotlib with arrows indicating direction. 74 | """ 75 | plt.switch_backend("Agg") 76 | 77 | pos = nx.spring_layout(graph) 78 | 79 | nx.draw_networkx_nodes(graph, pos, node_size=700, node_color="lightblue") 80 | 81 | nx.draw_networkx_edges( 82 | graph, pos, edgelist=graph.edges, arrowstyle="->", arrowsize=20 83 | ) 84 | 85 | labels = {node: f"{node}" for node in graph.nodes()} 86 | nx.draw_networkx_labels(graph, pos, labels, font_size=10) 87 | 88 | edge_labels = nx.get_edge_attributes(graph, "cUrl") 89 | nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels) 90 | 91 | plt.title("Directed Acyclic Graph (DAG)") 92 | plt.savefig("dag_visualization.png") 93 | plt.close() 94 | 95 | 96 | def find_json_path(json_obj, target_value, current_path=None): 97 | """ 98 | Finds the path(s) to a given value in a JSON object. 99 | 100 | Args: 101 | json_obj (dict or list): The JSON object to search. 102 | target_value: The value to find in the JSON object. 103 | current_path (list): The current path being explored (used for recursion). 104 | 105 | Returns: 106 | list: A list of dictionaries, each containing 'key_path' and 'value' for each occurrence of the target value. 107 | """ 108 | if current_path is None: 109 | current_path = [] 110 | 111 | results = [] 112 | 113 | if isinstance(json_obj, dict): 114 | for key, value in json_obj.items(): 115 | new_path = current_path + [key] 116 | if value == target_value: 117 | results.append({ 118 | 'key_path': new_path, 119 | 'value': value 120 | }) 121 | if isinstance(value, (dict, list)): 122 | results.extend(find_json_path(value, target_value, new_path)) 123 | elif isinstance(json_obj, list): 124 | for i, item in enumerate(json_obj): 125 | new_path = current_path + [i] 126 | if item == target_value: 127 | results.append({ 128 | 'key_path': new_path, 129 | 'value': item 130 | }) 131 | if isinstance(item, (dict, list)): 132 | results.extend(find_json_path(item, target_value, new_path)) 133 | 134 | return results 135 | 136 | 137 | 138 | def generate_code(node_id: str, graph: nx.DiGraph) -> str: 139 | """ 140 | Generates Python code for a given node in the graph based on its attributes. 141 | """ 142 | 143 | node_attrs = graph.nodes[node_id] 144 | 145 | if node_attrs.get("node_type", "") == "cookie": 146 | cookie_value = node_attrs.get('content', {}).get('value', '') 147 | cookie_key = node_attrs.get('content', {}).get('key', '') 148 | return f"{cookie_value} = cookie_dict['{cookie_key}']" 149 | 150 | content = node_attrs.get("content", {}) 151 | curl = content.get("key", "") 152 | response = content.get("value", {}) 153 | response_type = response.get("type", "") 154 | response_text = response.get("text", "") 155 | 156 | dynamic_parts = node_attrs.get("dynamic_parts", "") 157 | extracted_parts = node_attrs.get("extracted_parts", "") 158 | input_variables = node_attrs.get("input_variables", "") 159 | to_parse_response = True 160 | 161 | parse_response_prompt = "" 162 | 163 | if response_type in ["application/octet-stream", "application/pdf", "application/zip", "image/jpeg", "image/png"]: 164 | parse_response_prompt = f""" 165 | The response is a downloadable file of type {response_type}. 166 | Include code to save the response content to a file with an appropriate extension. 167 | """ 168 | 169 | if "application/json" in response_type: 170 | key_paths = [] 171 | for extracted_part in extracted_parts: 172 | key_path = find_json_path(json.loads(response_text), extracted_part) 173 | key_paths.append(key_path) 174 | 175 | parse_response_prompt = f""" 176 | Response: 177 | {response_text} 178 | 179 | Parse out the following variables from the response using JSON keys: 180 | {key_paths} 181 | 182 | Through your judgement from analyzing the response, if polling is required to retrieve the variables above from the response. If so, implement polling else dont. 183 | """ 184 | 185 | if "text/html" in response_type or "application/javascript" in response_type: 186 | if len(response_text) > 100000: 187 | context_snippets = [] 188 | for part in extracted_parts: 189 | index = response_text.find(part) 190 | if index != -1: 191 | start = max(0, index - 50) 192 | end = min(len(response_text), index + len(part) + 50) 193 | snippet = response_text[start:end] 194 | context_snippets.append(f"{part}: {snippet}") 195 | 196 | parse_response_prompt = f""" 197 | The HTML response is too long to process entirely. 198 | Here are the relevant sections for each variable to be extracted: 199 | 200 | {chr(10).join(context_snippets)} 201 | 202 | """ 203 | else: 204 | parse_response_prompt = f""" 205 | Response: 206 | {response_text} 207 | """ 208 | parse_response_prompt += f""" 209 | Parse out the variables following variables locations from the response using regex using locational context: 210 | 211 | {extracted_parts} 212 | Do not include the variable in the regex filter as the variable will change. And do not be too specific with the regex. 213 | 214 | """ 215 | 216 | dynamic_parts_prompt = "" 217 | if dynamic_parts: 218 | dynamic_parts_prompt = f""" 219 | Instead of hard coding, pass the following variables into the function as parameters in a dict. The dict should have keys thats the same as the value itself 220 | {dynamic_parts} 221 | 222 | Keep everything else in the header hardcoded. 223 | """ 224 | 225 | prompt = f""" 226 | Task: 227 | Write a Python function with a descriptive name that makes a request like the cURL below: 228 | {curl} 229 | 230 | 231 | Assume cookies are in a variable as parameter called "cookie_string". 232 | 233 | The parameters should be {"1. a dict of all the parameters and 2. Just the cookie string" if dynamic_parts else "only the cookie string"}. 234 | 235 | {dynamic_parts_prompt} 236 | 237 | {parse_response_prompt} 238 | 239 | Return a dictionary with the keys as the original parsed values content (needs to be hardcoded) and the values as the parsed values. 240 | 241 | Do not include pseudo-headers or any headers that start with a colon in the request. 242 | 243 | IMPORTANT! Do not include any backticks or markdown syntax AT ALL 244 | 245 | """ 246 | 247 | # Make the API call using o1_llm 248 | 249 | llm_model = llm.switch_to_alternate_model() 250 | try: 251 | response = llm_model.invoke(prompt) 252 | except Exception as e: 253 | print("Switching to default model") 254 | llm.revert_to_default_model() 255 | response = llm.switch_to_alternate_model().invoke(prompt) 256 | 257 | # Extract the generated code from the response 258 | code = response.content.strip() 259 | 260 | # cannot get chatgpt to not return backticks 261 | if code.startswith("```python"): 262 | code = code[10:] 263 | if code.endswith("```"): 264 | code = code[:-3] 265 | 266 | return code 267 | 268 | def aggregate_functions(txt_path, output_path): 269 | # Read the content of the file 270 | with open(txt_path, 'r') as file: 271 | content = file.read() 272 | 273 | # Initialize ChatGPT 274 | 275 | # Prepare the prompt for ChatGPT 276 | prompt = f""" 277 | The following text contains multiple Python functions: 278 | 279 | {content} 280 | 281 | Please generate Python code that does the following: 282 | 1. Fix up the functions if needed in the order they appear in the text. 283 | 2. Leave everything that is hardcoded as is. 284 | 3. Call each function in the order they appear in the text. 285 | 4. The cookies will be hard coded in the file in a string format of key=value;key=value. You will need to convert them to a dict to retrieve values from them. 286 | 5. Pass the return value of each function as an argument to the next function, if applicable. 287 | 6. Ensure that the last function in the text is called last. 288 | 7. Output the entire directly runnable code 289 | 290 | 291 | 292 | Only provide the Python code, without any explanations or markdown formatting. 293 | DO NOT include any backticks or markdown syntax AT ALL 294 | """ 295 | 296 | # Get the response from ChatGPT 297 | 298 | llm_model = llm.switch_to_alternate_model() 299 | try: 300 | response = llm_model.invoke(prompt) 301 | except Exception as e: 302 | print("Switching to default model") 303 | llm.revert_to_default_model() 304 | response = llm.switch_to_alternate_model().invoke(prompt) 305 | # Extract the generated code 306 | generated_code = response.content.strip() 307 | 308 | # Save the generated code to the specified output file 309 | with open(output_path, 'w') as file: 310 | file.write(generated_code) 311 | 312 | print(f"Aggregated function calls have been saved to '{output_path}'") 313 | 314 | return output_path 315 | 316 | def generate_obfuscation_map(dynamic_parts_list: List[str]) -> Dict[str, str]: 317 | obfuscation_map = {} 318 | for part in dynamic_parts_list: 319 | # Replace invalid characters with underscores and prepend with 'var_' to ensure it starts with a letter 320 | safe_key = f"var_{hash(part)}".replace('-', '_').replace('.', '_') 321 | obfuscation_map[part] = safe_key 322 | return obfuscation_map 323 | 324 | def swap_string_using_obfuscation_map(input_string: str, obfuscation_map: Dict[str, str]) -> str: 325 | """ 326 | Swaps all parts in the input string that match keys in the obfuscation map with their corresponding values. 327 | 328 | Args: 329 | input_string (str): The string to perform replacements on. 330 | obfuscation_map (Dict[str, str]): The obfuscation map with keys to be replaced by their values. 331 | 332 | Returns: 333 | str: The modified string with replacements made. 334 | """ 335 | for key, value in obfuscation_map.items(): 336 | input_string = input_string.replace(key, value) 337 | return input_string 338 | 339 | def print_dag_in_reverse(graph: nx.DiGraph, max_depth: Optional[int] = None, to_generate_code: bool = False) -> None: 340 | """ 341 | Generates the order of requests to be made based on the DAG. 342 | Prints the DAG starting from source nodes and ending at sink nodes, traversing successors. 343 | """ 344 | if to_generate_code: 345 | print("--------------Generating code------------") 346 | 347 | generated_code = "" 348 | 349 | dynamic_parts_list = [] 350 | 351 | def _print_dag_recursive( 352 | current_node_id: str, 353 | prefix: str = "", 354 | is_last: bool = True, 355 | visited: Optional[Set[str]] = None, 356 | fully_processed: Optional[Set[str]] = None, 357 | depth: int = 0, 358 | ) -> None: 359 | """ 360 | Helper function to recursively print the DAG in reverse order. 361 | """ 362 | nonlocal generated_code, dynamic_parts_list 363 | if visited is None: 364 | visited = set() 365 | if fully_processed is None: 366 | fully_processed = set() 367 | 368 | if current_node_id in fully_processed: 369 | return 370 | 371 | if current_node_id in visited: 372 | # Avoid infinite recursion in case of cycles 373 | return 374 | 375 | visited.add(current_node_id) 376 | 377 | if max_depth is not None and depth >= max_depth: 378 | visited.remove(current_node_id) 379 | return 380 | 381 | # Get child nodes (successors) 382 | children = list(graph.successors(current_node_id)) 383 | child_count = len(children) 384 | 385 | # Recursively process child nodes first 386 | for i, child_id in enumerate(children): 387 | is_last_child = i == child_count - 1 388 | new_prefix = prefix + (" " if is_last else "│ ") 389 | _print_dag_recursive( 390 | child_id, 391 | prefix=new_prefix, 392 | is_last=is_last_child, # Ensure this argument is passed correctly 393 | visited=visited, 394 | fully_processed=fully_processed, 395 | depth=depth + 1, 396 | ) 397 | 398 | # After all children have been processed, print the current node 399 | connector = "└── " if is_last else "├── " 400 | print(f"{prefix}{connector}{get_node_label(graph, current_node_id)}") 401 | if to_generate_code: 402 | generated_code += generate_code(current_node_id, graph) + "\n\n" 403 | fully_processed.add(current_node_id) 404 | visited.remove(current_node_id) 405 | 406 | def get_node_label(graph: nx.DiGraph, node_id: str) -> str: 407 | """ 408 | Generates a label for a node in the graph based on its attributes. 409 | """ 410 | # Get node attributes 411 | node_attrs = graph.nodes[node_id] 412 | dynamic_parts = node_attrs.get("dynamic_parts", []) 413 | extracted_parts = node_attrs.get("extracted_parts", "") 414 | content = node_attrs.get("content", "") 415 | key = content.get("key", "") 416 | input_variables = node_attrs.get("input_variables", "") 417 | 418 | if dynamic_parts: 419 | dynamic_parts_list.extend(dynamic_parts) 420 | node_type = node_attrs.get("node_type", "") 421 | node_label = f"[{node_type}] " 422 | node_label += f"[node_id: {node_id}]" 423 | node_label += f" [dynamic_parts: {dynamic_parts}]" 424 | node_label += f" [extracted_parts: {extracted_parts}]" 425 | node_label += f" [input_variables: {input_variables}]" 426 | node_label += f" [{key}]" 427 | return node_label 428 | 429 | # Start from source nodes (nodes with no incoming edges) 430 | source_nodes = [n for n in graph.nodes() if graph.in_degree(n) == 0] 431 | 432 | fully_processed = set() 433 | for idx, source_node in enumerate(source_nodes): 434 | is_last_source = idx == len(source_nodes) - 1 435 | _print_dag_recursive( 436 | source_node, 437 | prefix="", 438 | is_last=is_last_source, 439 | visited=set(), 440 | fully_processed=fully_processed, 441 | depth=0, 442 | ) 443 | 444 | if to_generate_code: 445 | obfuscation_map = generate_obfuscation_map(dynamic_parts_list) 446 | generated_code = swap_string_using_obfuscation_map(generated_code, obfuscation_map) 447 | with open("generated_code.txt", "w") as f: 448 | f.write(generated_code) 449 | 450 | aggregate_functions("generated_code.txt", "generated_code.py") 451 | print("--------------Generated integration code in generated_code.py!!------------") 452 | 453 | 454 | 455 | -------------------------------------------------------------------------------- /integuru_demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Integuru-AI/Integuru/a31446f9453cab892f48005cf5e0b0674699f9b5/integuru_demo.gif -------------------------------------------------------------------------------- /main.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "%load_ext autoreload\n", 10 | "%autoreload 2" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "from typing import List\n", 20 | "from integuru.graph_builder import build_graph\n", 21 | "from integuru.util.LLM import llm\n", 22 | "from dotenv import load_dotenv\n", 23 | "\n", 24 | "load_dotenv()\n", 25 | "\n", 26 | "agent = None\n", 27 | "\n", 28 | "async def call_agent(\n", 29 | " model: str,\n", 30 | " prompt: str,\n", 31 | " max_steps: int = 10,\n", 32 | " har_file_path: str = \"turbo.har\",\n", 33 | " cookie_path: str = \"turbo.json\",\n", 34 | " input_variables: dict = None,\n", 35 | "): \n", 36 | " \n", 37 | " llm.set_default_model(model)\n", 38 | " global agent\n", 39 | " graph, agent = build_graph(prompt, har_file_path, cookie_path)\n", 40 | " event_stream = graph.astream(\n", 41 | " {\n", 42 | " \"master_node\": None,\n", 43 | " \"in_process_node\": None,\n", 44 | " \"to_be_processed_nodes\": [],\n", 45 | " \"in_process_node_dynamic_parts\": [],\n", 46 | " \"action_url\": \"\",\n", 47 | " \"input_variables\": input_variables or {}, \n", 48 | " },\n", 49 | " {\n", 50 | " \"recursion_limit\": max_steps,\n", 51 | " },\n", 52 | " )\n", 53 | " async for event in event_stream:\n", 54 | " print(\"+++\", event)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "\n", 64 | "model = \"gpt-4o\"\n", 65 | "prompt = \"Download my bank statement file.\"\n", 66 | "input_variables = {\n", 67 | "}\n", 68 | "har_path = \"network_requests.har\"\n", 69 | "cookie_path = \"cookies.json\" \n", 70 | "max_steps = 15\n", 71 | "await call_agent(model=model, prompt=prompt, har_file_path=har_path, cookie_path=cookie_path, max_steps=max_steps, input_variables=input_variables)" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "from integuru.util.print import *\n", 81 | "\n", 82 | "print_dag(agent.dag_manager.graph, agent.global_master_node_id)" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "print_dag_in_reverse(agent.dag_manager.graph, to_generate_code=True)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [] 100 | } 101 | ], 102 | "metadata": { 103 | "kernelspec": { 104 | "display_name": "integuru", 105 | "language": "python", 106 | "name": "integuru" 107 | }, 108 | "language_info": { 109 | "codemirror_mode": { 110 | "name": "ipython", 111 | "version": 3 112 | }, 113 | "file_extension": ".py", 114 | "mimetype": "text/x-python", 115 | "name": "python", 116 | "nbconvert_exporter": "python", 117 | "pygments_lexer": "ipython3", 118 | "version": "3.12.7" 119 | } 120 | }, 121 | "nbformat": 4, 122 | "nbformat_minor": 2 123 | } 124 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "integuru" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["alanalanlu "] 6 | readme = "README.md" 7 | 8 | [tool.poetry.dependencies] 9 | python = ">=3.12,<3.13" 10 | langchain-openai = "^0.2.0" 11 | langchain-core = "^0.3.1" 12 | langgraph = "^0.2.22" 13 | langsmith = "^0.1.122" 14 | python-dotenv = "^1.0.1" 15 | click = "^8.1.7" 16 | playwright = "^1.47.0" 17 | networkx = "^3.3" 18 | matplotlib = "^3.9.2" 19 | ipykernel = "^6.29.5" 20 | 21 | [tool.poetry.scripts] 22 | integuru = "integuru.__main__:cli" 23 | 24 | [tool.poetry.dev-dependencies] 25 | pytest = "^7.0" 26 | 27 | [build-system] 28 | requires = ["poetry-core"] 29 | build-backend = "poetry.core.masonry.api" 30 | -------------------------------------------------------------------------------- /tests/test_integration_agent.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from integuru.agent import IntegrationAgent 3 | from integuru.models.agent_state import AgentState 4 | from unittest.mock import patch, MagicMock 5 | 6 | class TestIntegrationAgent(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.prompt = "Test prompt" 10 | self.har_file_path = "test.har" 11 | self.cookie_path = "test_cookies.json" 12 | self.agent = IntegrationAgent(self.prompt, self.har_file_path, self.cookie_path) 13 | self.state = AgentState( 14 | master_node=None, 15 | in_process_node=None, 16 | to_be_processed_nodes=[], 17 | in_process_node_dynamic_parts=[], 18 | action_url="", 19 | input_variables={} 20 | ) 21 | 22 | @patch('integuru.agent.llm.get_instance') 23 | def test_end_url_identify_agent(self, mock_llm_instance): 24 | mock_response = MagicMock() 25 | mock_response.additional_kwargs = { 26 | 'function_call': { 27 | 'arguments': '{"url": "http://example.com/action"}' 28 | } 29 | } 30 | mock_llm_instance.return_value.invoke.return_value = mock_response 31 | 32 | updated_state = self.agent.end_url_identify_agent(self.state) 33 | self.assertEqual(updated_state[self.agent.ACTION_URL_KEY], "http://example.com/action") 34 | 35 | @patch('integuru.agent.llm.get_instance') 36 | def test_input_variables_identifying_agent(self, mock_llm_instance): 37 | self.state[self.agent.IN_PROCESS_NODE_KEY] = "node_1" 38 | self.state[self.agent.INPUT_VARIABLES_KEY] = {"var1": "value1"} 39 | self.agent.dag_manager.graph.add_node("node_1", content={"key": MagicMock()}) 40 | self.agent.dag_manager.graph.nodes["node_1"]["content"]["key"].to_curl_command.return_value = "curl command" 41 | 42 | mock_response = MagicMock() 43 | mock_response.additional_kwargs = { 44 | 'function_call': { 45 | 'arguments': '{"identified_variables": [{"variable_name": "var1", "variable_value": "value1"}]}' 46 | } 47 | } 48 | mock_llm_instance.return_value.invoke.return_value = mock_response 49 | 50 | updated_state = self.agent.input_variables_identifying_agent(self.state) 51 | self.assertEqual(updated_state[self.agent.INPUT_VARIABLES_KEY], {"var1": "value1"}) 52 | 53 | @patch('integuru.agent.llm.get_instance') 54 | def test_dynamic_part_identifying_agent(self, mock_llm_instance): 55 | self.state[self.agent.TO_BE_PROCESSED_NODES_KEY] = ["node_1"] 56 | self.agent.dag_manager.graph.add_node("node_1", content={"key": MagicMock()}) 57 | self.agent.dag_manager.graph.nodes["node_1"]["content"]["key"].to_minified_curl_command.return_value = "curl command" 58 | 59 | mock_response = MagicMock() 60 | mock_response.additional_kwargs = { 61 | 'function_call': { 62 | 'arguments': '{"dynamic_parts": ["dynamic_part1"]}' 63 | } 64 | } 65 | mock_llm_instance.return_value.invoke.return_value = mock_response 66 | 67 | updated_state = self.agent.dynamic_part_identifying_agent(self.state) 68 | self.assertEqual(updated_state[self.agent.IN_PROCESS_NODE_DYNAMIC_PARTS_KEY], ["dynamic_part1"]) 69 | 70 | if __name__ == '__main__': 71 | unittest.main() 72 | --------------------------------------------------------------------------------