├── .github └── workflows │ ├── nightly-check.yml │ └── pull-request-check.yml ├── .gitignore ├── LICENSE ├── README.md ├── examples ├── ex1-factory-safety-report.py ├── ex2-fridge-recipe-generation.py ├── ex3-movie-tweets-analysis.py └── images │ ├── factory-1.png │ ├── factory-2.png │ ├── factory-3.png │ ├── factory-4.png │ └── fridge-1.png ├── jinaai ├── __init__.py ├── clients │ ├── BestBannerClient.py │ ├── HTTPClient.py │ ├── JinaChatClient.py │ ├── PromptPerfectClient.py │ ├── RationaleClient.py │ ├── SceneXClient.py │ └── __init__.py └── utils.py ├── scripts └── publish.sh ├── setup.py └── tests ├── mock ├── HTTPClientMock.py └── responses │ ├── Auth.KO.response.json │ ├── BestBannerResponse.py │ ├── JinaChatResponse.py │ ├── NotImplemented.response.json │ ├── PromptPerfectResponse.py │ ├── RationaleResponse.py │ └── SceneXResponse.py ├── real-cases ├── test_ex1-factory.py ├── test_ex2-fridge.py ├── test_ex3-tweet.py ├── test_ex4-email.py ├── test_ex5-story.py ├── test_ex6-video.py └── text_ex7-json.py ├── test_authentication.py ├── test_baseurls.py ├── test_bestbanner.py ├── test_chatcat.py ├── test_promptperfect.py ├── test_rationale.py ├── test_scenex.py └── test_utility.py /.github/workflows/nightly-check.yml: -------------------------------------------------------------------------------- 1 | name: Nightly Check 2 | 3 | on: 4 | schedule: 5 | - cron: '30 20 * * *' 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | python-version: [3.9] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | - run: pip install . && pip install pytest 24 | - run: cd tests && python -m pytest --ignore=real-cases 25 | - run: cd tests/real-cases && BESTBANNER_SECRET=$BB PROMPTPERFECT_SECRET=$PP SCENEX_SECRET=$SX RATIONALE_SECRET=$RA JINACHAT_SECRET=$CC pytest 26 | shell: bash 27 | env: 28 | PP: ${{ secrets.PROMPTPERFECT_SECRET }} 29 | SX: ${{ secrets.SCENEX_SECRET }} 30 | RA: ${{ secrets.RATIONALE_SECRET }} 31 | CC: ${{ secrets.JINACHAT_SECRET }} 32 | BB: ${{ secrets.BESTBANNER_SECRET }} 33 | -------------------------------------------------------------------------------- /.github/workflows/pull-request-check.yml: -------------------------------------------------------------------------------- 1 | name: PR Check 2 | 3 | on: 4 | pull_request: 5 | 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | strategy: 13 | matrix: 14 | python-version: [3.8, 3.9] 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - run: pip install . && pip install pytest 23 | - run: cd tests && python -m pytest --ignore=real-cases 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /node_modules 3 | /build 4 | /dist 5 | /**.egg-info 6 | 7 | # Logs 8 | logs 9 | *.log 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | lerna-debug.log* 14 | 15 | # OS 16 | .DS_Store 17 | __pycache__ 18 | 19 | # Tests 20 | /coverage 21 | /.nyc_output 22 | 23 | # IDEs and editors 24 | /.idea 25 | .project 26 | .classpath 27 | .c9/ 28 | *.launch 29 | .settings/ 30 | *.sublime-workspace 31 | 32 | # IDE - VSCode 33 | .vscode/* 34 | !.vscode/settings.json 35 | !.vscode/tasks.json 36 | !.vscode/launch.json 37 | !.vscode/extensions.json 38 | 39 | .pytest_cache -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JinaAI Python SDK 2 | 3 | The JinaAI Python SDK is an efficient instrument that smoothly brings the power of JinaAI's products — [SceneXplain](https://scenex.jina.ai), [PromptPerfect](https://promptperfect.jina.ai/), [Rationale](https://rationale.jina.ai/), [BestBanner](https://bestbanner.jina.ai/), and [JinaChat](https://chat.jina.ai/) — into Python applications. Acting as a sturdy interface for JinaAI's APIs, this SDK lets you effortlessly formulate and fine-tune prompts, thus streamlining application development. 4 | 5 | ## Installing 6 | 7 | ### Package manager 8 | 9 | Using pip: 10 | ```bash 11 | $ pip install jinaai 12 | ``` 13 | 14 | ## API secrets 15 | 16 | To generate an API secret, you need to authenticate on each respective platform's API tab: 17 | 18 | - [SceneXplain API](https://scenex.jina.ai/api) 19 | - [PromptPerfect API](https://promptperfect.jina.ai/api) 20 | - [Rationale API](https://rationale.jina.ai/api) 21 | - [JinaChat API](https://chat.jina.ai/api) 22 | - [BestBanner API](https://bestbanner.jina.ai/api) 23 | 24 | > **Note:** Each secret is product-specific and cannot be interchanged. If you're planning to use multiple products, you'll need to generate a separate secret for each. 25 | 26 | ## Example usage 27 | 28 | 29 | Import the SDK and instantiate a new client with your authentication secrets: 30 | 31 | ```python 32 | from jinaai import JinaAI 33 | 34 | jinaai = JinaAI( 35 | secrets = { 36 | 'promptperfect-secret': 'XXXXXX', 37 | 'scenex-secret': 'XXXXXX', 38 | 'rationale-secret': 'XXXXXX', 39 | 'jinachat-secret': 'XXXXXX', 40 | 'bestbanner-secret': 'XXXXXX', 41 | } 42 | ) 43 | ``` 44 | 45 | Describe images: 46 | 47 | ```python 48 | descriptions = jinaai.describe( 49 | 'https://picsum.photos/200' 50 | ) 51 | ``` 52 | 53 | Evaluate situations: 54 | 55 | ```python 56 | decisions = jinaai.decide( 57 | 'Going to Paris this summer', 58 | { 'analysis': 'proscons' } 59 | ) 60 | ``` 61 | 62 | Optimize prompts: 63 | 64 | ```python 65 | prompts = jinaai.optimize( 66 | 'Write an Hello World function in Python' 67 | ) 68 | ``` 69 | 70 | Generate complex answers: 71 | 72 | ```python 73 | output = jinaai.generate( 74 | 'Give me a recipe for a pizza with pineapple' 75 | ) 76 | ``` 77 | 78 | Create images from text: 79 | 80 | ```python 81 | output = jinaai.imagine( 82 | 'A controversial fusion of sweet pineapple and savory pizza.' 83 | ) 84 | ``` 85 | 86 | Use APIs together: 87 | 88 | ```python 89 | situations = [toBase64(img) for img in [ 90 | 'factory-1.png', 91 | 'factory-2.png', 92 | 'factory-3.png', 93 | 'factory-4.png', 94 | ]] 95 | 96 | descriptions = jinaai.describe(situations) 97 | 98 | prompt1 = [ 99 | 'Do any of those situations present a danger?', 100 | 'Reply with [YES] or [NO] and explain why', 101 | *['SITUATION:\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 102 | ] 103 | 104 | analysis = jinaai.generate('\n'.join(prompt1)) 105 | 106 | prompt2 = [ 107 | 'What should be done first to make those situations safer?', 108 | 'I only want the most urgent situation', 109 | *['SITUATION:\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 110 | ] 111 | 112 | recommendation = jinaai.generate('\n'.join(propmt2)) 113 | 114 | swot = jinaai.decide( 115 | recommendation['output'], 116 | { 'analysis': 'swot' } 117 | ) 118 | 119 | banners = jinaai.imagine( 120 | *[desc['output'] for i, desc in enumerate(descriptions['results'])] 121 | ) 122 | ``` 123 | 124 | ## Raw Output 125 | 126 | You can retrieve the raw output of each APIs by passing `raw: True` in the options: 127 | 128 | ```python 129 | descriptions = jinaai.describe( 130 | 'https://picsum.photos/200', 131 | { 'raw': True } 132 | ) 133 | 134 | print(descriptions['raw']) 135 | ``` 136 | 137 | ## Custom Base Urls 138 | 139 | Custom base Urls can be passed directly in the client's constructor: 140 | 141 | ```python 142 | jinaai = JinaAI( 143 | baseUrls={ 144 | 'promptperfect': 'https://promptperfect-customurl.jina.ai', 145 | 'scenex': 'https://scenex-customurl.jina.ai', 146 | 'rationale': 'https://rationale-customurl.jina.ai', 147 | 'jinachat': 'https://jinachat-customurl.jina.ai', 148 | 'bestbanner': 'https://bestbanner-customurl.jina.ai', 149 | } 150 | ) 151 | ``` 152 | 153 | ## API Documentation 154 | 155 | ### JinaAi.describe 156 | 157 | ```python 158 | output = JinaAI.describe(input, options) 159 | ``` 160 | 161 | - Input 162 | 163 | >| VARIABLE | TYPE | VALUE 164 | >|---------------------------------------|-------------------|---------- 165 | >| input | str / str array | Image URL or Base64 166 | 167 | - Options 168 | 169 | >| VARIABLE | TYPE | VALUE 170 | >|----------------------------------------|-------------------|---------- 171 | >| options | dict | 172 | >| options['algorithm'] | None / str | Aqua / Bolt / Comet / Dune / Ember / Flash / Glide / Hearth / Inception / Jelly 173 | >| options['features'] | None / str array | high_quality, question_answer, tts, opt-out, json 174 | >| options['languages'] | None / str array | en, cn, de, fr, it... 175 | >| options['question'] | None / str | Question related to the picture(s) 176 | >| options['style'] | None / str | default / concise / prompt 177 | >| options['output_length'] | None / number | 178 | >| options['json_schema'] | None / dict | 179 | >| options['callback_url'] | None / string | 180 | 181 | - Output 182 | 183 | >| VARIABLE | TYPE | VALUE 184 | >|----------------------------------------|-------------------|---------- 185 | >| output | dict | 186 | >| output['results'] | dict array | 187 | >| results[0]['output'] | str | The picture description 188 | >| results[0]['i18n'] | dict | Contains one key for each item in languages 189 | >| ...i18n['cn'] | str | The translated picture description 190 | >| ...i18n['cn'] | dict array | Only for Hearth algorithm 191 | >| ...i18n['cn'][0] | dict | 192 | >| ...i18n['cn'][0]['message'] | str | 193 | >| ...i18n['cn'][0]['isNarrator'] | boolean | 194 | >| ...i18n['cn'][0]['name'] | str | 195 | >| ...i18n['cn'] | dict array | Only for Inception algorithm 196 | >| ...i18n['cn'][0] | dict | 197 | >| ...i18n['cn'][0]['summary'] | str | 198 | >| ...i18n['cn'][0]['events'] | dict array | 199 | >| ...['events']['description'] | str | 200 | >| ...['events']['timestamp'] | str | 201 | >| results[0]['tts'] | dict | Only for Hearth algorithm 202 | >| ...tts['cn'] | str | Contains the url to the tts file 203 | >| results[0]['ssml'] | dict | Only for Hearth algorithm 204 | >| ...ssml['cn'] | str | Contains the url to the ssml file 205 | 206 |
207 | 208 | ### JinaAi.optimize 209 | 210 | ```python 211 | output = JinaAI.optimize(input, options) 212 | ``` 213 | 214 | - Input 215 | 216 | >| VARIABLE | TYPE | VALUE 217 | >|----------------------------------------|-------------------|---------- 218 | >| input | str / str array | Image URL or Base64 / prompt to optimize 219 | 220 | - Options 221 | 222 | >| VARIABLE | TYPE | VALUE 223 | >|----------------------------------------|-------------------|---------- 224 | >| options | dict | 225 | >| options['targetModel'] | None / str | chatgpt / gpt-4 / stablelm-tuned-alpha-7b / claude / cogenerate / text-davinci-003 / dalle / sd / midjourney / kandinsky / lexica 226 | >| options['features'] | None / str array | preview, no_spam, shorten, bypass_ethics, same_language, always_en, high_quality, redo_original_image, variable_subs, template_run 227 | >| options['iterations'] | None / number | Default: 1 228 | >| options['previewSettings'] | None / dict | Contains the settings for the preview 229 | >| ...previewSettings['temperature'] | number | Example: 0.9 230 | >| ...previewSettings['topP'] | number | Example: 0.9 231 | >| ...previewSettings['topK'] | number | Example: 0 232 | >| ...previewSettings['frequencyPenalty'] | number | Example: 0 233 | >| ...previewSettings['presencePenalty'] | number | Example: 0 234 | >| options['previewVariables'] | None / dict | Contains one key for each variables in the prompt 235 | >| ...previewVariables['var1'] | str | The value of the variable 236 | >| options['timeout'] | Number | Default: 20000 237 | >| options['target_language'] | None / str | en / cn / de / fr / it... 238 | 239 | - Output 240 | 241 | >| VARIABLE | TYPE | VALUE 242 | >|----------------------------------------|-------------------|---------- 243 | >| output | dict | 244 | >| output['results'] | dict array | 245 | >| results[0]['output'] | str | The optimized prompt 246 | 247 |
248 | 249 | ### JinaAi.decide 250 | 251 | ```python 252 | output = JinaAI.decide(input, options) 253 | ``` 254 | 255 | - Input 256 | 257 | >| VARIABLE | TYPE | VALUE 258 | >|----------------------------------------|-------------------|---------- 259 | >| input | str / str array | Decision to evaluate 260 | 261 | - Options 262 | 263 | >| VARIABLE | TYPE | VALUE 264 | >|----------------------------------------|-------------------|---------- 265 | >| options | dict | 266 | >| options['analysis'] | None / str | proscons / swot / multichoice / outcomes 267 | >| options['style'] | None / str | concise / professional / humor / sarcastic / childish / genZ 268 | >| options['profileId'] | None / str | The id of the Personas you want to use 269 | 270 | - Output 271 | 272 | >| VARIABLE | TYPE | VALUE 273 | >|----------------------------------------|-------------------|---------- 274 | >| output | dict | 275 | >| output['results'] | dict array | 276 | >| results[0]['proscons'] | None / dict | 277 | >| ...proscons['pros'] | dict | Contains one key for each pros 278 | >| ...proscons['pros']['pros1'] | str | The explanation of the pros 279 | >| ...proscons['cons'] | dict | Contains one key for each cons 280 | >| ...proscons['cons']['cons1'] | str | The explanation of the cons 281 | >| ...proscons['bestChoice'] | str | 282 | >| ...proscons['conclusion'] | str | 283 | >| ...proscons['confidenceScore'] | number | 284 | >| results[0]['swot'] | None / dict | 285 | >| ...swot['strengths'] | dict | Contains one key for each strength 286 | >| ...swot['strengths']['str1'] | str | The explanation of the strength 287 | >| ...swot['weaknesses'] | dict | Contains one key for each weakness 288 | >| ...swot['weaknesses']['weak1'] | str | The explanation of the weakness 289 | >| ...swot['opportunities'] | dict | Contains one key for each opportunity 290 | >| ...swot['opportunities']['opp1'] | str | The explanation of the opportunity 291 | >| ...swot['threats'] | dict | Contains one key for each threat 292 | >| ...swot['threats']['thre1'] | str | The explanation of the threat 293 | >| ...swot['bestChoice'] | str | 294 | >| ...swot['conclusion'] | str | 295 | >| ...swot['confidenceScore'] | number | 296 | >| results[0]['multichoice'] | None / dict | Contains one key for each choice 297 | >| ...multichoice['choice1'] | str | The value of the choice 298 | >| results[0]['outcomes'] | None / dict array | 299 | >| ...outcomes[0]['children'] | None / dict array | a recursive array of results['outcomes'] 300 | >| ...outcomes[0]['label'] | str | 301 | >| ...outcomes[0]['sentiment'] | str | 302 | 303 |
304 | 305 | ### JinaAi.generate 306 | 307 | ```python 308 | output = JinaAI.generate(input, options) 309 | ``` 310 | 311 | - Input 312 | 313 | >| VARIABLE | TYPE | VALUE 314 | >|----------------------------------------|------------------------|---------- 315 | >| input | str / str array | Image URL or Base64 / prompt 316 | 317 | - Options 318 | 319 | >| VARIABLE | TYPE | VALUE 320 | >|----------------------------------------|------------------------|---------- 321 | >| options | dict | 322 | >| options['role'] | None / str | user / assistant 323 | >| options['name'] | None / str | The name of the author of this message 324 | >| options['chatId'] | None / str | The id of the conversation to continue 325 | >| options['stream'] | None / boolean | Whether to stream back partial progress, Default: false 326 | >| options['temperature'] | None / number | Default: 1 327 | >| options['top_p'] | None / str | Default: 1 328 | >| options['stop'] | None / str / str array | Up to 4 sequences where the API will stop generating further tokens 329 | >| options['max_tokens'] | None / number | Default: infinite 330 | >| options['presence_penalty'] | None / number | Number between -2.0 and 2.0, Default: 0 331 | >| options['frequency_penalty'] | None / number | Number between -2.0 and 2.0, Default: 0 332 | >| options['logit_bias'] | None / dict | The likelihood for a token to appear in the completion 333 | >| ...logit_bias['tokenId'] | number | Bias value from -100 to 100 334 | >| options['image'] | str | The attached image of the message. The image can be either a URL or a base64-encoded string 335 | 336 | - Output 337 | 338 | >| VARIABLE | TYPE | VALUE 339 | >|----------------------------------------|-------------------|---------- 340 | >| output | dict | 341 | >| output['output'] | str | The generated answer 342 | >| output['chatId'] | str | The chatId to continue the conversation 343 | 344 |
345 | 346 | ### JinaAi.imagine 347 | 348 | ```python 349 | output = JinaAI.imagine(input, options) 350 | ``` 351 | 352 | - Input 353 | 354 | >| VARIABLE | TYPE | VALUE 355 | >|----------------------------------------|------------------------|---------- 356 | >| input | str / str array | Prompt 357 | 358 | - Options 359 | 360 | >| VARIABLE | TYPE | VALUE 361 | >|----------------------------------------|------------------------|---------- 362 | >| options | dict | 363 | >| options['style'] | None / str | default / photographic / minimalist / flat 364 | 365 | - Output 366 | 367 | >| VARIABLE | TYPE | VALUE 368 | >|----------------------------------------|-------------------|---------- 369 | >| output | dict | 370 | >| output['results'] | dict array | 371 | >| results[0]['output'] | array | array of 4 image urls 372 | 373 |
374 | 375 | ### JinaAi.utils 376 | 377 | ```python 378 | outout = JinaAI.utils.image_to_base64(input) 379 | ``` 380 | 381 | >| VARIABLE | TYPE | VALUE 382 | >|---------------------------------------|-------------------|---------- 383 | >| input | str | Image path on disk 384 | >| output | str | Base64 image 385 | 386 | ```python 387 | outout = JinaAI.utils.is_url(input) 388 | ``` 389 | 390 | >| VARIABLE | TYPE | VALUE 391 | >|---------------------------------------|-------------------|---------- 392 | >| input | str | 393 | >| output | boolean | 394 | 395 | ```python 396 | outout = JinaAI.utils.is_base64(input) 397 | ``` 398 | 399 | >| VARIABLE | TYPE | VALUE 400 | >|---------------------------------------|-------------------|---------- 401 | >| input | str | 402 | >| output | boolean | 403 | -------------------------------------------------------------------------------- /examples/ex1-factory-safety-report.py: -------------------------------------------------------------------------------- 1 | from jinaai import JinaAI 2 | import os 3 | 4 | jinaai = JinaAI( 5 | secrets = { 6 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 7 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 8 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 9 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', ''), 10 | 'bestbanner-secret': os.environ.get('BESTBANNER_SECRET', '') 11 | } 12 | ) 13 | 14 | def toBase64(img: str) -> str: 15 | return jinaai.utils.image_to_base64(f"images/{img}") 16 | 17 | situations = [toBase64(img) for img in [ 18 | 'factory-2.png', 19 | 'factory-3.png', 20 | 'factory-4.png', 21 | ]] 22 | 23 | def evaluate(): 24 | try: 25 | # 1. get a description of each situations 26 | descriptions = jinaai.describe(situations) 27 | for i, desc in enumerate(descriptions['results']): 28 | print(f"DESCRIPTION {i + 1}:\n{desc['output']}\n") 29 | # 2. get an analysis based on those descriptions 30 | analysis = jinaai.generate('\n'.join([ 31 | 'Does any of those situations present a danger?', 32 | 'Reply with [SITUATION_NUMBER] [YES] or [NO] and explain why', 33 | *['SITUATION ' + str(i + 1) + ':\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 34 | ])) 35 | print('ANALYSIS:\n', analysis['output']) 36 | # 3. get a recommendation on the most urgent action to take 37 | recommendation = jinaai.generate('\n'.join([ 38 | 'According to those situations, what should be done first to make everything safer?', 39 | 'I only want the most urgent situation', 40 | *['SITUATION ' + str(i + 1) + ':\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 41 | ])) 42 | print('RECOMMENDATION:\n', recommendation['output']) 43 | # 4. get a swot analysis of the recommendation 44 | swot = jinaai.decide( 45 | recommendation['output'], 46 | { 'analysis': 'swot' } 47 | ) 48 | print('SWOT:\n', swot['results'][0]['swot']) 49 | # 5. get a banner for the report 50 | banners = jinaai.imagine(descriptions['results'][0]['output']) 51 | print('BANNERS:\n', banners['results']) 52 | except Exception as e: 53 | print("Error:", str(e)) 54 | 55 | evaluate() 56 | -------------------------------------------------------------------------------- /examples/ex2-fridge-recipe-generation.py: -------------------------------------------------------------------------------- 1 | from jinaai import JinaAI 2 | import os 3 | 4 | jinaai = JinaAI( 5 | secrets = { 6 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 7 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 8 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 9 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', ''), 10 | 'bestbanner-secret': os.environ.get('BESTBANNER_SECRET', '') 11 | } 12 | ) 13 | 14 | def toBase64(img: str) -> str: 15 | return jinaai.utils.image_to_base64(f"images/{img}") 16 | 17 | fridge = toBase64('fridge-1.png') 18 | 19 | def generate(): 20 | try: 21 | # 1. get a description of the fridge content 22 | descriptions = jinaai.describe( 23 | fridge, 24 | { 'question': 'What ingredients are in the fridge?', 'languages': ['en'] } 25 | ) 26 | print('DESCRIPTION:\n', descriptions['results'][0]['output']) 27 | # 2. get an optmised prompt 28 | prompt = jinaai.optimize('\n'.join([ 29 | 'Give me one recipe based on this list for ingredients', 30 | *['INGREDIENTS:\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 31 | ])) 32 | print('PROMPT:\n', prompt['results'][0]['output']) 33 | # 3. get a recipe based on the descriptions 34 | recipe = jinaai.generate(prompt['results'][0]['output']) 35 | print('RECIPE:\n', recipe['output']) 36 | # 4. get a swot analysis of the recommendation 37 | swot = jinaai.decide( 38 | recipe['output'], 39 | { 'analysis': 'swot' } 40 | ) 41 | print('SWOT:\n', swot['results'][0]['swot']) 42 | # 5. get a banner for the recipe 43 | banners = jinaai.imagine(recipe['output']) 44 | print('BANNERS:\n', banners['results']) 45 | except Exception as e: 46 | print("Error:", str(e)) 47 | 48 | generate() 49 | -------------------------------------------------------------------------------- /examples/ex3-movie-tweets-analysis.py: -------------------------------------------------------------------------------- 1 | from jinaai import JinaAI 2 | import os 3 | 4 | jinaai = JinaAI( 5 | secrets = { 6 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 7 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 8 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 9 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', '') 10 | } 11 | ) 12 | 13 | positiveMovieTweets = [ 14 | 'Just watched the new movie! The plot was incredible, and the visual effects were mind-blowing. Definitely a must-see! #movie #amazing', 15 | "I can't stop thinking about the movie. The acting was superb, and the twist at the end caught me off guard. Highly recommended! #movie #thriller", 16 | 'The cinematography in the movie was stunning. Every scene was like a work of art. #movie #cinema', 17 | 'The new movie is a rollercoaster of emotions. I laughed, I cried, and I was on the edge of my seat throughout the entire film. #movie #emotional', 18 | "Just came back from watching the movie, and I'm still speechless. It's a masterpiece! #movie #masterpiece", 19 | "If you're looking for a good movie to watch, I highly recommend this one. It has a compelling story and brilliant performances. #movie #recommendation", 20 | 'The movie exceeded my expectations. The pacing was perfect, and the characters were so well-developed. #movie #surprise', 21 | "I'm still trying to process what I just witnessed in the movie. It's unlike anything I've ever seen before. #movie #unique", 22 | "Can't get enough of the movie's soundtrack. It perfectly complements the visuals and adds so much depth to the film. #movie #soundtrack", 23 | "Just watched the movie with my friends, and we had a blast. It's entertaining from start to finish. #movie #fun" 24 | ] 25 | 26 | negativeMovieTweets = [ 27 | 'I just watched the new movie, and it was a complete disappointment. The plot was confusing, and the acting was terrible. #movie #disappointed', 28 | 'Save your money and skip this movie. It was boring and predictable. #movie #boring', 29 | "I don't understand the hype around this movie. It was overrated and not worth the ticket price. #movie #overrated", 30 | 'I had high expectations for this movie, but it fell flat. The storyline was weak, and the characters were poorly developed. #movie #letdown', 31 | 'I regret watching this movie. It was a waste of time. #movie #wasteoftime', 32 | "I can't believe I paid to see this movie. It was absolutely awful. #movie #awful", 33 | 'The movie was a disaster. The dialogue was cringe-worthy, and the special effects were laughable. #movie #disaster', 34 | 'I was bored throughout the entire movie. It lacked any excitement or originality. #movie #uninteresting', 35 | 'I was really looking forward to this movie, but it was a major letdown. The pacing was off, and the ending was unsatisfying. #movie #majorletdown', 36 | "I don't recommend this movie at all. It was a total mess and didn't make any sense. #movie #notrecommended" 37 | ] 38 | 39 | def evaluate(tweets): 40 | try: 41 | # 1. get the general feeling according to the tweets 42 | prompt = '\n'.join([ 43 | 'According to those tweets, is the general feeling positive or negative?', 44 | 'Reply by [POSITIVE] or [NEGATIVE]', 45 | *['TWEET:\n' + t for i, t in enumerate(tweets)] 46 | ]) 47 | feeling = jinaai.generate(prompt) 48 | print('GENERAL FEELING:', feeling['output']) 49 | except Exception as e: 50 | print("Error:", str(e)) 51 | 52 | evaluate(positiveMovieTweets) 53 | evaluate(negativeMovieTweets) 54 | -------------------------------------------------------------------------------- /examples/images/factory-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/examples/images/factory-1.png -------------------------------------------------------------------------------- /examples/images/factory-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/examples/images/factory-2.png -------------------------------------------------------------------------------- /examples/images/factory-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/examples/images/factory-3.png -------------------------------------------------------------------------------- /examples/images/factory-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/examples/images/factory-4.png -------------------------------------------------------------------------------- /examples/images/fridge-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/examples/images/fridge-1.png -------------------------------------------------------------------------------- /jinaai/__init__.py: -------------------------------------------------------------------------------- 1 | from .clients.SceneXClient import SceneXClient 2 | from .clients.PromptPerfectClient import PromptPerfectClient 3 | from .clients.RationaleClient import RationaleClient 4 | from .clients.JinaChatClient import JinaChatClient 5 | from .clients.BestBannerClient import BestBannerClient 6 | from .utils import is_url, is_base64, image_to_base64, filter_args 7 | 8 | class JinaAI: 9 | def __init__(self, secrets={}, baseUrls={}): 10 | PPSecret = f"token {secrets['promptperfect-secret']}" if secrets and 'promptperfect-secret' in secrets else '' 11 | SXSecret = f"token {secrets['scenex-secret']}" if secrets and 'scenex-secret' in secrets else '' 12 | RASecret = f"token {secrets['rationale-secret']}" if secrets and 'rationale-secret' in secrets else '' 13 | CCSecret = f"Bearer {secrets['jinachat-secret']}" if secrets and 'jinachat-secret' in secrets else '' 14 | BBSecret = f"token {secrets['bestbanner-secret']}" if secrets and 'bestbanner-secret' in secrets else '' 15 | ppCustomUrl = baseUrls['promptperfect'] if baseUrls and 'promptperfect' in baseUrls else None 16 | sxCustomUrl = baseUrls['scenex'] if baseUrls and 'scenex' in baseUrls else None 17 | raCustomUrl = baseUrls['rationale'] if baseUrls and 'rationale' in baseUrls else None 18 | ccCustomUrl = baseUrls['jinachat'] if baseUrls and 'jinachat' in baseUrls else None 19 | bbCustomUrl = baseUrls['bestbanner'] if baseUrls and 'bestbanner' in baseUrls else None 20 | self.PPClient = PromptPerfectClient(**filter_args(headers = { "x-api-key": PPSecret }, baseUrl=ppCustomUrl)) 21 | self.SXClient = SceneXClient(**filter_args(headers = { "x-api-key": SXSecret }, baseUrl=sxCustomUrl)) 22 | self.RAClient = RationaleClient(**filter_args(headers = { "x-api-key": RASecret }, baseUrl=raCustomUrl)) 23 | self.CCClient = JinaChatClient(**filter_args(headers = { "authorization": CCSecret }, baseUrl=ccCustomUrl)) 24 | self.BBClient = BestBannerClient(**filter_args(headers = { "x-api-key": BBSecret }, baseUrl=bbCustomUrl)) 25 | 26 | def decide(self, input, options=None): 27 | if isinstance(input, list): 28 | data = self.RAClient.from_array(input, options) 29 | elif isinstance(input, str): 30 | data = self.RAClient.from_string(input, options) 31 | else: 32 | data = input 33 | return self.RAClient.decide(data, options) 34 | 35 | def optimize(self, input, options=None): 36 | if isinstance(input, list): 37 | data = self.PPClient.from_array(input, options) 38 | elif isinstance(input, str): 39 | data = self.PPClient.from_string(input, options) 40 | else: 41 | data = input 42 | return self.PPClient.optimize(data, options) 43 | 44 | def describe(self, input, options=None): 45 | if isinstance(input, list): 46 | data = self.SXClient.from_array(input, options) 47 | elif isinstance(input, str): 48 | data = self.SXClient.from_string(input, options) 49 | else: 50 | data = input 51 | return self.SXClient.describe(data, options) 52 | 53 | def generate(self, input, options=None): 54 | if isinstance(input, list): 55 | data = self.CCClient.from_array(input, options) 56 | elif isinstance(input, str): 57 | data = self.CCClient.from_string(input, options) 58 | else: 59 | data = input 60 | if options is not None and options.get('stream', False): 61 | return self.CCClient.stream(data, options) 62 | else: 63 | return self.CCClient.generate(data, options) 64 | 65 | def imagine(self, input, options=None): 66 | if isinstance(input, list): 67 | data = self.BBClient.from_array(input, options) 68 | elif isinstance(input, str): 69 | data = self.BBClient.from_string(input, options) 70 | else: 71 | data = input 72 | return self.BBClient.imagine(data, options) 73 | 74 | class utils: 75 | @staticmethod 76 | def is_url(string): 77 | return is_url(string) 78 | @staticmethod 79 | def is_base64(string): 80 | return is_base64(string) 81 | @staticmethod 82 | def image_to_base64(file_path): 83 | return image_to_base64(file_path) -------------------------------------------------------------------------------- /jinaai/clients/BestBannerClient.py: -------------------------------------------------------------------------------- 1 | from .HTTPClient import HTTPClient 2 | 3 | class BestBannerClient(HTTPClient): 4 | def __init__(self, headers=None, options=None, baseUrl='https://api.bestbanner.jina.ai/v1'): 5 | defaultHeaders = { 6 | 'Content-Type': 'application/json', 7 | } 8 | mergedHeaders = defaultHeaders.update(headers) 9 | super().__init__(baseUrl=baseUrl, headers=defaultHeaders, options=options) 10 | 11 | def from_array(self, input, options=None): 12 | return { 13 | 'data': [ 14 | { 15 | 'text': i, 16 | **(options or {}) 17 | } 18 | for i in input 19 | ] 20 | } 21 | 22 | def from_string(self, input, options=None): 23 | return { 24 | 'data': [ 25 | { 26 | 'text': input, 27 | **(options or {}) 28 | } 29 | ] 30 | } 31 | 32 | def to_simplified_output(self, output): 33 | if not output.get('result') or any(x.get('banners') and len(x['banners']) != 0 for x in output['result']) is False: 34 | raise Exception('Remote API Error, bad output: {}'.format(json.dumps(output))) 35 | return { 36 | 'results': [ 37 | { 38 | 'output': [ 39 | b['url'] for b in r['banners'] 40 | ] 41 | } 42 | for r in output['result'] 43 | ] 44 | } 45 | 46 | def imagine(self, data, options = None): 47 | raw_output = self.post('/generate', data) 48 | simplified_output = self.to_simplified_output(raw_output) 49 | if options and 'raw' in options: 50 | simplified_output['raw'] = raw_output 51 | return simplified_output 52 | 53 | -------------------------------------------------------------------------------- /jinaai/clients/HTTPClient.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | class HTTPClient: 4 | def __init__(self, baseUrl, headers=None, options=None): 5 | self.baseUrl = baseUrl 6 | self.headers = headers if headers else {} 7 | self.options = options if options else {} 8 | 9 | def setHeaders(self, headers): 10 | self.headers = headers 11 | 12 | def addHeader(self, header): 13 | self.headers.update(header) 14 | 15 | def get(self, url): 16 | response = requests.get(self.baseUrl + url, headers=self.headers) 17 | responseData = response.json() 18 | return responseData 19 | 20 | def post(self, url, data, toJson=True): 21 | response = requests.post(self.baseUrl + url, json=data, headers=self.headers, **self.options) 22 | if toJson == False: 23 | return response 24 | else: 25 | responseData = response.json() 26 | if "error" in responseData: 27 | raise Exception(responseData["error"]) 28 | return responseData 29 | 30 | def put(self, url, data): 31 | response = requests.put(self.baseUrl + url, headers=self.headers) 32 | responseData = response.json() 33 | return responseData 34 | 35 | def delete(self, url): 36 | response = requests.delete(self.baseUrl + url, headers=self.headers) 37 | responseData = response.json() 38 | return responseData 39 | -------------------------------------------------------------------------------- /jinaai/clients/JinaChatClient.py: -------------------------------------------------------------------------------- 1 | from .HTTPClient import HTTPClient 2 | from ..utils import is_base64, is_url, omit 3 | 4 | 5 | class JinaChatClient(HTTPClient): 6 | def __init__(self, headers=None, options=None, baseUrl='https://api.chat.jina.ai/v1/chat'): 7 | defaultHeaders = { 8 | 'Content-Type': 'application/json', 9 | } 10 | mergedHeaders = defaultHeaders.update(headers) 11 | super().__init__(baseUrl=baseUrl, headers=defaultHeaders, options=options) 12 | 13 | def from_array(self, input, options=None): 14 | return { 15 | 'messages': [ 16 | { 17 | 'content': i, 18 | **((options and options.get("image") and (is_url(options['image']) or is_base64(options['image'])) and { 'image': options['image'] }) or {}), 19 | 'role': 'user', 20 | **(omit(options, 'image')) 21 | } 22 | for i in input 23 | ], 24 | **(omit(options, 'image')) 25 | } 26 | 27 | def from_string(self, input, options=None): 28 | return { 29 | 'messages': [ 30 | { 31 | 'content': input, 32 | **((options and options.get("image") and (is_url(options['image']) or is_base64(options['image'])) and { 'image': options['image'] }) or {}), 33 | 'role': 'user', 34 | **(omit(options, 'image')) 35 | } 36 | ], 37 | **(omit(options, 'image')) 38 | } 39 | 40 | def to_simplified_output(self, output): 41 | if 'choices' not in output or len(output['choices']) < 1 or output['choices'][0]['message']['content'] == '': 42 | raise Exception('Remote API Error, bad output: ' + str(output)) 43 | return { 44 | 'output': output['choices'][0]['message']['content'], 45 | 'chatId': output['chatId'] 46 | } 47 | 48 | def generate(self, data, options = None): 49 | raw_output = self.post('/completions', data) 50 | simplified_output = self.to_simplified_output(raw_output) 51 | if options and 'raw' in options: 52 | simplified_output['raw'] = raw_output 53 | return simplified_output 54 | 55 | def stream(self, data, options = None): 56 | return self.post('/completions', data, False) 57 | -------------------------------------------------------------------------------- /jinaai/clients/PromptPerfectClient.py: -------------------------------------------------------------------------------- 1 | from .HTTPClient import HTTPClient 2 | from ..utils import is_base64, is_url 3 | 4 | class PromptPerfectClient(HTTPClient): 5 | def __init__(self, headers=None, options=None, baseUrl='https://api.promptperfect.jina.ai'): 6 | defaultHeaders = { 7 | 'Content-Type': 'application/json', 8 | } 9 | mergedHeaders = defaultHeaders.update(headers) 10 | super().__init__(baseUrl=baseUrl, headers=defaultHeaders, options=options) 11 | 12 | def from_array(self, input, options=None): 13 | return { 14 | 'data': [ 15 | { 16 | **(((not is_url(i) and not is_base64(i)) and { 'prompt': i }) or {}), 17 | **(((is_url(i) or is_base64(i)) and { 'imagePrompt': i }) or {}), 18 | 'targetModel': 'chatgpt', 19 | 'features': [], 20 | **(options or {}) 21 | } 22 | for i in input 23 | ] 24 | } 25 | 26 | def from_string(self, input, options=None): 27 | return { 28 | 'data': [ 29 | { 30 | **(((not is_url(input) and not is_base64(input)) and { 'prompt': input }) or {}), 31 | **(((is_url(input) or is_base64(input)) and { 'imagePrompt': input }) or {}), 32 | 'targetModel': 'chatgpt', 33 | 'features': [], 34 | **(options or {}) 35 | } 36 | ] 37 | } 38 | 39 | def to_simplified_output(self, output): 40 | if not output.get('result') or any(x.get('promptOptimized') != '' for x in output['result']) is False: 41 | raise Exception('Remote API Error, bad output: {}'.format(json.dumps(output))) 42 | return { 43 | 'results': [ 44 | { 45 | 'output': r.get('promptOptimized'), 46 | } 47 | for r in output['result'] 48 | ] 49 | } 50 | 51 | def optimize(self, data, options = None): 52 | raw_output = self.post('/optimizeBatch', data) 53 | simplified_output = self.to_simplified_output(raw_output) 54 | if options and 'raw' in options: 55 | simplified_output['raw'] = raw_output 56 | return simplified_output 57 | 58 | -------------------------------------------------------------------------------- /jinaai/clients/RationaleClient.py: -------------------------------------------------------------------------------- 1 | from .HTTPClient import HTTPClient 2 | from ..utils import is_base64, is_url 3 | 4 | MAXLEN = 300 5 | 6 | class RationaleClient(HTTPClient): 7 | def __init__(self, headers=None, options=None, baseUrl='https://us-central1-rationale-ai.cloudfunctions.net'): 8 | defaultHeaders = { 9 | 'Content-Type': 'application/json', 10 | } 11 | mergedHeaders = defaultHeaders.update(headers) 12 | super().__init__(baseUrl=baseUrl, headers=defaultHeaders, options=options) 13 | 14 | def from_array(self, input, options=None): 15 | return { 16 | 'data': [ 17 | { 18 | 'decision': i[:MAXLEN], 19 | **(options or {}) 20 | } 21 | for i in input 22 | ] 23 | } 24 | 25 | def from_string(self, input, options=None): 26 | return { 27 | 'data': [ 28 | { 29 | 'decision': input[:MAXLEN], 30 | **(options or {}) 31 | } 32 | ] 33 | } 34 | 35 | def to_simplified_output(self, output): 36 | if 'result' not in output or 'result' not in output['result']: 37 | raise Exception('Remote API Error, bad output: ' + json.dumps(output)) 38 | return { 39 | 'results': [ 40 | { 41 | 'proscons': r['keyResults'] if r['analysis'] == 'proscons' else None, 42 | 'swot': r['keyResults'] if r['analysis'] == 'swot' else None, 43 | 'multichoice': r['keyResults'] if r['analysis'] == 'multichoice' else None, 44 | 'outcomes': r['keyResults'] if r['analysis'] == 'outcomes' else None, 45 | } 46 | for r in output['result']['result'] 47 | ] 48 | } 49 | 50 | def decide(self, data, options = None): 51 | raw_output = self.post('/analysisApi', data) 52 | simplified_output = self.to_simplified_output(raw_output) 53 | if options and 'raw' in options: 54 | simplified_output['raw'] = raw_output 55 | return simplified_output 56 | 57 | -------------------------------------------------------------------------------- /jinaai/clients/SceneXClient.py: -------------------------------------------------------------------------------- 1 | from .HTTPClient import HTTPClient 2 | import time 3 | 4 | def autoFillFeatures(options=None): 5 | features = options.get('features', []) if options else [] 6 | if options and 'question' in options and 'question_answer' not in features: 7 | features.append('question_answer') 8 | if options and 'json_schema' in options and 'json' not in features: 9 | features.append('json') 10 | return features 11 | 12 | class SceneXClient(HTTPClient): 13 | def __init__(self, headers=None, options=None, baseUrl='https://api.scenex.jina.ai/v1'): 14 | defaultHeaders = { 15 | 'Content-Type': 'application/json', 16 | } 17 | mergedHeaders = defaultHeaders.update(headers) 18 | super().__init__(baseUrl=baseUrl, headers=defaultHeaders, options=options) 19 | 20 | def from_array(self, input, options=None): 21 | return { 22 | 'data': [ 23 | { 24 | 'image': i, 25 | **({"video": i} if options and options.get("algorithm") == "Inception" else {}), 26 | 'features': autoFillFeatures(options), 27 | **(options or {}) 28 | } 29 | for i in input 30 | ] 31 | } 32 | 33 | def from_string(self, input, options=None): 34 | return { 35 | 'data': [ 36 | { 37 | 'image': input, 38 | **({"video": input} if options and options.get("algorithm") == "Inception" else {}), 39 | 'features': autoFillFeatures(options), 40 | **(options or {}) 41 | } 42 | ] 43 | } 44 | 45 | def to_simplified_output(self, output): 46 | if not output.get('result'): 47 | raise Exception('Remote API Error, bad output: {}'.format(json.dumps(output))) 48 | return { 49 | 'results': [ 50 | { 51 | 'output': r['answer'] if 'answer' in r and r['answer'] is not None else (r['text'] if 'text' in r else 'Processing...'), 52 | 'i18n': r['i18n'] if "i18n" in r else None, 53 | "tts": r["tts"] if "tts" in r else None, 54 | "ssml": r["dialog"]["ssml"] if r.get("dialog") and "ssml" in r["dialog"] else None 55 | 56 | } 57 | for r in output['result'] 58 | ] 59 | } 60 | 61 | def describe_video(self, output, options = None): 62 | for i, scene in enumerate(output["result"]): 63 | raw_output = None 64 | is_done = False 65 | while is_done is False: 66 | raw_output = self.get(f"/scene/{scene['id']}") 67 | if raw_output["result"]["data"]["status"] != "pending": 68 | is_done = True 69 | time.sleep(10) 70 | if raw_output: 71 | output["result"][i] = raw_output["result"]["data"] 72 | return output 73 | 74 | def describe(self, data, options = None): 75 | raw_output = self.post('/describe', data) 76 | if options and 'algorithm' in options and options['algorithm'] == 'Inception': 77 | raw_output = self.describe_video(raw_output, options) 78 | simplified_output = self.to_simplified_output(raw_output) 79 | if options and 'raw' in options: 80 | simplified_output['raw'] = raw_output 81 | return simplified_output 82 | 83 | -------------------------------------------------------------------------------- /jinaai/clients/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jina-ai/jinaai-py/a3e0138db76f3b3f0cbf8cd8d60e297224e37fb5/jinaai/clients/__init__.py -------------------------------------------------------------------------------- /jinaai/utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import mimetypes 3 | import os 4 | import re 5 | from typing import List, Dict, Optional 6 | 7 | def is_url(string): 8 | url_pattern = r'^(?:\w+:)?\/\/([^\s.]+\.\S{2}|localhost[:?\d]*)\S*$' 9 | return bool(re.match(url_pattern, string)) 10 | 11 | def is_base64(string): 12 | base64_pattern = r'^data:[A-Za-z0-9+/]+;base64,' 13 | return bool(re.match(base64_pattern, string)) 14 | 15 | def image_to_base64(file_path): 16 | try: 17 | with open(file_path, 'rb') as file: 18 | file_data = file.read() 19 | base64_data = base64.b64encode(file_data).decode('utf-8') 20 | mime_type = get_mime_type(file_path) 21 | base64_string = f"data:{mime_type};base64,{base64_data}" 22 | return base64_string 23 | except Exception as error: 24 | raise Exception(f"Image to base64 error: {str(error)}") 25 | 26 | def get_mime_type(file_path): 27 | mime_type, _ = mimetypes.guess_type(file_path) 28 | return mime_type or 'application/octet-stream' 29 | 30 | def omit(d: Dict, key: str) -> Dict: 31 | if d is None: 32 | return {} 33 | return {k: v for k, v in d.items() if k != key} 34 | 35 | def filter_args(**kwargs): 36 | return {k: v for k, v in kwargs.items() if v is not None} 37 | 38 | -------------------------------------------------------------------------------- /scripts/publish.sh: -------------------------------------------------------------------------------- 1 | rm -rf dist 2 | python3 setup.py sdist bdist_wheel 3 | twine upload dist/* -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | import pathlib 3 | 4 | HERE = pathlib.Path(__file__).parent 5 | README = (HERE / "README.md").read_text() 6 | 7 | setup( 8 | name='jinaai', 9 | version='0.2.10', 10 | author='Jina AI', 11 | author_email='guillaume.roncari@jina.ai', 12 | description='Jina AI Python SDK', 13 | url='https://github.com/jina-ai/jinaai-py.git', 14 | packages=find_packages(), 15 | install_requires=[ 16 | 'requests', 17 | ], 18 | long_description=README, 19 | long_description_content_type='text/markdown', 20 | ) 21 | -------------------------------------------------------------------------------- /tests/mock/HTTPClientMock.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import patch 2 | import json 3 | import time 4 | from .responses.SceneXResponse import SceneXResponse 5 | from .responses.PromptPerfectResponse import PromptPerfectResponse 6 | from .responses.RationaleResponse import RationaleResponse 7 | from .responses.JinaChatResponse import JinaChatResponse 8 | from .responses.BestBannerResponse import BestBannerResponse 9 | 10 | def loadJsonResponse(filename): 11 | with open("mock/responses/" + filename, "r") as file: 12 | return json.load(file) 13 | 14 | AuthKOResponse = loadJsonResponse("Auth.KO.response.json") 15 | NotImplementedResponse = loadJsonResponse("NotImplemented.response.json") 16 | 17 | def hasAuthHeader (headers): 18 | if "x-api-key" in headers and headers["x-api-key"] != "": 19 | return True 20 | if "authorization" in headers and headers["authorization"] != "": 21 | return True 22 | return False 23 | 24 | def post(self, url, data): 25 | if hasAuthHeader(self.headers) == False: 26 | responseData = AuthKOResponse 27 | else: 28 | if url == "/describe": 29 | responseData = SceneXResponse(data) 30 | elif url == "/analysisApi": 31 | responseData = RationaleResponse(data) 32 | elif url == "/optimizeBatch": 33 | responseData = PromptPerfectResponse(data) 34 | elif url == "/completions": 35 | responseData = JinaChatResponse(data) 36 | elif url == "/generate": 37 | responseData = BestBannerResponse(data) 38 | else: 39 | responseData = NotImplementedResponse 40 | if "error" in responseData: 41 | raise Exception(responseData["error"]) 42 | return responseData 43 | 44 | def mock_post_method(xClient): 45 | return patch.object(xClient.__class__, "post", post) -------------------------------------------------------------------------------- /tests/mock/responses/Auth.KO.response.json: -------------------------------------------------------------------------------- 1 | { 2 | "error": { 3 | "message": "No token provided", 4 | "status": "UNAUTHENTICATED" 5 | } 6 | } -------------------------------------------------------------------------------- /tests/mock/responses/BestBannerResponse.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def BestBannerResponse(input): 4 | return { 5 | 'result': [ 6 | { 7 | 'id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i), 8 | 'userId': 'zoyqq4zkwdZLiBgH0eyhx4fcN9b2', 9 | 'text': e['text'], 10 | 'plainText': None, 11 | 'title': 'Skyrocket Your Productivity: Unlock Success in Fast-Paced Times\n', 12 | 'style': None, 13 | 'description': "Master the art of time management to thrive in today's rapid world.", 14 | 'resolution': { 15 | 'width': 1024, 16 | 'height': 1024 17 | }, 18 | 'banners': [{ 19 | 'id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i), 20 | 'url': 'https://picsum.photos/1024' 21 | } for _ in range(4)], 22 | 'createdAt': { 23 | 'nanoseconds': 821654000, 24 | 'seconds': 1688627912 25 | }, 26 | 'status': 'SUCCESS', 27 | 'metaData': {} 28 | } 29 | for i, e in enumerate(input["data"]) 30 | ] 31 | } -------------------------------------------------------------------------------- /tests/mock/responses/JinaChatResponse.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def JinaChatResponse(input): 4 | return { 5 | 'chatId': input.get('chatId', 'aaaaaaaaaaaaaaaaaaaaaaaaaaa'), 6 | 'inputMessageId': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa', 7 | 'responseMessageId': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa', 8 | 'choices': [{ 9 | 'index': 0, 10 | 'message': { 11 | 'role': 'assistant', 12 | 'content': '-'.join([message['content'] for message in input['messages']]) 13 | }, 14 | 'finish_reason': 'stop' 15 | }], 16 | 'usage': { 17 | 'prompt_tokens': 7, 18 | 'completion_tokens': 18, 19 | 'total_tokens': 25 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tests/mock/responses/NotImplemented.response.json: -------------------------------------------------------------------------------- 1 | { 2 | "error": { 3 | "message": "Not implemented" 4 | } 5 | } -------------------------------------------------------------------------------- /tests/mock/responses/PromptPerfectResponse.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def PromptPerfectResponse(input): 4 | return { 5 | 'result': [ 6 | { 7 | 'prompt': e.get('prompt') or e.get('imagePrompt') or '', 8 | 'imagePrompt': e.get('imagePrompt') or None, 9 | 'targetModel': e['targetModel'], 10 | 'features': e['features'], 11 | 'iterations': e.get('iterations', 1), 12 | 'previewSettings': e.get('previewSettings', {}), 13 | 'previewVariables': e.get('previewVariables', {}), 14 | 'timeout': e.get('timeout', 20000), 15 | 'targetLanguage': e.get('target_language'), 16 | 'promptOptimized': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 17 | 'credits': 1, 18 | 'language': e.get('target_language', 'en'), 19 | 'intermediateResults': [{ 20 | 'promptOptimized': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 21 | 'explain': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 22 | }], 23 | 'explain': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 24 | 'createdAt': int(time.time() * 1000), 25 | 'userId': 'zoyqq4zkwdZLiBgH0eyhx4fcN9b2', 26 | 'id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i) 27 | } 28 | for i, e in enumerate(input["data"]) 29 | ] 30 | } -------------------------------------------------------------------------------- /tests/mock/responses/RationaleResponse.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | ProsConsOutput = { 4 | 'pros': { 5 | 'Lorem': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 6 | }, 7 | 'cons': { 8 | 'Ipsum': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 9 | }, 10 | 'bestChoice': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 11 | 'conclusion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 12 | 'confidenceScore': 1 13 | } 14 | 15 | SWOTOutput = { 16 | 'strengths': { 17 | 'Lorem': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 18 | }, 19 | 'weaknesses': { 20 | 'Ipsum': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 21 | }, 22 | 'opportunities': { 23 | 'Dolor': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 24 | }, 25 | 'threats': { 26 | 'Sit': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 27 | }, 28 | 'bestChoice': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 29 | 'conclusion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 30 | 'confidenceScore': 1 31 | } 32 | 33 | MultichoiceOutput = { 34 | 'Lorem': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 35 | 'Ipsum': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 36 | 'Dolor': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 37 | } 38 | 39 | OutcomesOutput = [ 40 | { 41 | 'children': [], 42 | 'labal': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 43 | 'sentiment': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 44 | } 45 | ] 46 | 47 | def RationaleResponse(input): 48 | return { 49 | 'result': { 50 | 'result': [ 51 | { 52 | 'decision': e['decision'], 53 | 'decisionUserQuery': e['decision'], 54 | 'writingStyle': e.get('style', 'concise'), 55 | 'hasUserProfile': False, 56 | 'analysis': e.get('analysis', 'proscons'), 57 | 'sourceLang': 'en', 58 | 'keyResults': SWOTOutput if e.get('analysis') == 'swot' else MultichoiceOutput if e.get('analysis') == 'multichoice' else OutcomesOutput if e.get('analysis') == 'outcomes' else ProsConsOutput, 59 | 'keyResultsConclusion': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 60 | 'keyResultsBestChoice': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.', 61 | 'confidence': 1, 62 | 'createdAt': int(time.time() * 1000), 63 | 'profileId': None, 64 | 'isQuality': False, 65 | 'nonGibberish': False, 66 | 'id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i) 67 | } 68 | for i, e in enumerate(input['data']) 69 | ] 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /tests/mock/responses/SceneXResponse.py: -------------------------------------------------------------------------------- 1 | import time 2 | import json 3 | 4 | DESC = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec convallis ipsum est, et iaculis lacus tincidunt eget. Sed dictum diam ex, eget aliquam urna porta a.' 5 | 6 | def getDesc(e): 7 | if e.get('output_length'): 8 | return DESC[:e['output_length']] 9 | if e.get('json_schema'): 10 | return json.dumps(e['json_schema']) 11 | return DESC 12 | 13 | 14 | def SceneXResponse(input): 15 | return { 16 | 'result': [ 17 | { 18 | 'id': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i), 19 | 'image': e['image'], 20 | 'features': e['features'], 21 | 'uid': 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' + str(i), 22 | 'algorithm': e.get('algorithm', 'Aqua'), 23 | 'text': DESC, 24 | 'userId': 'zoyqq4zkwdZLiBgH0eyhx4fcN9b2', 25 | 'createdAt': int(time.time() * 1000), 26 | 'optOut': True if 'opt-out' in e['features'] else False, 27 | 'i18n': { 28 | l: getDesc(e) for l in e.get('languages', ['en']) 29 | } if e.get('algorithm', 'Aqua') != 'Hearth' else { 30 | l: [{ 31 | 'isNarrator': True, 32 | 'message': getDesc(e), 33 | 'name': 'Narrator' 34 | }, 35 | { 36 | 'isNarrator': False, 37 | 'message': getDesc(e), 38 | 'name': 'BobbyBoy' 39 | }] for l in e.get('languages', ['en']) 40 | }, 41 | 'answer': DESC if 'question_answer' in e['features'] else None, 42 | 'tts': { 43 | l: f"https://someurl/to/the/{l}/tts/file" for l in e.get('languages', ['en']) 44 | } if e.get('algorithm', 'Aqua') == 'Hearth' else None, 45 | 'dialog': { 46 | 'names': ['Narrator', 'BobbyBoy'], 47 | 'ssml': { 48 | l: f"https://someurl/to/the/{l}/ssml/file" for l in e.get('languages', ['en']) 49 | } 50 | } if e.get('algorithm', 'Aqua') == 'Hearth' else None, 51 | } 52 | for i, e in enumerate(input["data"]) 53 | ] 54 | } -------------------------------------------------------------------------------- /tests/real-cases/test_ex1-factory.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 13 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 14 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 15 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', ''), 16 | 'bestbanner-secret': os.environ.get('BESTBANNER_SECRET', '') 17 | } 18 | ) 19 | 20 | situations = [jinaai.utils.image_to_base64(f"../../examples/images/{img}") for img in [ 21 | 'factory-2.png', 22 | 'factory-3.png', 23 | 'factory-4.png', 24 | ]] 25 | 26 | descriptions = None 27 | analysis = None 28 | recommendation = None 29 | swot = None 30 | banners = None 31 | 32 | def test_scenex_get_descriptions(): 33 | global descriptions 34 | descriptions = jinaai.describe(situations) 35 | results = descriptions['results'] 36 | assert results 37 | assert len(results) == 3 38 | for i, desc in enumerate(descriptions['results']): 39 | assert len(results[i]['output']) > 0 40 | print(f"DESCRIPTION {i + 1}:\n{desc['output']}\n") 41 | 42 | def test_jinachat_get_analysis(): 43 | global analysis 44 | assert descriptions 45 | analysis = jinaai.generate('\n'.join([ 46 | 'Does any of those situations present a danger?', 47 | 'Reply with [SITUATION_NUMBER] [YES] or [NO] and explain why', 48 | *['SITUATION ' + str(i + 1) + ':\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 49 | ])) 50 | print('ANALYSIS:\n', analysis['output']) 51 | assert analysis['output'] 52 | assert len(analysis['output']) > 0 53 | assert analysis['chatId'] 54 | 55 | def test_jinachat_get_recommendation(): 56 | global recommendation 57 | assert descriptions 58 | recommendation = jinaai.generate('\n'.join([ 59 | 'According to those situations, what should be done first to make everything safer?', 60 | 'I only want the most urgent situation', 61 | *['SITUATION ' + str(i + 1) + ':\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 62 | ])) 63 | print('RECOMMENDATION:\n', recommendation['output']) 64 | assert recommendation['output'] 65 | assert len(recommendation['output']) > 0 66 | assert recommendation['chatId'] 67 | 68 | 69 | def test_rationale_get_swot(): 70 | global swot 71 | assert recommendation 72 | swot = jinaai.decide( 73 | recommendation['output'], 74 | { 'analysis': 'swot' } 75 | ) 76 | print('SWOT:\n', swot['results'][0]['swot']) 77 | results = swot['results'] 78 | assert results 79 | assert len(results) == 1 80 | assert results[0]['swot'] 81 | 82 | def test_bestbanner_get_banners(): 83 | global banners 84 | assert descriptions 85 | banners = jinaai.imagine(descriptions['results'][0]['output']) 86 | print('BANNERS:\n', banners['results']) 87 | assert banners['results'] 88 | assert len(banners['results']) == 1 89 | assert len(banners['results'][0]['output']) == 4 90 | -------------------------------------------------------------------------------- /tests/real-cases/test_ex2-fridge.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 13 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 14 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 15 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', ''), 16 | 'bestbanner-secret': os.environ.get('BESTBANNER_SECRET', '') 17 | } 18 | ) 19 | 20 | fridge = [jinaai.utils.image_to_base64(f"../../examples/images/{img}") for img in [ 21 | 'fridge-1.png', 22 | ]] 23 | 24 | descriptions = None 25 | prompt = None 26 | recipe = None 27 | swot = None 28 | banners = None 29 | 30 | def test_scenex_get_descriptions(): 31 | global descriptions 32 | descriptions = jinaai.describe( 33 | fridge, 34 | { 'question': 'What ingredients are in the fridge?', 'languages': ['en'] } 35 | ) 36 | print('DESCRIPTION:\n', descriptions['results'][0]['output']) 37 | assert descriptions['results'] 38 | assert len(descriptions['results']) == 1 39 | assert len(descriptions['results'][0]['output']) > 0 40 | 41 | def test_promptperfect_get_optiprompt(): 42 | global prompt 43 | assert descriptions 44 | prompt = jinaai.optimize('\n'.join([ 45 | 'Give me one recipe based on this list for ingredients', 46 | *['INGREDIENTS:\n' + desc['output'] for i, desc in enumerate(descriptions['results'])] 47 | ])) 48 | print('PROMPT:\n', prompt['results'][0]['output']) 49 | results = prompt['results'] 50 | assert results 51 | assert len(results) == 1 52 | assert len(results[0]['output']) > 0 53 | 54 | def test_jinachat_get_recipe(): 55 | global recipe 56 | assert prompt 57 | recipe = jinaai.generate(prompt['results'][0]['output']) 58 | print('RECIPE:\n', recipe['output']) 59 | assert recipe['output'] 60 | assert len(recipe['output']) > 0 61 | assert recipe['chatId'] 62 | 63 | def test_rationale_get_swot(): 64 | global swot 65 | assert recipe 66 | swot = jinaai.decide( 67 | recipe['output'], 68 | { 'analysis': 'swot' } 69 | ) 70 | print('SWOT:\n', swot['results'][0]['swot']) 71 | results = swot['results'] 72 | assert results 73 | assert len(results) == 1 74 | assert results[0]['swot'] 75 | 76 | def test_bestbanner_get_banners(): 77 | global banners 78 | assert recipe 79 | banners = jinaai.imagine(recipe['output']) 80 | print('BANNERS:\n', banners['results']) 81 | assert banners['results'] 82 | assert len(banners['results']) == 1 83 | assert len(banners['results'][0]['output']) == 4 84 | -------------------------------------------------------------------------------- /tests/real-cases/test_ex3-tweet.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'promptperfect-secret': os.environ.get('PROMPTPERFECT_SECRET', ''), 13 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 14 | 'rationale-secret': os.environ.get('RATIONALE_SECRET', ''), 15 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', '') 16 | } 17 | ) 18 | 19 | positiveMovieTweets = [ 20 | 'Just watched the new movie! The plot was incredible, and the visual effects were mind-blowing. Definitely a must-see! #movie #amazing', 21 | "I can't stop thinking about the movie. The acting was superb, and the twist at the end caught me off guard. Highly recommended! #movie #thriller", 22 | 'The cinematography in the movie was stunning. Every scene was like a work of art. #movie #cinema', 23 | 'The new movie is a rollercoaster of emotions. I laughed, I cried, and I was on the edge of my seat throughout the entire film. #movie #emotional', 24 | "Just came back from watching the movie, and I'm still speechless. It's a masterpiece! #movie #masterpiece", 25 | "If you're looking for a good movie to watch, I highly recommend this one. It has a compelling story and brilliant performances. #movie #recommendation", 26 | 'The movie exceeded my expectations. The pacing was perfect, and the characters were so well-developed. #movie #surprise', 27 | "I'm still trying to process what I just witnessed in the movie. It's unlike anything I've ever seen before. #movie #unique", 28 | "Can't get enough of the movie's soundtrack. It perfectly complements the visuals and adds so much depth to the film. #movie #soundtrack", 29 | "Just watched the movie with my friends, and we had a blast. It's entertaining from start to finish. #movie #fun" 30 | ] 31 | 32 | negativeMovieTweets = [ 33 | 'I just watched the new movie, and it was a complete disappointment. The plot was confusing, and the acting was terrible. #movie #disappointed', 34 | 'Save your money and skip this movie. It was boring and predictable. #movie #boring', 35 | "I don't understand the hype around this movie. It was overrated and not worth the ticket price. #movie #overrated", 36 | 'I had high expectations for this movie, but it fell flat. The storyline was weak, and the characters were poorly developed. #movie #letdown', 37 | 'I regret watching this movie. It was a waste of time. #movie #wasteoftime', 38 | "I can't believe I paid to see this movie. It was absolutely awful. #movie #awful", 39 | 'The movie was a disaster. The dialogue was cringe-worthy, and the special effects were laughable. #movie #disaster', 40 | 'I was bored throughout the entire movie. It lacked any excitement or originality. #movie #uninteresting', 41 | 'I was really looking forward to this movie, but it was a major letdown. The pacing was off, and the ending was unsatisfying. #movie #majorletdown', 42 | "I don't recommend this movie at all. It was a total mess and didn't make any sense. #movie #notrecommended" 43 | ] 44 | 45 | feeling = None 46 | 47 | def test_jinachat_get_feeling(): 48 | global feeling 49 | prompt = '\n'.join([ 50 | 'According to those tweets, is the general feeling positive or negative?', 51 | 'Reply by [POSITIVE] or [NEGATIVE]', 52 | *['TWEET:\n' + t for i, t in enumerate(positiveMovieTweets)] 53 | ]) 54 | feeling = jinaai.generate(prompt) 55 | print('GENERAL FEELING:', feeling['output']) 56 | assert feeling['output'] 57 | assert len(feeling['output']) > 0 58 | assert feeling['chatId'] 59 | assert 'POSITIVE' in feeling['output'] 60 | 61 | def test_jinachat_get_feeling(): 62 | global feeling 63 | prompt = '\n'.join([ 64 | 'According to those tweets, is the general feeling positive or negative?', 65 | 'Reply by [POSITIVE] or [NEGATIVE]', 66 | *['TWEET:\n' + t for i, t in enumerate(negativeMovieTweets)] 67 | ]) 68 | feeling = jinaai.generate(prompt) 69 | print('GENERAL FEELING:', feeling['output']) 70 | assert feeling['output'] 71 | assert len(feeling['output']) > 0 72 | assert feeling['chatId'] 73 | assert 'NEGATIVE' in feeling['output'] 74 | -------------------------------------------------------------------------------- /tests/real-cases/test_ex4-email.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'jinachat-secret': os.environ.get('JINACHAT_SECRET', '') 13 | } 14 | ) 15 | 16 | def test_jinachat_email_direct_response(): 17 | prompt = 'Compose a professional and courteous email to our valued customer, expressing sincere gratitude for their use of our products. Your email should convey appreciation and highlight specific reasons why their choice to utilize our products is valued and important. Please provide a warm and personalized message that makes the customer feel valued and appreciated. Additionally, be sure to include any relevant details or information about upcoming promotions, new products, or customer loyalty programs that may be of interest to the customer. Your email should be well-written, concise, and focused, while still conveying genuine gratitude and fostering a positive relationship with the customer.' 18 | email = jinaai.generate(prompt) 19 | print('EMAIL: ', email['output']) 20 | assert email['output'] 21 | assert len(email['output']) > 0 22 | assert email['chatId'] 23 | 24 | def test_jinachat_email_stream_response(): 25 | prompt = 'Compose a professional and courteous email to our valued customer, expressing sincere gratitude for their use of our products. Your email should convey appreciation and highlight specific reasons why their choice to utilize our products is valued and important. Please provide a warm and personalized message that makes the customer feel valued and appreciated. Additionally, be sure to include any relevant details or information about upcoming promotions, new products, or customer loyalty programs that may be of interest to the customer. Your email should be well-written, concise, and focused, while still conveying genuine gratitude and fostering a positive relationship with the customer.' 26 | stream = jinaai.generate(prompt, { 'stream': True }) 27 | print('STREAM: ', stream) 28 | loopCounter = 0 29 | for line in stream.iter_lines(): 30 | if line: 31 | print('CHUNK: ', line.decode('utf-8')) 32 | loopCounter = loopCounter + 1 33 | assert loopCounter > 1 34 | -------------------------------------------------------------------------------- /tests/real-cases/test_ex5-story.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 13 | } 14 | ) 15 | 16 | fridge = [jinaai.utils.image_to_base64(f"../../examples/images/{img}") for img in [ 17 | 'fridge-1.png', 18 | ]] 19 | 20 | def test_scenex_get_descriptions(): 21 | descriptions = jinaai.describe( 22 | fridge, 23 | { 'question': 'What ingredients are in the fridge?', 'algorithm': 'Hearth','languages': ['en'] } 24 | ) 25 | print('DESCRIPTION:\n', descriptions['results'][0]['output']) 26 | assert descriptions['results'] 27 | assert len(descriptions['results']) == 1 28 | assert len(descriptions['results'][0]['output']) > 0 29 | assert descriptions["results"][0]["tts"].get("en") 30 | assert descriptions["results"][0]["ssml"].get("en") 31 | print("TTS: ", descriptions["results"][0]["tts"]["en"]) 32 | print("SSML: ", descriptions["results"][0]["ssml"]["en"]) 33 | assert descriptions["results"][0]["i18n"]["en"] 34 | assert len(descriptions["results"][0]["i18n"]["en"]) > 0 35 | assert descriptions["results"][0]["i18n"]["en"][0]['message'] 36 | for line in descriptions["results"][0]["i18n"]["en"]: 37 | print(line["name"], ": ", line["message"]) 38 | -------------------------------------------------------------------------------- /tests/real-cases/test_ex6-video.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | # THIS TEST USES REAL CREDITS 9 | 10 | jinaai = JinaAI( 11 | secrets = { 12 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 13 | } 14 | ) 15 | 16 | def test_scenex_analyse_video(): 17 | descriptions = jinaai.describe( 18 | 'https://guillaume-public.s3.us-east-2.amazonaws.com/videos/superman.mp4', 19 | { 20 | 'algorithm': 'Inception', 21 | 'languages': ['en'], 22 | } 23 | ) 24 | assert len(descriptions['results'][0]['output']) > 0 25 | assert descriptions['results'][0]["i18n"]["en"] 26 | assert descriptions['results'][0]["i18n"]["en"]['summary'] 27 | assert len(descriptions['results'][0]["i18n"]["en"]['events']) > 0 28 | print('SUMMARY: ', descriptions['results'][0]["i18n"]["en"]['summary']) 29 | print('EVENTS: ', descriptions['results'][0]["i18n"]["en"]['events']) 30 | -------------------------------------------------------------------------------- /tests/real-cases/text_ex7-json.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import os 4 | current_dir = os.path.dirname(os.path.abspath(__file__)) 5 | root_dir = os.path.abspath(os.path.join(current_dir, '../..')) 6 | sys.path.append(root_dir) 7 | from jinaai import JinaAI 8 | 9 | # THIS TEST USES REAL CREDITS 10 | 11 | jinaai = JinaAI( 12 | secrets = { 13 | 'scenex-secret': os.environ.get('SCENEX_SECRET', ''), 14 | } 15 | ) 16 | 17 | def test_scenex_json_output(): 18 | descriptions = jinaai.describe( 19 | 'https://picsum.photos/200', 20 | { 21 | 'algorithm': 'Jelly', 22 | 'languages': ['en'], 23 | 'json_schema': { 24 | 'type': 'object', 25 | 'properties': { 26 | 'headcount':{ 27 | 'type': 'number', 28 | 'description': 'How many people in this image' 29 | }, 30 | 'location':{ 31 | 'type': 'string', 32 | 'description': 'Short description of the location' 33 | } 34 | } 35 | } 36 | } 37 | ) 38 | assert len(descriptions['results'][0]['output']) > 0 39 | assert descriptions['results'][0]["i18n"]["en"] 40 | assert json.loads(descriptions['results'][0]["i18n"]["en"]) 41 | print('JSON: ', json.loads(descriptions['results'][0]["i18n"]["en"])) 42 | -------------------------------------------------------------------------------- /tests/test_authentication.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 6 | sys.path.append(root_dir) 7 | sys.path.append(mock_dir) 8 | from jinaai import JinaAI 9 | from mock.HTTPClientMock import mock_post_method 10 | 11 | def test_auth_ko_no_secret(): 12 | jinaai = JinaAI() 13 | with mock_post_method(jinaai.SXClient): 14 | try: 15 | jinaai.describe('https://picsum.photos/200') 16 | assert True == False 17 | except Exception as e: 18 | assert e.args[0]['message'] == 'No token provided' 19 | assert e.args[0]['status'] == 'UNAUTHENTICATED' 20 | 21 | def test_auth_ko_no_partial_secret(): 22 | jinaai = JinaAI( 23 | secrets={ 24 | 'promptperfect-secret': 'some-fake-secret', 25 | } 26 | ) 27 | with mock_post_method(jinaai.SXClient): 28 | try: 29 | jinaai.describe('https://picsum.photos/200') 30 | assert True == False 31 | except Exception as e: 32 | assert e.args[0]['message'] == 'No token provided' 33 | assert e.args[0]['status'] == 'UNAUTHENTICATED' 34 | 35 | def test_auth_ok(): 36 | jinaai = JinaAI( 37 | secrets={ 38 | 'promptperfect-secret': 'some-fake-secret', 39 | 'scenex-secret': 'some-fake-secret', 40 | 'rationale-secret': 'some-fake-secret', 41 | 'jinachat-secret': 'some-fake-secret', 42 | } 43 | ) 44 | with mock_post_method(jinaai.SXClient): 45 | r = jinaai.describe('https://picsum.photos/200') 46 | assert r["results"][0]["output"] and len(r["results"][0]["output"]) > 0 47 | 48 | def test_auth_ok_with_partial(): 49 | jinaai = JinaAI( 50 | secrets={ 51 | 'scenex-secret': 'some-fake-secret', 52 | } 53 | ) 54 | with mock_post_method(jinaai.SXClient): 55 | r = jinaai.describe('https://picsum.photos/200') 56 | assert r["results"][0]["output"] and len(r["results"][0]["output"]) > 0 57 | -------------------------------------------------------------------------------- /tests/test_baseurls.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | def test_default_urls(): 9 | jinaai = JinaAI() 10 | assert jinaai.PPClient.baseUrl == 'https://api.promptperfect.jina.ai' 11 | assert jinaai.SXClient.baseUrl == 'https://api.scenex.jina.ai/v1' 12 | assert jinaai.RAClient.baseUrl == 'https://us-central1-rationale-ai.cloudfunctions.net' 13 | assert jinaai.CCClient.baseUrl == 'https://api.chat.jina.ai/v1/chat' 14 | assert jinaai.BBClient.baseUrl == 'https://api.bestbanner.jina.ai/v1' 15 | 16 | def test_customs_urls(): 17 | jinaai = JinaAI( 18 | baseUrls={ 19 | 'promptperfect': 'https://promptperfect-customurl.jina.ai', 20 | 'scenex': 'https://scenex-customurl.jina.ai', 21 | 'rationale': 'https://rationale-customurl.jina.ai', 22 | 'jinachat': 'https://jinachat-customurl.jina.ai', 23 | 'bestbanner': 'https://bestbanner-customurl.jina.ai', 24 | } 25 | ) 26 | assert jinaai.PPClient.baseUrl == 'https://promptperfect-customurl.jina.ai' 27 | assert jinaai.SXClient.baseUrl == 'https://scenex-customurl.jina.ai' 28 | assert jinaai.RAClient.baseUrl == 'https://rationale-customurl.jina.ai' 29 | assert jinaai.CCClient.baseUrl == 'https://jinachat-customurl.jina.ai' 30 | assert jinaai.BBClient.baseUrl == 'https://bestbanner-customurl.jina.ai' 31 | 32 | -------------------------------------------------------------------------------- /tests/test_bestbanner.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 6 | sys.path.append(root_dir) 7 | sys.path.append(mock_dir) 8 | from jinaai import JinaAI 9 | from mock.HTTPClientMock import mock_post_method 10 | 11 | jinaai = JinaAI( 12 | secrets={ 13 | 'promptperfect-secret': 'some-fake-secret', 14 | 'scenex-secret': 'some-fake-secret', 15 | 'rationale-secret': 'some-fake-secret', 16 | 'jinachat-secret': 'some-fake-secret', 17 | 'bestbanner-secret': 'some-fake-secret', 18 | } 19 | ) 20 | 21 | def test_default_input(): 22 | with mock_post_method(jinaai.BBClient): 23 | input = [ 24 | 'In today\'s fast-paced environment, increasing productivity ...', 25 | 'When you have two days to finish a task ...' 26 | ] 27 | r1 = jinaai.imagine({ "data": [ 28 | { 29 | 'text': i, 30 | } 31 | for i in input 32 | ]}) 33 | results = r1['results'] 34 | assert results 35 | assert len(results) == 2 36 | assert len(results[0]['output']) == 4 37 | assert len(results[1]['output']) == 4 38 | 39 | def test_text_input(): 40 | with mock_post_method(jinaai.BBClient): 41 | input = 'In todays fast-paced environment, increasing productivity ...' 42 | r1 = jinaai.imagine(input) 43 | results = r1['results'] 44 | assert results 45 | assert len(results) == 1 46 | assert len(results[0]['output']) == 4 47 | r2 = jinaai.imagine(input, { 48 | 'style': 'flat', 49 | }) 50 | results = r2['results'] 51 | assert results 52 | assert len(results) == 1 53 | assert len(results[0]['output']) == 4 54 | 55 | def test_text_arr_input(): 56 | with mock_post_method(jinaai.BBClient): 57 | input = [ 58 | 'In today\'s fast-paced environment, increasing productivity ...', 59 | 'When you have two days to finish a task ...' 60 | ] 61 | r1 = jinaai.imagine(input) 62 | results = r1['results'] 63 | assert results 64 | assert len(results) == 2 65 | assert len(results[0]['output']) == 4 66 | assert len(results[1]['output']) == 4 67 | r2 = jinaai.imagine(input, { 68 | 'style': 'minimalist', 69 | }) 70 | results = r2['results'] 71 | assert results 72 | assert len(results) == 2 73 | assert len(results[0]['output']) == 4 74 | assert len(results[1]['output']) == 4 75 | 76 | def test_raw_output(): 77 | with mock_post_method(jinaai.BBClient): 78 | input = [ 79 | 'In today\'s fast-paced environment, increasing productivity ...', 80 | 'When you have two days to finish a task ...' 81 | ] 82 | r1 = jinaai.imagine(input, { 'raw': True }) 83 | r1_raw_result = r1['raw']['result'] 84 | assert r1_raw_result 85 | assert len(r1_raw_result) == 2 86 | assert r1_raw_result[0]['text'] == input[0] 87 | assert r1_raw_result[1]['text'] == input[1] 88 | assert len(r1_raw_result[0]['banners']) == 4 89 | assert len(r1_raw_result[1]['banners']) == 4 90 | r2 = jinaai.imagine(input, { 91 | 'style': 'photographic', 92 | 'raw': True 93 | }) 94 | r2_raw_result = r2['raw']['result'] 95 | assert r2_raw_result 96 | assert len(r2_raw_result) == 2 97 | assert r2_raw_result[0]['text'] == input[0] 98 | assert r2_raw_result[1]['text'] == input[1] 99 | assert len(r2_raw_result[0]['banners']) == 4 100 | assert len(r2_raw_result[1]['banners']) == 4 101 | -------------------------------------------------------------------------------- /tests/test_chatcat.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 6 | sys.path.append(root_dir) 7 | sys.path.append(mock_dir) 8 | from jinaai import JinaAI 9 | from mock.HTTPClientMock import mock_post_method 10 | 11 | jinaai = JinaAI( 12 | secrets={ 13 | 'promptperfect-secret': 'some-fake-secret', 14 | 'scenex-secret': 'some-fake-secret', 15 | 'rationale-secret': 'some-fake-secret', 16 | 'jinachat-secret': 'some-fake-secret', 17 | } 18 | ) 19 | 20 | def test_default_input(): 21 | with mock_post_method(jinaai.CCClient): 22 | input_data = ['Give me an Hello World function in Typescript'] 23 | r1_input_messages = [{'role': 'user', 'content': i} for i in input_data] 24 | r1 = jinaai.generate({'messages': r1_input_messages}) 25 | assert r1['output'] 26 | assert len(r1['output']) > 0 27 | assert r1['chatId'] == 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' 28 | r2_input_messages = [{'role': 'user', 'content': i} for i in input_data] 29 | r2 = jinaai.generate({'messages': r2_input_messages, 'chatId': '1234567890'}) 30 | assert r2['output'] 31 | assert len(r2['output']) > 0 32 | assert r2['chatId'] == '1234567890' 33 | 34 | def test_text_input(): 35 | with mock_post_method(jinaai.CCClient): 36 | input_data = 'Give me an Hello World function in Typescript' 37 | r1 = jinaai.generate(input_data) 38 | assert r1['output'] 39 | assert len(r1['output']) > 0 40 | assert r1['chatId'] == 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' 41 | r2 = jinaai.generate(input_data, {'chatId': '1234567890'}) 42 | assert r2['output'] 43 | assert len(r2['output']) > 0 44 | assert r2['chatId'] == '1234567890' 45 | 46 | def test_text_with_img_input(): 47 | with mock_post_method(jinaai.CCClient): 48 | input_data = 'What could I do with this?' 49 | url = 'https://picsum.photos/200' 50 | r1 = jinaai.generate(input_data, { 'image': url }) 51 | assert r1['output'] 52 | assert len(r1['output']) > 0 53 | assert r1['chatId'] == 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' 54 | 55 | def test_text_arr_input(): 56 | with mock_post_method(jinaai.CCClient): 57 | input_data = [ 58 | 'Give me an Hello World function in Typescript', 59 | 'Make it take an optional param NAME and replace world by NAME if set' 60 | ] 61 | r1 = jinaai.generate(input_data) 62 | assert r1['output'] 63 | assert len(r1['output']) > 0 64 | assert r1['chatId'] == 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' 65 | r2 = jinaai.generate(input_data, {'chatId': '1234567890'}) 66 | assert r2['output'] 67 | assert len(r2['output']) > 0 68 | assert r2['chatId'] == '1234567890' 69 | 70 | def test_raw_output(): 71 | with mock_post_method(jinaai.CCClient): 72 | input_data = 'Give me an Hello World function in Typescript' 73 | r1 = jinaai.generate(input_data, {'raw': True}) 74 | raw_response = r1['raw'] 75 | assert raw_response['choices'] 76 | assert len(raw_response['choices']) > 0 77 | assert len(raw_response['choices'][0]['message']['content']) > 0 78 | assert len(raw_response['choices'][0]['finish_reason']) > 0 79 | assert raw_response['usage'] 80 | assert raw_response['usage']['prompt_tokens'] 81 | assert raw_response['usage']['completion_tokens'] 82 | assert raw_response['usage']['total_tokens'] 83 | assert raw_response['chatId'] == 'aaaaaaaaaaaaaaaaaaaaaaaaaaa' 84 | -------------------------------------------------------------------------------- /tests/test_promptperfect.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 6 | sys.path.append(root_dir) 7 | sys.path.append(mock_dir) 8 | from jinaai import JinaAI 9 | from mock.HTTPClientMock import mock_post_method 10 | 11 | jinaai = JinaAI( 12 | secrets={ 13 | 'promptperfect-secret': 'some-fake-secret', 14 | 'scenex-secret': 'some-fake-secret', 15 | 'rationale-secret': 'some-fake-secret', 16 | 'jinachat-secret': 'some-fake-secret', 17 | } 18 | ) 19 | 20 | def test_default_input(): 21 | with mock_post_method(jinaai.PPClient): 22 | input = ['Give me an Hello World function in Typescript'] 23 | r1 = jinaai.optimize({ "data": [ 24 | { 25 | 'prompt': i, 26 | 'targetModel': 'chatgpt', 27 | 'features': [], 28 | 'target_language': 'it' 29 | } for i in input 30 | ]}) 31 | results = r1['results'] 32 | assert results 33 | assert len(results) == 1 34 | assert len(results[0]['output']) > 0 35 | 36 | def test_string_input(): 37 | with mock_post_method(jinaai.PPClient): 38 | input1 = 'Give me an Hello World function in Typescript' 39 | input2 = 'https://picsum.photos/200' 40 | r1 = jinaai.optimize(input1) 41 | results = r1['results'] 42 | assert results 43 | assert len(results) == 1 44 | assert len(results[0]['output']) > 0 45 | r2 = jinaai.optimize(input2, { 46 | 'targetModel': 'dalle', 47 | 'features': ['shorten'], 48 | 'target_language': 'fr' 49 | }) 50 | results = r2['results'] 51 | assert results 52 | assert len(results) == 1 53 | assert len(results[0]['output']) > 0 54 | 55 | def test_arr_input(): 56 | with mock_post_method(jinaai.PPClient): 57 | input = ['Give me an Hello World function in Typescript', 'https://picsum.photos/300'] 58 | r1 = jinaai.optimize(input) 59 | results = r1['results'] 60 | assert results 61 | assert len(results) == 2 62 | assert len(results[0]['output']) > 0 63 | assert len(results[1]['output']) > 0 64 | r2 = jinaai.optimize(input, { 65 | 'targetModel': 'dalle', 66 | 'features': ['shorten'], 67 | 'target_language': 'fr' 68 | }) 69 | results = r2['results'] 70 | assert results 71 | assert len(results) == 2 72 | assert len(results[0]['output']) > 0 73 | assert len(results[1]['output']) > 0 74 | 75 | def test_raw_output(): 76 | with mock_post_method(jinaai.PPClient): 77 | input1 = 'Give me an Hello World function in Typescript' 78 | input2 = 'https://picsum.photos/200' 79 | r1 = jinaai.optimize(input1, { 'raw': True }) 80 | assert r1['raw']['result'] 81 | assert len(r1['raw']['result']) == 1 82 | assert r1['raw']['result'][0]['prompt'] == input1 83 | assert not r1['raw']['result'][0]['imagePrompt'] 84 | assert len(r1['raw']['result'][0]['features']) == 0 85 | assert r1['raw']['result'][0]['targetModel'] == 'chatgpt' 86 | assert r1['raw']['result'][0]['promptOptimized'] 87 | assert r1['raw']['result'][0]['language'] == 'en' 88 | assert not r1['raw']['result'][0]['targetLanguage'] 89 | r2 = jinaai.optimize(input2, { 90 | 'raw': True, 91 | 'target_language': 'it', 92 | 'targetModel': 'claude', 93 | 'features': ['shorten', 'high_quality'] 94 | }) 95 | assert r2['raw']['result'] 96 | assert len(r2['raw']['result']) == 1 97 | assert len(r2['raw']['result'][0]['prompt']) > 0 98 | assert r2['raw']['result'][0]['imagePrompt'] == input2 99 | assert len(r2['raw']['result'][0]['features']) == 2 100 | assert r2['raw']['result'][0]['targetModel'] == 'claude' 101 | assert r2['raw']['result'][0]['promptOptimized'] 102 | assert r2['raw']['result'][0]['language'] == 'it' 103 | assert r2['raw']['result'][0]['targetLanguage'] == 'it' 104 | -------------------------------------------------------------------------------- /tests/test_rationale.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 6 | sys.path.append(root_dir) 7 | sys.path.append(mock_dir) 8 | from jinaai import JinaAI 9 | from mock.HTTPClientMock import mock_post_method 10 | 11 | jinaai = JinaAI( 12 | secrets={ 13 | 'promptperfect-secret': 'some-fake-secret', 14 | 'scenex-secret': 'some-fake-secret', 15 | 'rationale-secret': 'some-fake-secret', 16 | 'jinachat-secret': 'some-fake-secret', 17 | } 18 | ) 19 | 20 | def test_default_input(): 21 | with mock_post_method(jinaai.RAClient): 22 | input = ['Going to Paris this summer'] 23 | r1 = jinaai.decide({ "data": [ 24 | { 25 | 'decision': i, 26 | 'analysis': 'swot', 27 | 'style': 'concise' 28 | } for i in input 29 | ]}) 30 | results = r1['results'] 31 | assert results 32 | assert len(results) == 1 33 | assert not r1['results'][0]['proscons'] 34 | assert r1['results'][0]['swot'] 35 | assert not r1['results'][0]['multichoice'] 36 | assert not r1['results'][0]['outcomes'] 37 | r1KeyResults = r1['results'][0]['swot'] 38 | assert r1KeyResults['strengths'] 39 | assert r1KeyResults['weaknesses'] 40 | assert r1KeyResults['opportunities'] 41 | assert r1KeyResults['threats'] 42 | 43 | def test_text_input(): 44 | with mock_post_method(jinaai.RAClient): 45 | input = 'Going to Paris this summer' 46 | r1 = jinaai.decide(input) 47 | assert r1['results'] 48 | assert len(r1['results']) == 1 49 | assert r1['results'][0]['proscons'] 50 | assert not r1['results'][0]['swot'] 51 | assert not r1['results'][0]['multichoice'] 52 | assert not r1['results'][0]['outcomes'] 53 | r1KeyResults = r1['results'][0]['proscons'] 54 | assert r1KeyResults['pros'] 55 | assert r1KeyResults['cons'] 56 | r2 = jinaai.decide(input, { 57 | 'analysis': 'multichoice', 58 | 'style': 'genZ' 59 | }) 60 | assert r2['results'] 61 | assert len(r2['results']) == 1 62 | assert not r2['results'][0]['proscons'] 63 | assert not r2['results'][0]['swot'] 64 | assert r2['results'][0]['multichoice'] 65 | assert not r2['results'][0]['outcomes'] 66 | r2KeyResults = r2['results'][0]['multichoice'] 67 | assert len(r2KeyResults) == 3 68 | 69 | 70 | def test_arr_input(): 71 | with mock_post_method(jinaai.RAClient): 72 | input = ['Going to Paris this summer', 'Going to Beijing this winter'] 73 | r1 = jinaai.decide(input) 74 | assert r1['results'] 75 | assert len(r1['results']) == 2 76 | assert r1['results'][0]['proscons'] 77 | assert not r1['results'][0]['swot'] 78 | assert not r1['results'][0]['multichoice'] 79 | assert not r1['results'][0]['outcomes'] 80 | assert r1['results'][1]['proscons'] 81 | assert not r1['results'][1]['swot'] 82 | assert not r1['results'][1]['multichoice'] 83 | assert not r1['results'][1]['outcomes'] 84 | r1KeyResults1 = r1['results'][0]['proscons'] 85 | assert r1KeyResults1['pros'] 86 | assert r1KeyResults1['cons'] 87 | r1KeyResults2 = r1['results'][1]['proscons'] 88 | assert r1KeyResults2['pros'] 89 | assert r1KeyResults2['cons'] 90 | r2 = jinaai.decide(input, { 91 | 'analysis': 'multichoice', 92 | 'style': 'genZ' 93 | }) 94 | assert r2['results'] 95 | assert len(r2['results']) == 2 96 | assert not r2['results'][0]['proscons'] 97 | assert not r2['results'][0]['swot'] 98 | assert r2['results'][0]['multichoice'] 99 | assert not r2['results'][0]['outcomes'] 100 | assert not r2['results'][1]['proscons'] 101 | assert not r2['results'][1]['swot'] 102 | assert r2['results'][1]['multichoice'] 103 | assert not r2['results'][1]['outcomes'] 104 | r2KeyResults1 = r2['results'][0]['multichoice'] 105 | assert len(r2KeyResults1) == 3 106 | r2KeyResults2 = r2['results'][1]['multichoice'] 107 | assert len(r2KeyResults2) == 3 108 | 109 | 110 | def test_raw_output(): 111 | with mock_post_method(jinaai.RAClient): 112 | input = ['Going to Paris this summer', 'Going to Beijing this winter'] 113 | r1 = jinaai.decide(input, { 'raw': True }) 114 | assert r1['raw']['result'] 115 | assert r1['raw']['result']['result'] 116 | assert len(r1['raw']['result']['result']) == 2 117 | assert r1['raw']['result']['result'][0]['decision'] == input[0] 118 | assert r1['raw']['result']['result'][1]['decision'] == input[1] 119 | assert r1['raw']['result']['result'][0]['writingStyle'] == 'concise' 120 | assert r1['raw']['result']['result'][1]['writingStyle'] == 'concise' 121 | assert r1['raw']['result']['result'][0]['analysis'] == 'proscons' 122 | assert r1['raw']['result']['result'][1]['analysis'] == 'proscons' 123 | r1KeyResults1 = r1['raw']['result']['result'][0]['keyResults'] 124 | assert r1KeyResults1['pros'] 125 | assert r1KeyResults1['cons'] 126 | r1KeyResults2 = r1['raw']['result']['result'][1]['keyResults'] 127 | assert r1KeyResults2['pros'] 128 | assert r1KeyResults2['cons'] 129 | r2 = jinaai.decide(input, { 130 | 'analysis': 'multichoice', 131 | 'style': 'genZ', 132 | 'raw': True 133 | }) 134 | assert r2['raw']['result'] 135 | assert r2['raw']['result']['result'] 136 | assert len(r2['raw']['result']['result']) == 2 137 | assert r2['raw']['result']['result'][0]['decision'] == input[0] 138 | assert r2['raw']['result']['result'][1]['decision'] == input[1] 139 | assert r2['raw']['result']['result'][0]['writingStyle'] == 'genZ' 140 | assert r2['raw']['result']['result'][1]['writingStyle'] == 'genZ' 141 | assert r2['raw']['result']['result'][0]['analysis'] == 'multichoice' 142 | assert r2['raw']['result']['result'][1]['analysis'] == 'multichoice' 143 | r2KeyResults1 = r2['raw']['result']['result'][0]['keyResults'] 144 | assert len(r2KeyResults1) == 3 145 | r2KeyResults2 = r2['raw']['result']['result'][1]['keyResults'] 146 | assert len(r2KeyResults2) == 3 147 | -------------------------------------------------------------------------------- /tests/test_scenex.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import os 4 | current_dir = os.path.dirname(os.path.abspath(__file__)) 5 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 6 | mock_dir = os.path.abspath(os.path.join(current_dir, './mock')) 7 | sys.path.append(root_dir) 8 | sys.path.append(mock_dir) 9 | from jinaai import JinaAI 10 | from mock.HTTPClientMock import mock_post_method 11 | 12 | jinaai = JinaAI( 13 | secrets={ 14 | 'promptperfect-secret': 'some-fake-secret', 15 | 'scenex-secret': 'some-fake-secret', 16 | 'rationale-secret': 'some-fake-secret', 17 | 'jinachat-secret': 'some-fake-secret', 18 | } 19 | ) 20 | 21 | def test_default_input(): 22 | with mock_post_method(jinaai.SXClient): 23 | input = ['https://picsum.photos/200'] 24 | r1 = jinaai.describe({ "data": [ 25 | { 26 | 'image': i, 27 | 'features': [], 28 | 'algorithm': 'Ember', 29 | 'languages': ['it'], 30 | 'style': 'concise' 31 | } for i in input 32 | ]}) 33 | results = r1['results'] 34 | assert results 35 | assert len(results) == 1 36 | assert len(results[0]['output']) > 0 37 | assert results[0]['i18n'].get('it') 38 | 39 | def test_image_url_input(): 40 | with mock_post_method(jinaai.SXClient): 41 | input = 'https://picsum.photos/200' 42 | r1 = jinaai.describe(input) 43 | results = r1['results'] 44 | assert results 45 | assert len(results) == 1 46 | assert len(results[0]['output']) > 0 47 | r2 = jinaai.describe(input, { 48 | 'features': ['high_quality'], 49 | 'algorithm': 'Comet', 50 | 'languages': ['fr', 'de'] 51 | }) 52 | results = r2['results'] 53 | assert results 54 | assert len(results) == 1 55 | assert len(results[0]['output']) > 0 56 | assert results[0]['i18n'].get('fr') 57 | assert results[0]['i18n'].get('de') 58 | 59 | def test_image_url_input_shortened_answer(): 60 | with mock_post_method(jinaai.SXClient): 61 | input = 'https://picsum.photos/200' 62 | r1 = jinaai.describe(input, { 'output_length': 50 }) 63 | results = r1['results'] 64 | assert results 65 | assert len(results) == 1 66 | assert len(results[0]['output']) > 0 67 | assert len(results[0]['output']) > 50 68 | assert results[0]['i18n'].get('en') 69 | assert len(results[0]['i18n']['en']) == 50 70 | r2 = jinaai.describe(input, { 71 | 'output_length': 50, 72 | 'languages': ['fr', 'de'] 73 | }) 74 | results = r2['results'] 75 | assert results 76 | assert len(results) == 1 77 | assert len(results[0]['output']) > 0 78 | assert len(results[0]['output']) > 50 79 | assert results[0]['i18n'].get('fr') 80 | assert len(results[0]['i18n']['fr']) == 50 81 | assert results[0]['i18n'].get('de') 82 | assert len(results[0]['i18n']['de']) == 50 83 | 84 | 85 | def test_image_url_input_json_answer(): 86 | with mock_post_method(jinaai.SXClient): 87 | input = 'https://picsum.photos/200' 88 | r1 = jinaai.describe(input, { 'json_schema': { 89 | 'type': 'object', 90 | 'properties': { 91 | 'headcount': { 92 | 'type': 'number', 93 | 'description': 'How many people in this image' 94 | } 95 | } 96 | } 97 | }) 98 | results = r1['results'] 99 | assert results 100 | assert len(results) == 1 101 | assert len(results[0]['output']) > 0 102 | assert len(results[0]['output']) > 50 103 | assert results[0]['i18n'].get('en') 104 | assert json.loads(results[0]['i18n']['en']) 105 | 106 | 107 | def test_image_url_input_heart_algo(): 108 | with mock_post_method(jinaai.SXClient): 109 | input = 'https://picsum.photos/200' 110 | r1 = jinaai.describe(input, { 'algorithm': 'Hearth' }) 111 | results = r1['results'] 112 | assert results 113 | assert len(results) == 1 114 | assert len(results[0]['output']) > 0 115 | assert results[0]['i18n'].get('en') 116 | assert len(results[0]['i18n']['en']) == 2 117 | assert len(results[0]['i18n']['en'][0]['message']) > 50 118 | assert results[0]['tts'].get('en') 119 | assert results[0]['ssml'].get('en') 120 | r2 = jinaai.describe(input, { 121 | 'algorithm': 'Hearth', 122 | 'output_length': 50, 123 | 'languages': ['fr', 'de'] 124 | }) 125 | results = r2['results'] 126 | assert results 127 | assert len(results) == 1 128 | assert len(results[0]['output']) > 0 129 | assert len(results[0]['output']) > 50 130 | assert results[0]['i18n'].get('fr') 131 | assert len(results[0]['i18n']['fr']) == 2 132 | assert len(results[0]['i18n']['fr'][0]['message']) == 50 133 | assert results[0]['i18n'].get('de') 134 | assert len(results[0]['i18n']['de']) == 2 135 | assert len(results[0]['i18n']['de'][0]['message']) == 50 136 | assert results[0]['tts'].get('fr') 137 | assert results[0]['ssml'].get('fr') 138 | assert results[0]['tts'].get('de') 139 | assert results[0]['ssml'].get('de') 140 | 141 | def test_image_url_arr_input(): 142 | with mock_post_method(jinaai.SXClient): 143 | input = ['https://picsum.photos/200', 'https://picsum.photos/300'] 144 | r1 = jinaai.describe(input) 145 | results = r1['results'] 146 | assert results 147 | assert len(results) == 2 148 | assert len(results[0]['output']) > 0 149 | assert len(results[1]['output']) > 0 150 | r2 = jinaai.describe(input, { 151 | 'features': ['high_quality'], 152 | 'algorithm': 'Dune', 153 | 'languages': ['fr'] 154 | }) 155 | results = r2['results'] 156 | assert results 157 | assert len(results) == 2 158 | assert len(results[0]['output']) > 0 159 | assert len(results[1]['output']) > 0 160 | assert results[0]['i18n'].get('fr') 161 | assert results[1]['i18n'].get('fr') 162 | 163 | def test_raw_output(): 164 | with mock_post_method(jinaai.SXClient): 165 | input = ['https://picsum.photos/200', 'https://picsum.photos/300'] 166 | r1 = jinaai.describe(input, { 'raw': True }) 167 | r1_raw_result = r1['raw']['result'] 168 | assert r1_raw_result 169 | assert len(r1_raw_result) == 2 170 | assert r1_raw_result[0]['image'] == input[0] 171 | assert r1_raw_result[1]['image'] == input[1] 172 | assert len(r1_raw_result[0]['features']) == 0 173 | assert r1_raw_result[0]['algorithm'] == 'Aqua' 174 | assert r1_raw_result[1]['algorithm'] == 'Aqua' 175 | assert r1_raw_result[0]['text'] 176 | assert r1_raw_result[1]['text'] 177 | assert not r1_raw_result[0]['answer'] 178 | assert not r1_raw_result[1]['answer'] 179 | assert r1_raw_result[0]['i18n'].get('en') 180 | assert r1_raw_result[1]['i18n'].get('en') 181 | r2 = jinaai.describe(input, { 182 | 'question': 'How many people are on this photo?', 183 | 'features': ['high_quality'], 184 | 'algorithm': 'Dune', 185 | 'languages': ['fr'], 186 | 'raw': True 187 | }) 188 | r2_raw_result = r2['raw']['result'] 189 | assert r2_raw_result 190 | assert len(r2_raw_result) == 2 191 | assert r2_raw_result[0]['image'] == input[0] 192 | assert r2_raw_result[1]['image'] == input[1] 193 | assert len(r2_raw_result[0]['features']) == 2 194 | assert len(r2_raw_result[1]['features']) == 2 195 | assert r2_raw_result[0]['features'][0] == 'high_quality' 196 | assert r2_raw_result[0]['features'][1] == 'question_answer' 197 | assert r2_raw_result[1]['features'][0] == 'high_quality' 198 | assert r2_raw_result[1]['features'][1] == 'question_answer' 199 | assert r2_raw_result[0]['algorithm'] == 'Dune' 200 | assert r2_raw_result[1]['algorithm'] == 'Dune' 201 | assert r2_raw_result[0]['text'] 202 | assert r2_raw_result[1]['text'] 203 | assert r2_raw_result[0]['answer'] 204 | assert r2_raw_result[1]['answer'] 205 | assert not r2_raw_result[0]['i18n'].get('en') 206 | assert not r2_raw_result[1]['i18n'].get('en') 207 | assert r2_raw_result[0]['i18n'].get('fr') 208 | assert r2_raw_result[1]['i18n'].get('fr') 209 | -------------------------------------------------------------------------------- /tests/test_utility.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | current_dir = os.path.dirname(os.path.abspath(__file__)) 4 | root_dir = os.path.abspath(os.path.join(current_dir, '..')) 5 | sys.path.append(root_dir) 6 | from jinaai import JinaAI 7 | 8 | jinaai = JinaAI() 9 | 10 | imageFile = '../examples/images/factory-1.png' 11 | imageUrl = 'https://picsum.photos/200' 12 | imageB64 = jinaai.utils.image_to_base64(imageFile) 13 | 14 | def test_is_url(): 15 | assert jinaai.utils.is_url(imageFile) == False 16 | assert jinaai.utils.is_url(imageUrl) == True 17 | assert jinaai.utils.is_url(imageB64) == False 18 | 19 | def test_is_base64(): 20 | assert jinaai.utils.is_base64(imageFile) == False 21 | assert jinaai.utils.is_base64(imageUrl) == False 22 | assert jinaai.utils.is_base64(imageB64) == True 23 | 24 | def test_image_to_base64(): 25 | assert jinaai.utils.is_base64(imageB64) == True 26 | --------------------------------------------------------------------------------