├── .gitignore ├── LICENSE ├── README.md ├── openai_chat ├── README.md ├── __init__.py ├── __manifest__.py ├── data │ ├── openai-odoo-avatar.png │ ├── openai_chat_data.xml │ └── openai_completion_data.xml ├── i18n │ └── fr.po ├── models │ ├── __init__.py │ ├── mail_ai_bot.py │ ├── mail_channel.py │ ├── mail_thread.py │ ├── res_partner.py │ └── res_users.py ├── security │ ├── ir.model.access.csv │ └── security.xml └── static │ ├── description │ ├── icon.png │ ├── index.html │ └── logo.png │ ├── img │ ├── chat.png │ ├── clear_chat.png │ ├── discuss.png │ ├── logo.png │ ├── longer_answer.png │ ├── open_chat.png │ ├── openai_logo.svg │ └── truncated_answer.png │ └── src │ └── models │ └── messaging_initializer.js ├── openai_connector ├── README.md ├── __init__.py ├── __manifest__.py ├── i18n │ └── fr.po ├── models │ ├── __init__.py │ ├── openai_completion.py │ ├── openai_completion_result.py │ ├── openai_fine_tuning.py │ ├── openai_image.py │ ├── openai_image_result.py │ ├── openai_mixin.py │ ├── openai_question_answer.py │ ├── openai_result_mixin.py │ ├── openai_tool.py │ ├── openai_tool_property.py │ └── res_config_settings.py ├── security │ ├── ir.model.access.csv │ └── security.xml ├── static │ ├── description │ │ ├── icon.png │ │ ├── index.html │ │ └── logo.png │ ├── img │ │ ├── completion_params.png │ │ ├── openai_logo.svg │ │ ├── openai_params.png │ │ ├── prompt.png │ │ ├── settings.png │ │ └── tests.png │ └── src │ │ └── scss │ │ └── style.scss └── views │ ├── openai_completion_result_views.xml │ ├── openai_completion_views.xml │ ├── openai_fine_tuning_views.xml │ ├── openai_image_result_views.xml │ ├── openai_image_views.xml │ ├── openai_question_answer_views.xml │ └── res_config_settings_views.xml ├── openai_edit_product_image ├── README.md ├── __init__.py ├── __manifest__.py ├── data │ ├── openai_edit_data.xml │ └── prompt_templates.xml ├── i18n │ └── fr.po ├── models │ ├── __init__.py │ └── product.py ├── security │ ├── ir.model.access.csv │ └── security.xml ├── static │ ├── description │ │ ├── icon.png │ │ ├── index.html │ │ └── logo.png │ └── img │ │ ├── apply_image.png │ │ ├── config_product.png │ │ ├── create_image.png │ │ ├── create_image_prompt.png │ │ ├── openai_logo.svg │ │ ├── product.png │ │ └── product_results.png └── views │ ├── openai_product_result_views.xml │ └── product_views.xml ├── openai_product_description ├── README.md ├── __init__.py ├── __manifest__.py ├── data │ ├── openai_completion_data.xml │ └── prompt_templates.xml ├── i18n │ └── fr.po ├── models │ ├── __init__.py │ └── product.py ├── security │ ├── ir.model.access.csv │ └── security.xml ├── static │ ├── description │ │ ├── icon.png │ │ ├── index.html │ │ └── logo.png │ └── img │ │ ├── create_description_action.png │ │ ├── openai_logo.svg │ │ └── results.png └── views │ └── openai_product_result_views.xml ├── openai_product_tags ├── README.md ├── __init__.py ├── __manifest__.py ├── data │ ├── openai_completion_data.xml │ └── prompt_templates.xml ├── i18n │ └── fr.po ├── models │ ├── __init__.py │ └── product.py ├── security │ ├── ir.model.access.csv │ └── security.xml ├── static │ ├── description │ │ ├── icon.png │ │ ├── index.html │ │ └── logo.png │ └── img │ │ ├── create_tags_action.png │ │ ├── openai_logo.svg │ │ └── product_tags.png └── views │ └── openai_product_result_views.xml └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 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 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | #Pycharm 132 | .idea 133 | -------------------------------------------------------------------------------- /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 by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # odoo-openai 2 | OpenAI tools integration in Odoo (ChatGPT, GPT3, DALL-E...) 3 | 4 | | | Addons | Description | Versions | 5 | |---------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|---------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------| 6 | | [](./openai_connector/README.md) | [openai_connector](./openai_connector/README.md) | Connector for OpenAI API | ![16.0](https://img.shields.io/badge/-16.0-blueviolet)![17.0](https://img.shields.io/badge/-17.0-blue) | 7 | | [](./openai_chat/README.md) | [openai_chat](./openai_chat/README.md) | Add an AI Bot user to chat with like in ChatGPT | ![16.0](https://img.shields.io/badge/-16.0-blueviolet)![17.0](https://img.shields.io/badge/-17.0-blue) | 8 | | [](./openai_edit_product_image/README.md) | [openai_edit_product_image](./openai_edit_product_image/README.md) | Create a new product image from a cropped product image with DALL-E | ![16.0](https://img.shields.io/badge/-16.0-blueviolet)![17.0](https://img.shields.io/badge/-17.0-blue) | 9 | | [](./openai_product_description/README.md) | [openai_product_description](./openai_product_description/README.md) | Generate a product sales description with OpenAI | ![16.0](https://img.shields.io/badge/-16.0-blueviolet)![17.0](https://img.shields.io/badge/-17.0-blue) | 10 | | [](./openai_product_tags/README.md) | [openai_product_tags](./openai_product_tags/README.md) | Generate product tags with OpenAI | ![16.0](https://img.shields.io/badge/-16.0-blueviolet)![17.0](https://img.shields.io/badge/-17.0-blue) | 11 | -------------------------------------------------------------------------------- /openai_chat/README.md: -------------------------------------------------------------------------------- 1 | [![License: AGPL-3](https://img.shields.io/badge/licence-AGPL--3-blue.png)](http://www.gnu.org/licenses/agpl-3.0-standalone.html) 2 | 3 | OpenAI Chat 4 | =================== 5 | 6 | [OpenAI Logo](https://openai.com/) 7 | 8 | This module adds an AI Bot user to chat with like in ChatGPT. 9 | 10 | ## Usage 11 | 12 | Open a chat and start talking to AI Bot: 13 | 14 | ![image](./static/img/open_chat.png) 15 | 16 | ![image](./static/img/chat.png) 17 | 18 | Or go is **Discuss**: 19 | 20 | ![image](./static/img/discuss.png) 21 | 22 | 23 | ### Clear the chat 24 | 25 | use the command **/clear** to clear the chat: 26 | 27 | ![image](./static/img/clear_chat.png) 28 | 29 | ### Boost AI Bot answer 30 | 31 | By default, AI Bot answer length is limited. To get longer answer, start your prompt with an exclamation mark, so AI Bor will use a maximum of tokens to answer. 32 | 33 | 34 | 35 | ![image](./static/img/truncated_answer.png) 36 | ![image](./static/img/longer_answer.png) 37 | 38 | 39 | 40 | ## Requirements 41 | 42 | **openai_connector** is required. 43 | 44 | This module requires the Python client library for OpenAI API 45 | 46 | pip install openai 47 | 48 | ## Maintainer 49 | 50 | * This module is maintained by [Michel Perrocheau](https://github.com/myrrkel). 51 | * Contact me on [LinkedIn](https://www.linkedin.com/in/michel-perrocheau-ba17a4122). 52 | 53 | [](https://github.com/myrrkel) 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /openai_chat/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/algpl.html). 4 | 5 | from . import models 6 | -------------------------------------------------------------------------------- /openai_chat/__manifest__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/algpl.html). 4 | { 5 | 'name': 'OpenAI Chat', 6 | 'version': '16.1.0.0', 7 | 'author': 'Michel Perrocheau', 8 | 'website': 'https://github.com/myrrkel', 9 | 'summary': "Add a AI Bot user to chat with like in ChatGPT", 10 | 'sequence': 0, 11 | 'certificate': '', 12 | 'license': 'AGPL-3', 13 | 'depends': [ 14 | 'openai_connector', 15 | 'mail', 16 | 'bus', 17 | ], 18 | 'category': 'Community', 19 | 'complexity': 'easy', 20 | 'qweb': [ 21 | ], 22 | 'demo': [ 23 | ], 24 | 'images': [ 25 | ], 26 | 'data': [ 27 | 'security/ir.model.access.csv', 28 | 'security/security.xml', 29 | 'data/openai_chat_data.xml', 30 | 'data/openai_completion_data.xml', 31 | ], 32 | 'assets': { 33 | 'mail.assets_messaging': [ 34 | 'openai_chat/static/src/models/messaging_initializer.js', 35 | ], 36 | }, 37 | 'auto_install': False, 38 | 'installable': True, 39 | 'application': False, 40 | } 41 | -------------------------------------------------------------------------------- /openai_chat/data/openai-odoo-avatar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/data/openai-odoo-avatar.png -------------------------------------------------------------------------------- /openai_chat/data/openai_chat_data.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AI Bot 6 | 7 | ai@example.com 8 | 9 | 10 | 11 | 12 | 13 | ai 14 | 15 | 16 | 17 | --
18 | AI]]>
19 | 20 |
21 |
22 |
-------------------------------------------------------------------------------- /openai_chat/data/openai_completion_data.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AI Chat 6 | 7 | [] 8 | gpt-3.5-turbo 9 | 3200 10 | 1 11 | 1 12 | 0.5 13 | 0 14 | 1 15 | The following is a conversation with an AI assistant. 16 | 17 | 18 | -------------------------------------------------------------------------------- /openai_chat/i18n/fr.po: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/i18n/fr.po -------------------------------------------------------------------------------- /openai_chat/models/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/algpl.html). 4 | 5 | from . import res_users 6 | from . import res_partner 7 | from . import mail_thread 8 | from . import mail_ai_bot 9 | from . import mail_channel 10 | -------------------------------------------------------------------------------- /openai_chat/models/mail_ai_bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, _ 6 | from odoo.tools import plaintext2html, html2plaintext 7 | from odoo.exceptions import UserError 8 | import logging 9 | import openai 10 | 11 | _logger = logging.getLogger(__name__) 12 | 13 | 14 | class MailBot(models.AbstractModel): 15 | _name = 'mail.ai.bot' 16 | _description = 'Mail AI Bot' 17 | 18 | def _answer_to_message(self, record, values): 19 | ai_bot_id = self.env['ir.model.data']._xmlid_to_res_id('openai_chat.partner_ai') 20 | if len(record) != 1 or values.get('author_id') == ai_bot_id or values.get('message_type') != 'comment': 21 | return 22 | if self._is_bot_in_private_channel(record): 23 | if values.get('body', '').startswith('!'): 24 | answer_type = 'important' 25 | else: 26 | answer_type = 'chat' 27 | 28 | try: 29 | answer = self._get_answer(record, answer_type) 30 | except openai.APIError as err: 31 | _logger.error(err) 32 | if 'maximum context length' in err.message: 33 | answer = _('ERROR - Sorry, this request requires too many tokens.' 34 | 'Please consider using the command "\\clean" to clear the AI chat.') 35 | pass 36 | else: 37 | raise UserError(err.message) 38 | 39 | if answer: 40 | message_type = 'comment' 41 | subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment') 42 | record = record.with_context(mail_create_nosubscribe=True).sudo() 43 | record.message_post(body=answer, author_id=ai_bot_id, message_type=message_type, subtype_id=subtype_id) 44 | 45 | def get_chat_messages(self, record, header, only_human=False): 46 | partner_ai_id = self.env.ref('openai_chat.partner_ai') 47 | previous_message_ids = record.message_ids.filtered(lambda m: m.body != '') 48 | if only_human: 49 | previous_message_ids = previous_message_ids.filtered(lambda m: m.author_id != partner_ai_id) 50 | 51 | chat_messages = [{'role': 'system', 'content': header}] if header else [] 52 | for message_id in previous_message_ids.sorted('date'): 53 | role = 'assistant' if message_id.author_id == partner_ai_id else 'user' 54 | chat_message = {'role': role, 55 | 'content': html2plaintext(message_id.body)} 56 | chat_messages.append(chat_message) 57 | return chat_messages 58 | 59 | def _get_answer(self, record, answer_type='chat'): 60 | completion_id = self.env.ref('openai_chat.completion_chat') 61 | header = completion_id.prompt_template 62 | 63 | if answer_type == 'chat': 64 | messages = self.get_chat_messages(record, header) 65 | res = completion_id.create_completion(messages=messages) 66 | elif answer_type == 'important': 67 | messages = self.get_chat_messages(record, header, only_human=True) 68 | res = completion_id.create_completion(messages, 69 | max_tokens=2048) 70 | else: 71 | return 72 | if res: 73 | return res[0] 74 | 75 | def _is_bot_in_private_channel(self, record): 76 | ai_bot_id = self.env['ir.model.data']._xmlid_to_res_id('openai_chat.partner_ai') 77 | if record._name == 'mail.channel' and record.channel_type == 'chat': 78 | return ai_bot_id in record.with_context(active_test=False).channel_partner_ids.ids 79 | return False 80 | -------------------------------------------------------------------------------- /openai_chat/models/mail_channel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, _ 6 | 7 | 8 | class MailChannel(models.Model): 9 | _inherit = 'mail.channel' 10 | 11 | def execute_command_clear_ai_chat(self, **kwargs): 12 | partner = self.env.user.partner_id 13 | key = kwargs['body'] 14 | if key.lower().strip() == '/clear': 15 | ai_bot_id = self.env['ir.model.data']._xmlid_to_res_id('openai_chat.partner_ai') 16 | ai_chat_member_ids = {ai_bot_id, partner.id} 17 | if ai_chat_member_ids == set(self.channel_member_ids.mapped('partner_id.id')): 18 | self.env['bus.bus']._sendone(self.env.user.partner_id, 'mail.message/delete', 19 | {'message_ids': self.message_ids.ids}) 20 | self.message_ids.unlink() 21 | -------------------------------------------------------------------------------- /openai_chat/models/mail_thread.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models 6 | 7 | 8 | class MailThread(models.AbstractModel): 9 | _inherit = 'mail.thread' 10 | 11 | def _message_post_after_hook(self, message, msg_vals): 12 | res = super(MailThread, self)._message_post_after_hook(message, msg_vals) 13 | self.env['mail.ai.bot']._answer_to_message(self, msg_vals) 14 | return res 15 | -------------------------------------------------------------------------------- /openai_chat/models/res_partner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | import logging 7 | 8 | _logger = logging.getLogger(__name__) 9 | 10 | 11 | class ResPartner(models.Model): 12 | _inherit = 'res.partner' 13 | 14 | def _compute_im_status(self): 15 | super(ResPartner, self)._compute_im_status() 16 | ai_bot_user_id = self.env['ir.model.data']._xmlid_to_res_id('openai_chat.partner_ai') 17 | for user in self.filtered(lambda u: u.id == ai_bot_user_id): 18 | user.im_status = 'online' 19 | -------------------------------------------------------------------------------- /openai_chat/models/res_users.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2023 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | import logging 7 | 8 | _logger = logging.getLogger(__name__) 9 | 10 | 11 | class ResUsers(models.Model): 12 | _inherit = 'res.users' 13 | 14 | def _init_messaging(self): 15 | if self._is_internal(): 16 | self._init_ai_bot() 17 | return super()._init_messaging() 18 | 19 | def _init_ai_bot(self): 20 | self.ensure_one() 21 | ai_bot_partner_id = self.env['ir.model.data']._xmlid_to_res_id('openai_chat.partner_ai') 22 | channel_info = self.env['mail.channel'].channel_get([ai_bot_partner_id, self.partner_id.id]) 23 | channel = self.env['mail.channel'].browse(channel_info['id']) 24 | return channel 25 | -------------------------------------------------------------------------------- /openai_chat/security/ir.model.access.csv: -------------------------------------------------------------------------------- 1 | "id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create","perm_unlink" 2 | -------------------------------------------------------------------------------- /openai_chat/security/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /openai_chat/static/description/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/description/icon.png -------------------------------------------------------------------------------- /openai_chat/static/description/index.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

OpenAI Chat

4 |

openai_chat

5 |
6 |

7 | This module adds an AI Bot user to chat with like in ChatGPT. 8 |

9 |
10 |
11 | 12 | 13 |
14 |
15 |
16 | 17 |
18 |
19 | Contact me 20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /openai_chat/static/description/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/description/logo.png -------------------------------------------------------------------------------- /openai_chat/static/img/chat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/chat.png -------------------------------------------------------------------------------- /openai_chat/static/img/clear_chat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/clear_chat.png -------------------------------------------------------------------------------- /openai_chat/static/img/discuss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/discuss.png -------------------------------------------------------------------------------- /openai_chat/static/img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/logo.png -------------------------------------------------------------------------------- /openai_chat/static/img/longer_answer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/longer_answer.png -------------------------------------------------------------------------------- /openai_chat/static/img/open_chat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/open_chat.png -------------------------------------------------------------------------------- /openai_chat/static/img/openai_logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /openai_chat/static/img/truncated_answer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_chat/static/img/truncated_answer.png -------------------------------------------------------------------------------- /openai_chat/static/src/models/messaging_initializer.js: -------------------------------------------------------------------------------- 1 | /** @odoo-module **/ 2 | 3 | import { registerPatch } from '@mail/model/model_core'; 4 | import { insert } from '@mail/model/model_field_command'; 5 | 6 | registerPatch({ 7 | name: 'MessagingInitializer', 8 | recordMethods: { 9 | /** 10 | * @override 11 | */ 12 | _initCommands() { 13 | this._super(); 14 | this.messaging.update({ 15 | commands: insert({ 16 | help: this.env._t("Clear chat with AI Bot"), 17 | methodName: 'execute_command_clear_ai_chat', 18 | name: "clear", 19 | }), 20 | }); 21 | }, 22 | }, 23 | }); 24 | -------------------------------------------------------------------------------- /openai_connector/README.md: -------------------------------------------------------------------------------- 1 | [![License: AGPL-3](https://img.shields.io/badge/licence-AGPL--3-blue.png)](http://www.gnu.org/licenses/agpl-3.0-standalone.html) 2 | 3 | OpenAI Connector 4 | ================= 5 | 6 | [OpenAI Logo](https://openai.com/) 7 | 8 | 9 | This technical module provides a connector for the OpenAI API and allows integration of ChatGPT and DALL-E capabilities within Odoo. 10 | ChatGPT4 and DALL·E 3 are available. 11 | 12 | It can be used as a playground to test OpenAI tools in Odoo but does not have standalone functionality. 13 | The module is intended to be inherited by other modules for specific use cases, such as: 14 | - [openai_chat](../openai_chat/README.md): Adding an AI bot user for interactive chat using ChatGPT 15 | - [openai_edit_product_image](../openai_edit_product_image/README.md): Generating a new product image from a cropped image using DALL-E 16 | - [openai_product_description](../openai_product_description/README.md): Generating sales descriptions for products using ChatGPT 17 | - [openai_product_tags](../openai_product_tags/README.md): Generating product tags using ChatGPT 18 | 19 | To create custom OpenAI completions, edits, or images, refer to the API documentation for proper configuration of API parameters. 20 | 21 | [OpenAI API Documentation](https://beta.openai.com/docs/api-reference/introduction) 22 | 23 | ## Configuration 24 | 25 | Create an account on [https://beta.openai.com/](https://beta.openai.com/) 26 | 27 | Generate your API key: [API keys](https://beta.openai.com/account/api-keys) 28 | 29 | In **Settings**, fill the **API Key** field with your generated key. 30 | 31 | ![image](./static/img/settings.png) 32 | 33 | ## Usage 34 | 35 | ### OpenAI Completion 36 | 37 | To create a new **OpenAI Completion**, go to **Settings**, **Technical**, **OpenAI Completion** and create a new record. 38 | 39 | ![image](./static/img/completion_params.png) 40 | 41 | **Model**: The model on witch the completion will be applied. 42 | 43 | **Target Field**: The field where the generated value will be saved. 44 | 45 | **Domain**: The domain to select the records on witch the completion will be run. 46 | 47 | 48 | ![image](./static/img/openai_params.png) 49 | 50 | Check the [API Documentation](https://beta.openai.com/docs/api-reference/introduction) to set **OpenAI Parameters** values. 51 | 52 | For Completion results go to **Settings**, **Technical**, **OpenAI Completion Results** 53 | 54 | ### OpenAI Image 55 | 56 | To create a new **OpenAI Image**, go to **Settings**, **Technical**, **OpenAI Image** and create a new record. 57 | 58 | For results go to **Settings**, **Technical**, **OpenAI Image Results** 59 | 60 | ### Prompt template 61 | 62 | Write a prompt template in Qweb. 63 | 64 | Available functions in prompt template: 65 | - object : Current record 66 | - answer_lang : Function returning the language name 67 | - html2plaintext : Function to convert html to text 68 | 69 | ![image](./static/img/prompt.png) 70 | 71 | ### Tests 72 | 73 | Test actions use the first record of the model selected by the domain. 74 | 75 | Test first your prompt to adjust your template, then test the result of the Completion, Edit or Image to adjust OpenAI parameters. 76 | 77 | ![image](./static/img/tests.png) 78 | 79 | ## Requirements 80 | 81 | This module requires the Python client library for OpenAI API 82 | 83 | pip install openai>=1.6.1 84 | 85 | ## Maintainer 86 | 87 | * This module is maintained by [Michel Perrocheau](https://github.com/myrrkel). 88 | * Contact me on [LinkedIn](https://www.linkedin.com/in/michel-perrocheau-ba17a4122). 89 | 90 | [](https://github.com/myrrkel) 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /openai_connector/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from . import models 6 | -------------------------------------------------------------------------------- /openai_connector/__manifest__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | { 5 | 'name': 'OpenAI Connector', 6 | 'version': '16.2.0.0', 7 | 'author': 'Michel Perrocheau', 8 | 'website': 'https://github.com/myrrkel', 9 | 'summary': "Connector for OpenAI API", 10 | 'sequence': 0, 11 | 'certificate': '', 12 | 'license': 'AGPL-3', 13 | 'depends': [ 14 | 'base', 15 | 'mail', 16 | ], 17 | 'external_dependencies': { 18 | 'python': ['openai'], 19 | }, 20 | 'category': 'OpenAI', 21 | 'complexity': 'easy', 22 | 'qweb': [ 23 | ], 24 | 'demo': [ 25 | ], 26 | 'images': [ 27 | ], 28 | 'data': [ 29 | 'security/ir.model.access.csv', 30 | 'security/security.xml', 31 | 'views/res_config_settings_views.xml', 32 | 'views/openai_completion_views.xml', 33 | 'views/openai_completion_result_views.xml', 34 | 'views/openai_image_views.xml', 35 | 'views/openai_image_result_views.xml', 36 | 'views/openai_question_answer_views.xml', 37 | 'views/openai_fine_tuning_views.xml', 38 | ], 39 | 'assets': { 40 | 'web.assets_backend': [ 41 | 'openai_connector/static/src/scss/style.scss', 42 | ], 43 | }, 44 | 45 | 'auto_install': False, 46 | 'installable': True, 47 | 'application': False, 48 | } 49 | -------------------------------------------------------------------------------- /openai_connector/i18n/fr.po: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/i18n/fr.po -------------------------------------------------------------------------------- /openai_connector/models/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from . import res_config_settings 6 | from . import openai_mixin 7 | from . import openai_result_mixin 8 | from . import openai_completion 9 | from . import openai_completion_result 10 | from . import openai_image 11 | from . import openai_image_result 12 | from . import openai_question_answer 13 | from . import openai_fine_tuning 14 | from . import openai_tool 15 | from . import openai_tool_property 16 | -------------------------------------------------------------------------------- /openai_connector/models/openai_completion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | import json 5 | 6 | from odoo import models, fields, api, _ 7 | 8 | import logging 9 | 10 | _logger = logging.getLogger(__name__) 11 | 12 | 13 | class OpenAiCompletion(models.Model): 14 | _name = 'openai.completion' 15 | _description = 'OpenAI Completion' 16 | _inherit = ['openai.mixin'] 17 | 18 | def _get_openai_model_list(self): 19 | try: 20 | openai = self.get_openai() 21 | except Exception as err: 22 | return [('gpt-3.5-turbo', 'gpt-3.5-turbo')] 23 | model_list = openai.models.list() 24 | res = [(m.id, m.id) for m in model_list.data] 25 | res.sort() 26 | return res 27 | 28 | def _get_post_process_list(self): 29 | return [('list_to_many2many', _('List to Many2many')), 30 | ('json_to_questions', _('JSON to questions'))] 31 | 32 | def _get_response_format_list(self): 33 | return [('text', _('Text')), 34 | ('json_object', _('JSON Object')), 35 | ] 36 | 37 | ai_model = fields.Selection(selection='_get_openai_model_list', string='AI Model') 38 | fine_tuning_id = fields.Many2one('openai.fine.tuning', string='Fine-Tuning') 39 | temperature = fields.Float(default=1) 40 | max_tokens = fields.Integer(default=3000) 41 | top_p = fields.Float(default=1) 42 | frequency_penalty = fields.Float() 43 | presence_penalty = fields.Float() 44 | stop = fields.Char() 45 | test_answer = fields.Text(readonly=True) 46 | post_process = fields.Selection(selection='_get_post_process_list') 47 | response_format = fields.Selection(selection='_get_response_format_list', default='text') 48 | tool_ids = fields.Many2many('openai.tool', string='Tools', copy=True) 49 | 50 | def create_completion(self, rec_id=0, messages=None, prompt='', **kwargs): 51 | openai = self.get_openai() 52 | if not messages: 53 | if not prompt: 54 | prompt = self.get_prompt(rec_id) 55 | messages = [{'role': 'user', 'content': prompt}] 56 | 57 | max_tokens = kwargs.get('max_tokens', self.max_tokens) 58 | stop = kwargs.get('stop', self.stop or '') 59 | if isinstance(stop, str) and ',' in stop: 60 | stop = stop.split(',') 61 | response_format = {'type': kwargs.get('response_format', self.response_format) or 'text'} 62 | model = self.ai_model or self.fine_tuning_id.fine_tuned_model or kwargs.get('model', 'gpt-3.5-turbo') 63 | temperature = self.temperature or kwargs.get('temperature', 0) 64 | top_p = self.top_p or kwargs.get('top_p', 0) 65 | max_tokens = kwargs.get('max_tokens', self.max_tokens or 3000) 66 | tools = [t.get_tool_dict() for t in self.tool_ids] if self.tool_ids else None 67 | _logger.info(f'Create completion: {messages}') 68 | res = openai.chat.completions.create( 69 | model=model, 70 | messages=messages, 71 | max_tokens=max_tokens, 72 | n=self.n or 1, 73 | temperature=temperature, 74 | top_p=top_p, 75 | frequency_penalty=self.frequency_penalty, 76 | presence_penalty=self.presence_penalty, 77 | stop=stop, 78 | response_format=response_format, 79 | tools=tools, 80 | tool_choice='auto' if tools else None, 81 | ) 82 | prompt_tokens = res.usage.prompt_tokens 83 | completion_tokens = res.usage.completion_tokens 84 | total_tokens = res.usage.total_tokens 85 | 86 | result_ids = [] 87 | for choice in res.choices: 88 | if choice.finish_reason == 'tool_calls': 89 | for tool_call in choice.message.tool_calls: 90 | messages.append(choice.message) 91 | messages.append(self.run_tool_call(tool_call)) 92 | return self.create_completion(rec_id, messages, prompt, **kwargs) 93 | _logger.info(f'Completion result: {choice.message.content}') 94 | if rec_id: 95 | answer = choice.message.content 96 | result_id = self.create_result(rec_id, prompt, answer, prompt_tokens, completion_tokens, total_tokens) 97 | if self.post_process and not self.target_field_id: 98 | result_id.exec_post_process(answer) 99 | result_ids.append(result_id) 100 | else: 101 | try: 102 | return self.get_result_content(res) 103 | except Exception as err: 104 | _logger.error(err, exc_info=True) 105 | return result_ids 106 | 107 | def get_result_content(self, res): 108 | def _extract_json(content): 109 | start_pos = content.find('{') 110 | end_post = content.rfind('}') + 1 111 | return content[start_pos:end_post] 112 | 113 | if self.response_format == 'json_object': 114 | return [_extract_json(choice.message.content) for choice in res.choices] 115 | return [choice.message.content for choice in res.choices] 116 | 117 | 118 | def run_tool_call(self, tool_call): 119 | tool_name = tool_call.function.name 120 | res_dict = {'role': 'tool', 121 | "tool_call_id": tool_call.id, 122 | 'content': '', 123 | 'name': tool_name} 124 | tool_id = self.tool_ids.filtered(lambda t: t.name == tool_name) 125 | if not tool_id: 126 | return res_dict 127 | model_name = tool_id.model or self.model_id.model 128 | model = self.env[model_name] 129 | 130 | if hasattr(model, tool_name): 131 | function = getattr(model, tool_name) 132 | else: 133 | model = self.env['openai.tool'] 134 | if hasattr(model, tool_name): 135 | function = getattr(model, tool_name) 136 | else: 137 | return res_dict 138 | 139 | arguments = tool_call.function.arguments 140 | if arguments: 141 | arguments_vals = json.loads(arguments) 142 | _logger.info(f'Run tool: {tool_name}({arguments_vals})') 143 | res = function(**arguments_vals) 144 | else: 145 | res = function() 146 | _logger.info(f'Run tool: {tool_name}()') 147 | 148 | res_dict['content'] = str(res) 149 | return res_dict 150 | 151 | def openai_create(self, rec_id, method=False): 152 | return self.create_completion(rec_id) 153 | 154 | def create_result(self, rec_id, prompt, answer, prompt_tokens, completion_tokens, total_tokens): 155 | values = {'completion_id': self.id, 156 | 'model_id': self.model_id.id, 157 | 'target_field_id': self.target_field_id.id, 158 | 'res_id': rec_id, 159 | 'prompt': prompt, 160 | 'answer': answer, 161 | 'prompt_tokens': prompt_tokens, 162 | 'completion_tokens': completion_tokens, 163 | 'total_tokens': total_tokens, 164 | } 165 | result_id = self.env['openai.completion.result'].create(values) 166 | return result_id 167 | 168 | def run_test_completion(self): 169 | rec_id = self.get_records(limit=1).id 170 | if not rec_id: 171 | return 172 | self.test_prompt = self.get_prompt(rec_id) 173 | result_ids = self.create_completion(rec_id) 174 | self.test_answer = result_ids[0].answer 175 | -------------------------------------------------------------------------------- /openai_connector/models/openai_completion_result.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | import ast 7 | import logging 8 | import re 9 | 10 | _logger = logging.getLogger(__name__) 11 | 12 | 13 | def clean_list_element(el): 14 | if '.' in el: 15 | el = el.split('.')[1] 16 | if '-' in el: 17 | el = el.split('-')[1] 18 | el = re.sub(r'[^\w\s,-]', '', el.strip()) 19 | return el 20 | 21 | 22 | class OpenAiCompletionResult(models.Model): 23 | _name = 'openai.completion.result' 24 | _description = 'OpenAI Completion Result' 25 | _inherit = ['openai.result.mixin'] 26 | 27 | completion_id = fields.Many2one('openai.completion', string='Completion', readonly=True, ondelete='cascade') 28 | answer = fields.Text(readonly=False) 29 | origin_answer = fields.Text(readonly=True) 30 | prompt_tokens = fields.Integer(readonly=True) 31 | completion_tokens = fields.Integer(readonly=True) 32 | total_tokens = fields.Integer(readonly=True) 33 | 34 | def _compute_name(self): 35 | for rec in self: 36 | if hasattr(rec.resource_ref, 'name'): 37 | rec.name = f'{rec.completion_id.name} - {rec.resource_ref.name}' 38 | elif hasattr(rec.resource_ref, 'display_name'): 39 | rec.name = f'{rec.completion_id.name} - {rec.resource_ref.display_name}' 40 | else: 41 | rec.name = f'{rec.completion_id.name} - {rec.model_id.name} ({rec.res_id})' 42 | 43 | def write(self, vals): 44 | if self.answer and vals.get('answer') and not self.origin_answer: 45 | vals['origin_answer'] = self.answer 46 | return super(OpenAiCompletionResult, self).write(vals) 47 | 48 | def exec_post_process(self, value): 49 | if not self.completion_id.post_process: 50 | return value 51 | post_process_function = getattr(self, self.completion_id.post_process) 52 | return post_process_function(value) 53 | 54 | def get_answer_value(self): 55 | return self.exec_post_process(self.answer) 56 | 57 | def json_to_questions(self, val): 58 | values = ast.literal_eval(val) 59 | questions = values.get('questions', []) 60 | for question in questions: 61 | create_vals = {'name': question, 62 | 'model_id': self.model_id.id, 63 | 'res_id': self.res_id, 64 | } 65 | self.env['openai.question.answer'].create(create_vals) 66 | 67 | def list_to_many2many(self, val): 68 | """ 69 | :param val: a string representing a python list or a comma separated list 70 | e.g: "test = ['val1', 'val2']" or " val1, val2, " 71 | :return: a many2many update list. 72 | e.g: [(5, 0, 0), (0, 0, {'name': 'new tag'})] 73 | """ 74 | 75 | res = [(5, 0, 0)] 76 | if '=' in val: 77 | val = val.split('=')[1] 78 | val = val.strip() 79 | if val[0] == '[': 80 | # Eval Python list string 81 | val_list = ast.literal_eval(val) 82 | else: 83 | # Split the string 84 | if '\n' in val: 85 | separator = '\n' 86 | else: 87 | separator = ',' 88 | val_list = val.split(separator) 89 | 90 | val_list = [clean_list_element(el) for el in val_list] 91 | if not val_list: 92 | return False 93 | 94 | # Create many2many update list 95 | target_model = self.target_field_id.relation 96 | for el in val_list: 97 | if not el: 98 | continue 99 | rec_el = self.env[target_model].search([('name', '=', el)]) 100 | if not rec_el: 101 | res.append((0, 0, {'name': el})) 102 | else: 103 | res.append((4, rec_el.id)) 104 | return res 105 | -------------------------------------------------------------------------------- /openai_connector/models/openai_fine_tuning.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2024 - Michel Perrocheau (https://github.com/myrrkel). 2 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 3 | 4 | import json 5 | from tempfile import NamedTemporaryFile 6 | from odoo import models, fields, api, _ 7 | from odoo.tools.safe_eval import safe_eval 8 | from odoo.addons.base.models.ir_model import SAFE_EVAL_BASE 9 | 10 | import logging 11 | 12 | _logger = logging.getLogger(__name__) 13 | 14 | 15 | class OpenAiFineTuning(models.Model): 16 | _name = 'openai.fine.tuning' 17 | _description = 'OpenAI Fine-Tuning' 18 | 19 | def _get_training_model_list(self): 20 | return [('gpt-3.5-turbo', 'gpt-3.5-turbo'), 21 | ('gpt-3.5-turbo-1106', 'gpt-3.5-turbo-1106'), 22 | ('gpt-3.5-turbo-0613', 'gpt-3.5-turbo-0613'), 23 | ('gpt-4-0613', 'gpt-4-0613'), 24 | ('babbage-002', 'babbage-002'), 25 | ('davinci-002', 'davinci-002')] 26 | 27 | name = fields.Char() 28 | training_model = fields.Selection(selection=_get_training_model_list, default='gpt-3.5-turbo') 29 | training_file_id = fields.Char('Training File ID') 30 | fine_tuning_job_id = fields.Char('Fine-Tuning Job ID') 31 | fine_tuned_model = fields.Char('Fine-Tuned Model') 32 | question_answer_domain = fields.Char() 33 | question_answer_ids = fields.Many2many('openai.question.answer', string='Questions /Answers', 34 | compute='_compute_question_answers', 35 | store=False) 36 | system_role_content = fields.Char() 37 | 38 | def _compute_question_answers(self): 39 | for rec in self: 40 | domain = safe_eval(rec.question_answer_domain, 41 | SAFE_EVAL_BASE, 42 | {'self': rec}) if rec.question_answer_domain else [] 43 | rec.question_answer_ids = self.env['openai.question.answer'].search(domain) 44 | 45 | def get_training_content(self): 46 | content = '' 47 | for question_answer_id in self.question_answer_ids: 48 | messages = { 49 | 'messages': [ 50 | {'role': 'system', 'content': self.system_role_content}, 51 | {'role': 'user', 'content': question_answer_id.name}, 52 | {'role': 'assistant', 'content': question_answer_id.answer} 53 | ] 54 | } 55 | content += json.dumps(messages) + '\n' 56 | return bytes(content, 'utf-8') 57 | 58 | def create_training_file(self): 59 | client = self.env['openai.mixin'].get_openai() 60 | file = ('training_%s' % self.id, self.get_training_content()) 61 | res = client.files.create(file=file, purpose='fine-tune') 62 | self.training_file_id = res.id 63 | 64 | def create_fine_tuning(self): 65 | client = self.env['openai.mixin'].get_openai() 66 | res = client.fine_tuning.jobs.create(training_file=self.training_file_id, model=self.training_model) 67 | self.fine_tuning_job_id = res.id 68 | _logger.info(res) 69 | 70 | def update_fine_tuned_model(self): 71 | client = self.env['openai.mixin'].get_openai() 72 | res = client.fine_tuning.jobs.retrieve(self.fine_tuning_job_id) 73 | self.fine_tuned_model = res.fine_tuned_model 74 | _logger.info(res) 75 | 76 | def action_create_training_file(self): 77 | for rec in self: 78 | rec.create_training_file() 79 | 80 | def action_create_fine_tuning(self): 81 | for rec in self: 82 | rec.create_fine_tuning() 83 | 84 | def action_update_fine_tuned_model(self): 85 | for rec in self: 86 | rec.update_fine_tuned_model() 87 | -------------------------------------------------------------------------------- /openai_connector/models/openai_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | from odoo.exceptions import UserError 7 | import base64 8 | import logging 9 | import requests 10 | import openai 11 | import io 12 | from PIL import Image 13 | 14 | _logger = logging.getLogger(__name__) 15 | 16 | 17 | def resize_image(image, size, origin_x, origin_y): 18 | res_image = Image.new('RGBA', (size, size), (255, 255, 255, 0)) 19 | res_image.paste(image, (int((size - origin_x) / 2), int((size - origin_y) / 2))) 20 | return res_image 21 | 22 | 23 | def square_image(binary_image, ratio=1): 24 | res_image = Image.open(io.BytesIO(base64.b64decode(binary_image))) 25 | x, y = res_image.size 26 | size = max(x, y) 27 | res_image = resize_image(res_image, size, x, y) 28 | 29 | if ratio not in [0, 1]: 30 | zoom_size = int(size * 1 / ratio) 31 | res_image = resize_image(res_image, zoom_size, size, size) 32 | 33 | img_byte_arr = io.BytesIO() 34 | res_image.save(img_byte_arr, format='PNG') 35 | return img_byte_arr.getvalue() 36 | 37 | 38 | class OpenAiImage(models.Model): 39 | _name = 'openai.image' 40 | _description = 'OpenAI Image' 41 | _inherit = ['openai.mixin'] 42 | 43 | def _get_openai_image_size_list(self): 44 | size_list = ['256x256', '512x512', '1024x1024'] 45 | res = [(m, m) for m in size_list] 46 | return res 47 | 48 | def _get_openai_image_size_dalle3_list(self): 49 | size_list = ['1024x1024', '1024x1792', '1792x1024'] 50 | res = [(m, m) for m in size_list] 51 | return res 52 | 53 | def _get_openai_image_method_list(self): 54 | return [ 55 | ('create', _('Create')), 56 | ('create_edit', _('Edit')), 57 | ('create_variation', _('Variation')), 58 | ] 59 | 60 | def _get_openai_image_model(self): 61 | return [ 62 | ('dall-e-2', _('DALL·E 2')), 63 | ('dall-e-3', _('DALL·E 3')), 64 | ] 65 | 66 | method = fields.Selection(selection='_get_openai_image_method_list') 67 | ai_model = fields.Selection(selection='_get_openai_image_model', string='AI Model') 68 | size = fields.Selection(selection='_get_openai_image_size_list', default='1024x1024') 69 | size_dalle3 = fields.Selection(string='Size DALL·E 3', selection='_get_openai_image_size_dalle3_list', 70 | default='1024x1024') 71 | source_image_field_id = fields.Many2one('ir.model.fields', string='Source Image Field') 72 | mask_image_field_id = fields.Many2one('ir.model.fields', string='Mask Image Field') 73 | resize_ratio_field_id = fields.Many2one('ir.model.fields', string='Resize Ratio Field') 74 | test_answer = fields.Image(readonly=True) 75 | test_source_image = fields.Image() 76 | test_mask_image = fields.Image() 77 | test_resize_ratio = fields.Float(default=1) 78 | 79 | def create_image(self, rec_id, method=False): 80 | prompt = self.get_prompt(rec_id) 81 | try: 82 | res = self.run_image_method(prompt, rec_id, method) 83 | except openai.APIError as err: 84 | raise UserError(err.message) 85 | 86 | if isinstance(res, bytes): 87 | return self.create_result(rec_id, prompt, res) 88 | result_ids = [] 89 | for data in res.data: 90 | if data.b64_json: 91 | result_id = self.create_result(rec_id, prompt, data.b64_json, method=method) 92 | else: 93 | result_id = self.create_result_from_url(rec_id, prompt, data.url) 94 | result_ids.append(result_id) 95 | return result_ids 96 | 97 | def get_source_image(self, rec_id, resize=False): 98 | record_id = self.get_record(rec_id) 99 | if self.env.context.get('openai_test') and self.test_source_image: 100 | return square_image(self.test_source_image, self.test_resize_ratio or 1) 101 | 102 | image_field = self.source_image_field_id.name or self.target_field_id.name 103 | if not image_field: 104 | return 105 | image = record_id[image_field] 106 | if not image and self.source_image_field_id.name: 107 | image = record_id[self.target_field_id.name] 108 | if image: 109 | return square_image(image, self.get_image_ratio(rec_id) if resize else 1) 110 | 111 | def get_mask_image(self, rec_id): 112 | record_id = self.get_record(rec_id) 113 | if self.env.context.get('openai_test') and self.test_mask_image: 114 | return square_image(self.test_mask_image, self.test_resize_ratio or 1) 115 | 116 | if self.mask_image_field_id: 117 | mask = record_id[self.mask_image_field_id.name] 118 | if mask: 119 | return square_image(mask, self.get_image_ratio(rec_id)) 120 | return None 121 | 122 | def get_image_ratio(self, rec_id): 123 | record_id = self.get_record(rec_id) 124 | if self.resize_ratio_field_id: 125 | return record_id[self.resize_ratio_field_id.name] or 1 126 | return 1 127 | 128 | def run_image_method(self, prompt, rec_id=False, method=False): 129 | openai_cli = self.get_openai() 130 | method = method or self.method 131 | if self.env.context.get('openai_test'): 132 | number_of_result = 1 133 | else: 134 | number_of_result = self.n or 1 135 | 136 | if method == 'create': 137 | params = { 138 | 'prompt': prompt, 139 | 'n': number_of_result, 140 | 'size': self.size_dalle3 if self.ai_model == 'dall-e-3' else self.size, 141 | 'response_format': 'b64_json' 142 | } 143 | if self.ai_model: 144 | params['model'] = self.ai_model 145 | return openai_cli.images.generate(**params) 146 | if method == 'create_edit': 147 | image = self.get_source_image(rec_id, resize=True) 148 | if not image: 149 | raise UserError('Source image is required for image edition.') 150 | mask = self.get_mask_image(rec_id) 151 | params = { 152 | 'prompt': prompt, 153 | 'image': image, 154 | 'n': number_of_result, 155 | 'size': self.size, 156 | 'response_format': 'b64_json' 157 | } 158 | if mask: 159 | params['mask'] = mask 160 | 161 | return openai_cli.images.edit(**params) 162 | if method == 'create_variation': 163 | image = self.get_source_image(rec_id) 164 | if not image: 165 | raise UserError('Source image is required to crete image variation.') 166 | return openai_cli.images.create_variation(image=image, 167 | n=number_of_result, 168 | size=self.size, 169 | response_format='b64_json') 170 | 171 | def openai_create(self, rec_id, method=False): 172 | return self.create_image(rec_id, method=method) or [] 173 | 174 | def create_result_from_url(self, rec_id, prompt, image_url): 175 | return self.create_result(rec_id, prompt, base64.b64encode(requests.get(image_url).content)) 176 | 177 | def create_result(self, rec_id, prompt, answer, method=False): 178 | values = {'image_id': self.id, 179 | 'model_id': self.model_id.id, 180 | 'target_field_id': self.target_field_id.id, 181 | 'res_id': rec_id, 182 | 'prompt': prompt, 183 | 'answer': answer, 184 | 'method': method, 185 | 'test_result': self.env.context.get('openai_test', False), 186 | } 187 | result_id = self.env['openai.image.result'].create(values) 188 | return result_id 189 | 190 | def run_test_image(self): 191 | rec_id = self.get_records(limit=1).id 192 | if not rec_id: 193 | return 194 | self.test_prompt = self.get_prompt(rec_id) 195 | result_ids = self.with_context(openai_test=True).create_image(rec_id) 196 | if result_ids: 197 | self.test_answer = result_ids[0].answer 198 | return {'type': 'ir.actions.client', 'tag': 'reload'} 199 | 200 | def result_to_source_image(self): 201 | self.test_source_image = self.test_answer 202 | -------------------------------------------------------------------------------- /openai_connector/models/openai_image_result.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | import logging 7 | 8 | _logger = logging.getLogger(__name__) 9 | 10 | 11 | class OpenAiImageResult(models.Model): 12 | _name = 'openai.image.result' 13 | _description = 'OpenAI Image Result' 14 | _inherit = ['openai.result.mixin'] 15 | 16 | image_id = fields.Many2one('openai.image', string='OpenAI Action', readonly=True, ondelete='cascade') 17 | original_image = fields.Image(compute='_compute_original_image') 18 | method = fields.Char() 19 | answer = fields.Image(readonly=False) 20 | 21 | def _compute_name(self): 22 | for rec in self: 23 | if hasattr(rec.resource_ref, 'name'): 24 | name = f'{rec.image_id.name} - {rec.resource_ref.name}' 25 | elif hasattr(rec.resource_ref, 'display_name'): 26 | name = f'{rec.image_id.name} - {rec.resource_ref.display_name}' 27 | else: 28 | name = f'{rec.image_id.name} - {rec.model_id.name} ({self.res_id})' 29 | if rec.test_result: 30 | name = '%s (%s)' % (name, _('TEST')) 31 | rec.name = name 32 | 33 | def _compute_original_image(self): 34 | for rec in self: 35 | try: 36 | record_id = self.env[rec.model_id.model].browse(rec.res_id) 37 | if rec.image_id.source_image_field_id: 38 | res = record_id[rec.image_id.source_image_field_id.name] 39 | if res: 40 | rec.original_image = res 41 | continue 42 | rec.original_image = None 43 | except Exception as err: 44 | _logger.error(err) 45 | pass 46 | -------------------------------------------------------------------------------- /openai_connector/models/openai_mixin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | from odoo.exceptions import UserError 7 | from odoo.tools.safe_eval import safe_eval 8 | from odoo.addons.base.models.ir_model import SAFE_EVAL_BASE 9 | from odoo.tools import html2plaintext 10 | import logging 11 | from openai import OpenAI 12 | 13 | _logger = logging.getLogger(__name__) 14 | 15 | 16 | class OpenAiMixin(models.AbstractModel): 17 | _name = 'openai.mixin' 18 | _description = 'OpenAI Mixin' 19 | _inherit = ['mail.render.mixin'] 20 | 21 | name = fields.Char() 22 | active = fields.Boolean(default=True) 23 | model_id = fields.Many2one('ir.model', string='Model', required=True, ondelete='cascade') 24 | domain = fields.Char() 25 | save_on_target_field = fields.Boolean() 26 | target_field_id = fields.Many2one('ir.model.fields', string='Target Field') 27 | prompt_template = fields.Text() 28 | prompt_template_id = fields.Many2one('ir.ui.view', string='Prompt Template View') 29 | n = fields.Integer(default=1) 30 | answer_lang_id = fields.Many2one('res.lang', string='Answer Language', context={'active_test': False}) 31 | test_prompt = fields.Text(readonly=True) 32 | 33 | @api.model 34 | def get_openai(self): 35 | api_key = self.env['ir.config_parameter'].sudo().get_param('openai_api_key') 36 | if not api_key: 37 | raise UserError(_('OpenAI API key is required.')) 38 | client = OpenAI(api_key=api_key) 39 | return client 40 | 41 | def get_prompt(self, rec_id=0): 42 | context = {'html2plaintext': html2plaintext} 43 | lang = self.env.lang 44 | answer_lang_id = self.answer_lang_id or self.env['res.lang']._lang_get(lang) 45 | if answer_lang_id: 46 | context['answer_lang'] = answer_lang_id.name 47 | if self.prompt_template_id: 48 | prompt = self._render_template_qweb_view(self.prompt_template_id.xml_id, self.model_id.model, [rec_id], 49 | add_context=context) 50 | elif self.prompt_template: 51 | prompt = self._render_template_qweb(self.prompt_template, self.model_id.model, [rec_id], 52 | add_context=context) 53 | else: 54 | raise UserError(_('A prompt template is required')) 55 | 56 | return prompt[rec_id].strip() 57 | 58 | def get_records(self, limit=0): 59 | domain = safe_eval(self.domain, SAFE_EVAL_BASE, {'self': self}) if self.domain else [] 60 | rec_ids = self.env[self.model_id.model].search(domain, limit=limit) 61 | return rec_ids 62 | 63 | def get_record(self, rec_id): 64 | record_id = self.env[self.model_id.model].browse(rec_id) 65 | return record_id 66 | 67 | def run(self): 68 | for rec_id in self.get_records(): 69 | self.apply(rec_id.id) 70 | 71 | def apply(self, rec_id, method=False): 72 | result_ids = self.openai_create(rec_id, method) 73 | for result_id in result_ids: 74 | if self.save_on_target_field: 75 | result_id.save_result_on_target_field() 76 | 77 | def openai_create(self, rec_id, method=False): 78 | return False 79 | 80 | def run_test_prompt(self): 81 | rec_id = self.get_records(limit=1).id 82 | if not rec_id: 83 | return 84 | self.test_prompt = self.get_prompt(rec_id) 85 | -------------------------------------------------------------------------------- /openai_connector/models/openai_question_answer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2024 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | 7 | import logging 8 | 9 | _logger = logging.getLogger(__name__) 10 | 11 | 12 | class OpenAiQuestionAnswer(models.Model): 13 | _name = 'openai.question.answer' 14 | _description = 'OpenAI Question Answer' 15 | 16 | name = fields.Text('Question') 17 | answer = fields.Text('Answer') 18 | model_id = fields.Many2one('ir.model', string='Model', ondelete='cascade') 19 | model = fields.Char(related='model_id.model', string='Model Name', readonly=True, store=True) 20 | res_id = fields.Integer('Resource ID', readonly=True) 21 | resource_ref = fields.Reference(string='Record', selection='_selection_target_model', 22 | compute='_compute_resource_ref', inverse='_set_resource_ref') 23 | answer_completion_id = fields.Many2one('openai.completion', string='Answer Completion') 24 | content_length = fields.Integer(compute='_compute_content_length') 25 | 26 | @api.model 27 | def _selection_target_model(self): 28 | model_ids = self.env['ir.model'].search([]) 29 | return [(model.model, model.name) for model in model_ids] 30 | 31 | def _compute_content_length(self): 32 | for res in self: 33 | res.content_length = len(res.name) + len(res.answer) 34 | 35 | @api.depends('res_id') 36 | def _compute_resource_ref(self): 37 | for rec in self: 38 | if rec.model_id and rec.res_id: 39 | record = self.env[rec.model_id.model].browse(rec.res_id) 40 | res_id = record[0] if record else 0 41 | rec.resource_ref = '%s,%s' % (rec.model_id.model, res_id.id) 42 | else: 43 | rec.resource_ref = False 44 | 45 | @api.onchange('resource_ref') 46 | def _set_resource_ref(self): 47 | for rec in self: 48 | if rec.resource_ref: 49 | rec.model_id = self.env['ir.model']._get(rec.resource_ref._name) 50 | rec.res_id = rec.resource_ref.id 51 | 52 | def action_answer_question(self): 53 | for rec in self: 54 | res = rec.answer_completion_id.create_completion(rec.id) 55 | rec.answer = res[0].answer 56 | 57 | def get_score(self, keyword_list): 58 | score = 0 59 | for keyword in keyword_list: 60 | keyword = keyword.lower() 61 | if keyword in self.name.lower(): 62 | score += 2 63 | if keyword in self.answer.lower(): 64 | score += 1 65 | return score 66 | -------------------------------------------------------------------------------- /openai_connector/models/openai_result_mixin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import models, fields, api, _ 6 | import logging 7 | 8 | _logger = logging.getLogger(__name__) 9 | 10 | 11 | class OpenAiResultMixin(models.AbstractModel): 12 | _name = 'openai.result.mixin' 13 | _description = 'OpenAI result Mixin' 14 | 15 | name = fields.Char(compute='_compute_name') 16 | model_id = fields.Many2one('ir.model', string='Model', readonly=True, ondelete='cascade') 17 | model = fields.Char(related='model_id.model', string='Model Name', readonly=True, store=True) 18 | target_field_id = fields.Many2one('ir.model.fields', string='Target Field', readonly=True) 19 | res_id = fields.Integer('Resource ID', readonly=True) 20 | resource_ref = fields.Reference(string='Record', selection='_selection_target_model', 21 | compute='_compute_resource_ref', inverse='_set_resource_ref', readonly=True) 22 | prompt = fields.Text(readonly=True) 23 | test_result = fields.Boolean() 24 | 25 | @api.model 26 | def _selection_target_model(self): 27 | model_ids = self.env['ir.model'].search([]) 28 | return [(model.model, model.name) for model in model_ids] 29 | 30 | @api.depends('model_id', 'res_id') 31 | def _compute_resource_ref(self): 32 | for rec in self: 33 | if rec.model_id and rec.res_id: 34 | record = self.env[rec.model_id.model].browse(rec.res_id) 35 | res_id = record[0] if record else 0 36 | rec.resource_ref = '%s,%s' % (rec.model_id.model, res_id.id) 37 | else: 38 | rec.resource_ref = False 39 | 40 | @api.onchange('resource_ref') 41 | def _set_resource_ref(self): 42 | for rec in self: 43 | if rec.resource_ref: 44 | rec.res_id = rec.resource_ref.id 45 | 46 | def get_answer_value(self): 47 | return self.answer 48 | 49 | def save_result_on_target_field(self): 50 | record = self.env[self.model_id.model].browse(self.res_id) 51 | answer_value = self.get_answer_value() 52 | if answer_value and self.target_field_id: 53 | record.write({self.target_field_id.name: answer_value}) 54 | 55 | def action_apply(self): 56 | self.save_result_on_target_field() 57 | -------------------------------------------------------------------------------- /openai_connector/models/openai_tool.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2024 - Michel Perrocheau (https://github.com/myrrkel). 2 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 3 | 4 | import json 5 | from odoo import models, fields, api, _ 6 | from odoo.osv import expression 7 | 8 | import logging 9 | 10 | _logger = logging.getLogger(__name__) 11 | 12 | 13 | class OpenAiTool(models.Model): 14 | _name = 'openai.tool' 15 | _description = 'OpenAI Tool' 16 | 17 | def _get_tool_type_list(self): 18 | return [('function', _('Function'))] 19 | 20 | name = fields.Char() 21 | description = fields.Text() 22 | model_id = fields.Many2one('ir.model', string='Model', ondelete='cascade') 23 | model = fields.Char(related='model_id.model', string='Model Name', readonly=True, store=True) 24 | type = fields.Selection(selection=_get_tool_type_list) 25 | property_ids = fields.One2many('openai.tool.property', 'tool_id', copy=True) 26 | required_property_ids = fields.One2many('openai.tool.property', 'tool_id', readonly=True, 27 | domain=[('required', '=', True)]) 28 | 29 | def get_tool_dict(self): 30 | res = {'type': 'function', 31 | 'function': { 32 | 'name': self.name, 33 | 'description': self.description}} 34 | properties = {} 35 | for property_id in self.property_ids: 36 | properties[property_id.name] = {'type': property_id.type, 37 | 'description': property_id.description} 38 | if properties: 39 | parameters = {'type': 'object', 40 | 'properties': properties} 41 | required = [p.name for p in self.required_property_ids] 42 | if required: 43 | parameters['required'] = required 44 | res['function']['parameters'] = parameters 45 | return res 46 | 47 | @api.model 48 | def search_question_answer(self, keywords): 49 | if ',' not in keywords: 50 | keywords = keywords.replace(' ', ',') 51 | keyword_list = keywords.split(',') 52 | domain = [] 53 | for keyword in keyword_list: 54 | domain = expression.OR([domain, [('name', '=ilike', f'%{keyword}%')]]) 55 | domain = expression.OR([domain, [('answer', '=ilike', f'%{keyword}%')]]) 56 | question_answer_ids = self.env['openai.question.answer'].search(domain) 57 | if not question_answer_ids: 58 | return 'No result found. Suggest to user to reformulate his question or to suggest some keywords.' 59 | res = [{'question': q.name, 60 | 'answer': q.answer, 61 | 'score': q.get_score(keyword_list), 62 | 'length': q.content_length, 63 | } 64 | for q in question_answer_ids] 65 | res = sorted(res, key=lambda x: x['score'], reverse=True) 66 | max_score = res[0]['score'] 67 | res = list(filter(lambda x: x['score'] == max_score, res)) 68 | res = sorted(res, key=lambda x: x['length']) 69 | return json.dumps(res[0]) 70 | 71 | @api.model 72 | def get_search_question_answer_tool(self): 73 | return { 74 | "type": "function", 75 | "function": { 76 | "name": "search_question_answer", 77 | "description": "Search by keywords in the frequently asked questions database. " 78 | "Returns a list of questions with their answers", 79 | "parameters": { 80 | "type": "object", 81 | "properties": { 82 | "keywords": { 83 | "type": "string", 84 | "description": "A list of comma separated keywords. Example: keyword1,keyword2,keyword3", 85 | }, 86 | }, 87 | "required": ["keywords"], 88 | }, 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /openai_connector/models/openai_tool_property.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2024 - Michel Perrocheau (https://github.com/myrrkel). 2 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 3 | 4 | import json 5 | from tempfile import NamedTemporaryFile 6 | from odoo import models, fields, api, _ 7 | from odoo.tools.safe_eval import safe_eval 8 | from odoo.addons.base.models.ir_model import SAFE_EVAL_BASE 9 | 10 | import logging 11 | 12 | _logger = logging.getLogger(__name__) 13 | 14 | 15 | class OpenAiToolProperty(models.Model): 16 | _name = 'openai.tool.property' 17 | _description = 'OpenAI Tool Property' 18 | 19 | def _get_tool_property_type_list(self): 20 | return [('string', _('String')), 21 | ('integer', _('Integer'))] 22 | 23 | name = fields.Char() 24 | tool_id = fields.Many2one('openai.tool', invisible=True) 25 | type = fields.Selection(selection=_get_tool_property_type_list) 26 | description = fields.Text() 27 | required = fields.Boolean() 28 | -------------------------------------------------------------------------------- /openai_connector/models/res_config_settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2022 - Michel Perrocheau (https://github.com/myrrkel). 3 | # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). 4 | 5 | from odoo import api, fields, models, _ 6 | import logging 7 | 8 | _logger = logging.getLogger(__name__) 9 | 10 | 11 | class ResConfigSettings(models.TransientModel): 12 | _inherit = 'res.config.settings' 13 | 14 | openai_api_key = fields.Char(string="OpenAI API Key", config_parameter='openai_api_key') 15 | openai_organization_id = fields.Char(string="OpenAI Organisation ID", config_parameter='openai_organization_id') 16 | -------------------------------------------------------------------------------- /openai_connector/security/ir.model.access.csv: -------------------------------------------------------------------------------- 1 | "id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create","perm_unlink" 2 | access_openai_completion_user,access_openai_completion user,openai_connector.model_openai_completion,base.group_user,1,0,0,0 3 | access_openai_completion_admin,access_openai_completion admin,openai_connector.model_openai_completion,base.group_erp_manager,1,1,1,1 4 | access_openai_completion_result_user,access_openai_completion_result user,openai_connector.model_openai_completion_result,base.group_user,1,1,1,1 5 | access_openai_image_user,access_openai_image user,openai_connector.model_openai_image,base.group_user,1,0,0,0 6 | access_openai_image_admin,access_openai_image admin,openai_connector.model_openai_image,base.group_erp_manager,1,1,1,1 7 | access_openai_image_result_user,access_openai_image_result user,openai_connector.model_openai_image_result,base.group_user,1,1,1,1 8 | access_openai_question_answer_user,access_openai_question_answer user,openai_connector.model_openai_question_answer,base.group_user,1,1,1,1 9 | access_openai_fine_tuning_user,access_openai_fine_tuning user,openai_connector.model_openai_fine_tuning,base.group_user,1,0,0,0 10 | access_openai_fine_tuning_admin,access_openai_fine_tuning admin,openai_connector.model_openai_fine_tuning,base.group_erp_manager,1,1,1,1 11 | access_openai_tool_user,access_openai_tool user,openai_connector.model_openai_tool,base.group_user,1,0,0,0 12 | access_openai_tool_admin,access_openai_tool admin,openai_connector.model_openai_tool,base.group_erp_manager,1,1,1,1 13 | access_openai_tool_property_user,access_openai_tool_property user,openai_connector.model_openai_tool_property,base.group_user,1,0,0,0 14 | access_openai_tool_property_admin,access_openai_tool_property admin,openai_connector.model_openai_tool_property,base.group_erp_manager,1,1,1,1 -------------------------------------------------------------------------------- /openai_connector/security/security.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /openai_connector/static/description/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/description/icon.png -------------------------------------------------------------------------------- /openai_connector/static/description/index.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

OpenAI Connector

4 |

openai_connector

5 |
6 |

7 | This module adds a connector for OpenAI API 8 |

9 |
10 |
11 | 12 | 13 |
14 |
15 |
16 | 17 |
18 |
19 | Contact me 20 |
21 |
22 |
23 | -------------------------------------------------------------------------------- /openai_connector/static/description/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/description/logo.png -------------------------------------------------------------------------------- /openai_connector/static/img/completion_params.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/img/completion_params.png -------------------------------------------------------------------------------- /openai_connector/static/img/openai_logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /openai_connector/static/img/openai_params.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/img/openai_params.png -------------------------------------------------------------------------------- /openai_connector/static/img/prompt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/img/prompt.png -------------------------------------------------------------------------------- /openai_connector/static/img/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/img/settings.png -------------------------------------------------------------------------------- /openai_connector/static/img/tests.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/myrrkel/odoo-openai/96ecfa58d6a552b98f071c9381fc857484872ee8/openai_connector/static/img/tests.png -------------------------------------------------------------------------------- /openai_connector/static/src/scss/style.scss: -------------------------------------------------------------------------------- 1 | .btn-center { 2 | width: 30%; 3 | display: block; 4 | margin-left: auto; 5 | margin-right: auto; 6 | } 7 | 8 | .alert-info-center { 9 | width: max-content; 10 | margin-left: auto; 11 | margin-right: auto; 12 | } 13 | .image-transparent-background img { 14 | background: 15 | repeating-conic-gradient(#b8b8b8 0% 25%, transparent 0% 50%) 16 | 50% / 15px 15px 17 | } -------------------------------------------------------------------------------- /openai_connector/views/openai_completion_result_views.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | openai.completion.result.view.form 5 | openai.completion.result 6 | 7 |
8 | 9 |
10 |
13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 |
35 |
36 |
37 |
38 | 39 | 40 | openai.completion.result.view.tree 41 | openai.completion.result 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | openai.completion.result.simple.view.tree 54 | openai.completion.result 55 | 56 | 57 | 58 | 59 |