polymage 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
polymage-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: polymage
3
+ Version: 0.0.1
4
+ Summary: polymage : a multimodal agent python library
5
+ Author-email: Fabrice Gaillard <fgaillard@w3architect.com>
6
+ License: Apache 2.0
7
+ Requires-Python: >=3.13
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: groq>=0.37.1
11
+ Requires-Dist: instructor>=1.13.0
12
+ Requires-Dist: ollama>=0.6.1
13
+ Requires-Dist: openai>=2.9.0
14
+ Requires-Dist: pillow>=12.0.0
15
+ Requires-Dist: requests>=2.32.5
16
+ Dynamic: license-file
17
+
18
+ # Multimodal Agents Framework
19
+
20
+ A modular, platform-agnostic Python library to orchestrate multimodal AI agents across platforms
21
+ and models (Gemma, moondream, Flux, HiDream, etc.)
22
+
23
+ Can run both on Local platforms
24
+ - Ollama (https://ollama.com), available for macOS, Windows, and Linux
25
+ - LmStudio (https://lmstudio.ai), available for macOS, Windows, and Linux
26
+ - DrawThings (https://drawthings.ai), available only on macOS
27
+
28
+ And on Cloud platforms
29
+ - Groq (https://groq.com/)
30
+ - Cloudflare (https://developers.cloudflare.com/workers-ai/)
31
+
32
+
33
+ ## ✨ Features
34
+
35
+ - Define agents with prompts + multimodal inputs (image, audio, video, text)
36
+ - Run same agent on multiple platforms/models for comparison
37
+ - Workflow orchestration : just python scripts or tools like Apache Airflow
38
+
39
+ ## 🚀 Quick Start
40
+
41
+ ### Clone the repo
42
+
43
+ ```bash
44
+ # clone the repo
45
+ git clone
46
+ ```
47
+
48
+ ### Use uv to create a virtual environment (https://docs.astral.sh/uv/)
49
+
50
+ uv is the best tool to manage multiple python version and multiple virtual python environment on your machine
51
+
52
+ Installation guide at https://docs.astral.sh/uv/getting-started/installation/
53
+
54
+ ```bash
55
+ uv venv
56
+ ```
57
+
58
+
59
+
60
+
61
+ ---
62
+
63
+ Apache 2.0 License — Happy building! 🚀
@@ -0,0 +1,46 @@
1
+ # Multimodal Agents Framework
2
+
3
+ A modular, platform-agnostic Python library to orchestrate multimodal AI agents across platforms
4
+ and models (Gemma, moondream, Flux, HiDream, etc.)
5
+
6
+ Can run both on Local platforms
7
+ - Ollama (https://ollama.com), available for macOS, Windows, and Linux
8
+ - LmStudio (https://lmstudio.ai), available for macOS, Windows, and Linux
9
+ - DrawThings (https://drawthings.ai), available only on macOS
10
+
11
+ And on Cloud platforms
12
+ - Groq (https://groq.com/)
13
+ - Cloudflare (https://developers.cloudflare.com/workers-ai/)
14
+
15
+
16
+ ## ✨ Features
17
+
18
+ - Define agents with prompts + multimodal inputs (image, audio, video, text)
19
+ - Run same agent on multiple platforms/models for comparison
20
+ - Workflow orchestration : just python scripts or tools like Apache Airflow
21
+
22
+ ## 🚀 Quick Start
23
+
24
+ ### Clone the repo
25
+
26
+ ```bash
27
+ # clone the repo
28
+ git clone
29
+ ```
30
+
31
+ ### Use uv to create a virtual environment (https://docs.astral.sh/uv/)
32
+
33
+ uv is the best tool to manage multiple python version and multiple virtual python environment on your machine
34
+
35
+ Installation guide at https://docs.astral.sh/uv/getting-started/installation/
36
+
37
+ ```bash
38
+ uv venv
39
+ ```
40
+
41
+
42
+
43
+
44
+ ---
45
+
46
+ Apache 2.0 License — Happy building! 🚀
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "polymage"
7
+ version = "0.0.1"
8
+ authors = [
9
+ { name="Fabrice Gaillard", email="fgaillard@w3architect.com" },
10
+ ]
11
+ description = "polymage : a multimodal agent python library"
12
+ readme = "README.md"
13
+ license = {text = "Apache 2.0"}
14
+ requires-python = ">=3.13"
15
+ dependencies = [
16
+ "groq>=0.37.1",
17
+ "instructor>=1.13.0",
18
+ "ollama>=0.6.1",
19
+ "openai>=2.9.0",
20
+ "pillow>=12.0.0",
21
+ "requests>=2.32.5",
22
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,16 @@
1
+ from typing import Any
2
+
3
+ from omniagent.agent.agent import Agent
4
+
5
+
6
+ class InstructAgent(Agent):
7
+ def __init__(self, **kwargs):
8
+ super().__init__(**kwargs)
9
+
10
+
11
+ def run(self, prompt: str, **kwargs) -> Any:
12
+ platform=self.platform
13
+ model=self.model
14
+ system_prompt=self.system_prompt
15
+
16
+ return platform.generate(model=model, prompt=prompt, system_prompt=system_prompt, **kwargs)
@@ -0,0 +1,24 @@
1
+ from abc import ABC
2
+ from typing import Any, Optional
3
+
4
+ from omniagent.platform.platfom import Platform
5
+
6
+
7
+ class Agent(ABC):
8
+ def __init__(
9
+ self,
10
+ platform: Platform,
11
+ model: str,
12
+ system_prompt: Optional[str] = None,
13
+ ):
14
+ self.platform=platform
15
+ self.model=model
16
+ self.system_prompt=system_prompt or ""
17
+
18
+ def run(self, prompt: str, **kwargs) -> Any:
19
+ platform=self.platform
20
+ model=self.model
21
+ system_prompt=self.system_prompt
22
+
23
+ return platform.generate(model=model, prompt=prompt, system_prompt=system_prompt, **kwargs)
24
+
@@ -0,0 +1,75 @@
1
+ import base64
2
+ from io import BytesIO
3
+ from PIL import Image
4
+
5
+
6
+ def base64_to_image(base64_string) -> Image.Image:
7
+ """
8
+ Convert a base64 string to a PIL Image object.
9
+
10
+ Args:
11
+ base64_string (str): Base64 encoded image string
12
+
13
+ Returns:
14
+ PIL.Image.Image: The decoded image as a PIL Image object
15
+
16
+ Raises:
17
+ ValueError: If the base64 string is invalid or cannot be decoded
18
+ OSError: If the decoded data is not a valid image format
19
+ """
20
+ try:
21
+ # Remove data URL prefix if present (e.g., "data:image/png;base64,")
22
+ if base64_string.startswith('data:'):
23
+ # Find the comma and take everything after it
24
+ base64_string = base64_string.split(',', 1)[1]
25
+
26
+ # Decode the base64 string to bytes
27
+ image_bytes = base64.b64decode(base64_string)
28
+
29
+ # Create a BytesIO object from the decoded bytes
30
+ image_buffer = BytesIO(image_bytes)
31
+
32
+ # Open the image using PIL
33
+ image = Image.open(image_buffer)
34
+
35
+ # Load the image data to ensure it's valid
36
+ image.load()
37
+
38
+ return image
39
+
40
+ except OSError as e:
41
+ raise OSError(f"Invalid image data or unsupported format: {e}")
42
+
43
+
44
+ def image_to_base64(image, format='PNG') -> str:
45
+ """
46
+ Convert an image to a base64-encoded string.
47
+
48
+ Parameters:
49
+ image (str or PIL.Image.Image):
50
+ - If str: path to the image file.
51
+ - If PIL.Image.Image: an in-memory image object.
52
+ format (str):
53
+ The image format to use when encoding (e.g., 'PNG', 'JPEG').
54
+ Only used if input is a PIL Image object. Default is 'PNG'.
55
+
56
+ Returns:
57
+ str: Base64-encoded string of the image.
58
+
59
+ Raises:
60
+ FileNotFoundError: If image path does not exist.
61
+ ValueError: If input type is not supported.
62
+ """
63
+ if isinstance(image, str):
64
+ # Input is a file path
65
+ with open(image, "rb") as image_file:
66
+ encoded_str = base64.b64encode(image_file.read()).decode('utf-8')
67
+ elif isinstance(image, Image.Image):
68
+ # Input is a PIL Image object
69
+ buffered = BytesIO()
70
+ image.save(buffered, format=format)
71
+ encoded_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
72
+ else:
73
+ raise ValueError("Input must be a file path (str) or a PIL Image object.")
74
+
75
+ return encoded_str
@@ -0,0 +1,17 @@
1
+ from abc import ABC
2
+ from typing import Dict, Optional, Any
3
+
4
+
5
+ class Model(ABC):
6
+ name: str
7
+ type: str # e.g., "text2text", "text2image", "image2image"
8
+ default_params: Dict[str, Any]
9
+
10
+ def __init__(self, name: str, type: str, **overrides):
11
+ self.name = name
12
+ self.type = type
13
+ self.params = {**self.default_params, **overrides}
14
+
15
+ def get_payload(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
16
+ """Build platform-agnostic payload (agent may further modify)."""
17
+ raise NotImplementedError
@@ -0,0 +1,43 @@
1
+ import os
2
+ import random
3
+ import requests
4
+
5
+ from src.omniagent.platform.platfom import Platform
6
+
7
+
8
+ """
9
+ Clouflare provide AI workers with some free tier
10
+
11
+ Clouflare support LLm and some other multimedia models
12
+ you can find the list of supported models here : https://developers.cloudflare.com/workers-ai/models/
13
+ """
14
+
15
+
16
+ class CloudflarePlatform(Platform):
17
+ def __init__(self, **kwargs):
18
+ super().__init__("cloudflare", **kwargs)
19
+
20
+ def _text2image(self, agent: Agent, model: str, prompt: str) -> str:
21
+ CLOUDFLARE_ID = os.environ['CLOUDFLARE_ID']
22
+ CLOUDFLARE_TOKEN = os.environ['CLOUDFLARE_TOKEN']
23
+ random_seed = random.randint(0, 2 ** 32 - 1)
24
+ url = "https://api.cloudflare.com/client/v4/accounts/" + CLOUDFLARE_ID + "/ai/run/@cf/black-forest-labs/flux-1-schnell"
25
+ headers = {
26
+ 'Content-Type': 'application/json',
27
+ 'Authorization': 'Bearer ' + CLOUDFLARE_TOKEN
28
+ }
29
+ data = {
30
+ 'steps': 5,
31
+ 'seed': random_seed,
32
+ 'prompt': prompt
33
+ }
34
+ try:
35
+ response = requests.post(url, headers=headers, json=data)
36
+ response.raise_for_status() # Raise an exception for HTTP errors
37
+ result = response.json()
38
+ #print(f"RESULT = {result}")
39
+ return result['result']['image']
40
+
41
+ except Exception as e:
42
+ print(f"Error generating image: {e}")
43
+ raise
@@ -0,0 +1,119 @@
1
+ import base64
2
+ from io import BytesIO
3
+
4
+ import requests
5
+ from typing import Any
6
+ from PIL import Image
7
+
8
+ import omniagent.imageutils
9
+ from omniagent.platform.platfom import Platform
10
+
11
+ #
12
+ # installed models default params
13
+ #
14
+ highdream_fast_settings = {
15
+ "model": "hidream_i1_fast_q8p.ckpt",
16
+ "negative_prompt": "",
17
+ "steps": 14,
18
+ "batch_count": 1,
19
+ "sampler": "DPM++ 2M Trailing",
20
+ "seed": -1,
21
+ "hires_fix": False,
22
+ "tiled_decoding": False,
23
+ "clip_skip": 1,
24
+ "shift": 1.0,
25
+ "guidance_scale": 1.0,
26
+ "resolution_dependent_shift": False
27
+ }
28
+
29
+ flux_kontext_settings = {
30
+ "model": "flux_1_kontext_dev_q8p.ckpt",
31
+ "negative_prompt": "",
32
+ "steps": 8,
33
+ "batch_count": 1,
34
+ "sampler": "DPM++ 2M Trailing",
35
+ "seed": -1,
36
+ "hires_fix": False,
37
+ "tiled_decoding": False,
38
+ "clip_skip": 1,
39
+ "shift": 1.0,
40
+ "guidance_scale": 2.0,
41
+ "resolution_dependent_shift": True,
42
+ "loras": [{"file": "flux.1_turbo_alpha_lora_f16.ckpt", "weight": 1, "mode": "all"}],
43
+ }
44
+
45
+ qwen_image_edit_settings_4_steps = {
46
+ "model": "qwen_image_edit_2509_q8p.ckpt",
47
+ "negative_prompt": "",
48
+ "steps": 5,
49
+ "batch_count": 1,
50
+ "sampler": "DPM++ 2M Trailing",
51
+ "seed": -1,
52
+ "hires_fix": False,
53
+ "tiled_decoding": False,
54
+ "clip_skip": 1,
55
+ "shift": 1.0,
56
+ "guidance_scale": 2.0,
57
+ "resolution_dependent_shift": True,
58
+ "loras": [{"file": "qwen_image_edit_2509_lightning_4_step_v1.0_lora_f16.ckpt", "weight": 1, "mode": "all"}],
59
+ }
60
+
61
+ qwen_image_edit_settings_8_steps = {
62
+ "model": "qwen_image_edit_2509_q8p.ckpt",
63
+ "negative_prompt": "",
64
+ "steps": 8,
65
+ "batch_count": 1,
66
+ "sampler": "DPM++ 2M Trailing",
67
+ "seed": -1,
68
+ "hires_fix": False,
69
+ "tiled_decoding": False,
70
+ "clip_skip": 1,
71
+ "shift": 1.0,
72
+ "guidance_scale": 2.0,
73
+ "resolution_dependent_shift": True,
74
+ "loras": [{"file": "qwen_image_edit_2509_lightning_8_step_v1.0_lora_f16.ckpt", "weight": 1, "mode": "all"}],
75
+ }
76
+
77
+
78
+
79
+ MODELS_SETTINGS = {
80
+ "highdream_fast": highdream_fast_settings,
81
+ "flux_kontext": flux_kontext_settings,
82
+ "qwen_image_edit_4_steps": qwen_image_edit_settings_4_steps,
83
+ "qwen_image_edit_8_steps": qwen_image_edit_settings_8_steps,
84
+ }
85
+
86
+ class DrawThingsPlatform(Platform):
87
+ def __init__(self, host: str = "127.0.0.1:7860", **kwargs):
88
+ self.host = host
89
+
90
+
91
+ def _text2image(self, model: str, prompt: str) -> Image:
92
+ payload = MODELS_SETTINGS[model]
93
+ payload["prompt"] = prompt
94
+
95
+ try:
96
+ response = requests.post(f"http://{self.host}/sdapi/v1/txt2img", json=payload)
97
+ response.raise_for_status()
98
+ json_data = response.json()
99
+ base64_string = json_data["images"][0]
100
+ image = omniagent.base64_to_image(base64_string)
101
+ return image
102
+ except Exception as e:
103
+ raise RuntimeError(f"DrawThings API error: {e}")
104
+
105
+
106
+ def _image2image(self, model: str, prompt: str, image: Image) -> Image:
107
+ payload = MODELS_SETTINGS[model]
108
+ payload["prompt"] = prompt
109
+ base64_image = omniagent.image_to_base64(image)
110
+ payload["init_images"] = [base64_image]
111
+
112
+ try:
113
+ response = requests.post(f"http://{self.host}/sdapi/v1/img2img", json=payload)
114
+ response.raise_for_status()
115
+ json_data = response.json()
116
+ base64_string = json_data["images"][0]
117
+ return base64_string
118
+ except Exception as e:
119
+ raise RuntimeError(f"DrawThings API error: {e}")
@@ -0,0 +1,52 @@
1
+ from groq import Groq
2
+
3
+ from src.omniagent.platform.platfom import Platform
4
+
5
+
6
+ """
7
+ groq platform
8
+
9
+ groq support LLm and audio2text models
10
+ you can find the list of supported models here : https://console.groq.com/docs/models
11
+ """
12
+
13
+
14
+ class GroqPlatform(Platform):
15
+ def __init__(self, api_key: str, **kwargs):
16
+ super().__init__("groq", api_key=api_key, **kwargs)
17
+ self.client = Groq(api_key=api_key)
18
+
19
+ def _text2text(self, model: str, prompt: str) -> str:
20
+ messages = []
21
+ messages.append({"role": "user", "content": prompt})
22
+ #
23
+ # TODO manage system prompt
24
+ #
25
+ #if agent.system_prompt:
26
+ # messages.append({"role": "system", "content": agent.system_prompt})
27
+
28
+ try:
29
+ response = self.client.chat.completions.create(
30
+ model=model,
31
+ messages=messages,
32
+ # Controls randomness: lowering results in less random completions.
33
+ # As the temperature approaches zero, the model will become deterministic
34
+ # and repetitive.
35
+ temperature=0.8,
36
+ # The maximum number of tokens to generate. Requests can use up to
37
+ # 32,768 tokens shared between prompt and completion.
38
+ max_tokens=4096,
39
+ # Controls diversity via nucleus sampling: 0.5 means half of all
40
+ # likelihood-weighted options are considered.
41
+ top_p=1,
42
+ # A stop sequence is a predefined or user-specified text string that
43
+ # signals an AI to stop generating content, ensuring its responses
44
+ # remain focused and concise. Examples include punctuation marks and
45
+ # markers like "[end]".
46
+ stop=None,
47
+ # If set, partial message deltas will be sent.
48
+ stream=False,
49
+ )
50
+ return response.choices[0].message.content or ""
51
+ except Exception as e:
52
+ raise RuntimeError(f"Groq API error: {e}")
@@ -0,0 +1,114 @@
1
+ import instructor
2
+ from typing import Optional, Any
3
+ from openai import OpenAI
4
+ from pydantic import BaseModel
5
+ from PIL import Image
6
+
7
+ from omniagent.imageutils import image_to_base64
8
+ from omniagent.platform.platfom import Platform
9
+
10
+ #
11
+ # example : https://github.com/YorkieDev/lmstudioservercodeexamples?tab=readme-ov-file#vision-analysis-python
12
+ #
13
+
14
+ class LMStudioPlatform(Platform):
15
+ def __init__(self, host: str = "127.0.0.1:1234", **kwargs):
16
+ self.host = host
17
+
18
+
19
+ def _text2text(self, model: str, prompt: str, **kwargs) -> str:
20
+ system_prompt: Optional[str] = kwargs.get("system_promt", "")
21
+
22
+ client = OpenAI(
23
+ base_url="http://localhost:1234/v1", # LM Studio's default endpoint
24
+ api_key="lm-studio" # Dummy key (LM Studio doesn't require real keys)
25
+ )
26
+ response = client.chat.completions.create(
27
+ model=model, # e.g., "gpt-4o" or local model like "llama-3"
28
+ messages=[
29
+ {"role": "system", "content": system_prompt},
30
+ {"role": "user", "content": prompt}
31
+ ],
32
+ temperature=0.8
33
+ )
34
+ return response.choices[0].message.content
35
+
36
+
37
+ def _text2data(self, model: str, response_model: BaseModel, prompt: str, **kwargs) -> Any:
38
+ # Patch the OpenAI client with Instructor
39
+ client = instructor.patch(
40
+ OpenAI(
41
+ base_url="http://localhost:1234/v1", # LM Studio's default endpoint
42
+ api_key="lm-studio" # Dummy key (LM Studio doesn't require real keys)
43
+ ),
44
+ mode=instructor.Mode.JSON # CRITICAL FOR NON-OPENAI MODELS
45
+ )
46
+
47
+ # Get structured response
48
+ response_data = client.chat.completions.create(
49
+ model=model, # Must match LM Studio's loaded model name
50
+ response_model=response_model,
51
+ messages=[
52
+ {"role": "user", "content": prompt}
53
+ ],
54
+ max_retries=3 # Auto-retry on validation failures
55
+ )
56
+
57
+ return response_data.model_dump_json(indent=2)
58
+
59
+
60
+
61
+ def _image2text(self, model: str, prompt: str, image: Image.Image) -> str:
62
+ client = OpenAI(
63
+ base_url="http://localhost:1234/v1", # LM Studio's default endpoint
64
+ api_key="lm-studio" # Dummy key (LM Studio doesn't require real keys)
65
+ )
66
+
67
+ base64_image = image_to_base64(image)
68
+
69
+ response = client.responses.create(
70
+ model=model,
71
+ input=[
72
+ {
73
+ "role": "user",
74
+ "content": [
75
+ {"type": "input_text", "text": prompt},
76
+ {"type": "input_image", "image_url": f"data:image/png;base64,{base64_image}"},
77
+ ],
78
+ }
79
+ ],
80
+ )
81
+ return response.model_dump_json(indent=2)
82
+
83
+ def _image2data(self, model: str, response_model: BaseModel, prompt: str, image: Image.Image, **kwargs) -> str:
84
+ # Patch the OpenAI client with Instructor
85
+ client = instructor.patch(
86
+ OpenAI(
87
+ base_url="http://localhost:1234/v1", # LM Studio's default endpoint
88
+ api_key="lm-studio" # Dummy key (LM Studio doesn't require real keys)
89
+ ),
90
+ mode=instructor.Mode.JSON # CRITICAL FOR NON-OPENAI MODELS
91
+ )
92
+
93
+ # Get structured response
94
+ response_data = client.chat.completions.create(
95
+ model="your-model-name-here", # Must match LM Studio's loaded model name
96
+ response_model=response_model,
97
+ messages=[{
98
+ "role": "user",
99
+ "content": prompt
100
+ }],
101
+ max_retries=3 # Auto-retry on validation failures
102
+ )
103
+
104
+ return response_data.model_dump_json(indent=2)
105
+
106
+
107
+ def _text2image(self, model: str, prompt: str, **kwargs) -> Image.Image:
108
+ """Platform-specific execution interface"""
109
+ pass
110
+
111
+ def _image2image(self, model: str, prompt: str, image: Image.Image, **kwargs) -> Image.Image:
112
+ """Platform-specific execution interface"""
113
+ pass
114
+
@@ -0,0 +1,33 @@
1
+ from ollama import chat
2
+ from PIL import Image
3
+
4
+ from src.omniagent.platform.platfom import Platform
5
+
6
+ class OllamaPlatform(Platform):
7
+ def __init__(self, host: str = "http://localhost:11434", **kwargs):
8
+ super().__init__("ollama", **kwargs)
9
+ self.host = host
10
+
11
+
12
+ def _text2text(self, model: str, prompt: str, **kwargs) -> str:
13
+ payload = {
14
+ 'role': 'user',
15
+ 'content': prompt,
16
+ }
17
+
18
+ try:
19
+ response = chat(model=model, messages=[payload])
20
+ return response['message']['content']
21
+ except Exception as e:
22
+ raise RuntimeError(f"Ollama API error: {e}")
23
+
24
+
25
+ def _image2text(self, model: str, prompt: str, image: Image.Image) -> str:
26
+ """
27
+ Not implemented yet
28
+ :param model:
29
+ :param prompt:
30
+ :param image:
31
+ :return:
32
+ """
33
+ pass
@@ -0,0 +1,76 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any, Optional
3
+ from pydantic import BaseModel
4
+ from PIL import Image
5
+
6
+ class Platform(ABC):
7
+ """Abstract base for AI platform connectors"""
8
+
9
+ def generate(self, model: str, prompt: str, **kwargs) -> Any:
10
+ """
11
+ Polymorphic entry point that dispatches to the appropriate internal method
12
+ based on the presence of an input image and/or expected output type.
13
+ """
14
+ print(f"Generate model={model}, prompt={prompt}, kwargs={kwargs}")
15
+ image: Optional[Image.Image] = kwargs.get("image", None)
16
+ output_type: str = kwargs.get("output_type", "text") # 'text' or 'image'
17
+
18
+ if image is not None:
19
+ # Image input → multimodal
20
+ if output_type == "image":
21
+ return self._image2image(model, prompt, image, **kwargs)
22
+ else:
23
+ return self._image2text(model, prompt, image, **kwargs)
24
+ else:
25
+ # Text-only input
26
+ if output_type == "image":
27
+ return self._text2image(model, prompt, **kwargs)
28
+ else:
29
+ return self._text2text(model, prompt, **kwargs)
30
+
31
+
32
+ def generate_data(self, model: str, response_model: BaseModel, prompt: str, **kwargs) -> Any:
33
+ """
34
+ Polymorphic entry point that dispatches to the appropriate internal method
35
+ based on the presence of an input image.
36
+ use for text to text or image to text structured output
37
+ """
38
+ image: Optional[Image.Image] = kwargs.get("image", None)
39
+ if image is not None:
40
+ # Image input → multimodal
41
+ return self._image2data(model, response_model, prompt, image, **kwargs)
42
+ else:
43
+ return self._text2data(model, response_model, prompt, **kwargs)
44
+
45
+
46
+ @abstractmethod
47
+ def _text2text(self, model: str, prompt: str, **kwargs) -> Any:
48
+ """Platform-specific execution interface"""
49
+ pass
50
+
51
+ @abstractmethod
52
+ def _text2data(self, model: str, response_model: BaseModel, prompt: str, **kwargs) -> Any:
53
+ """Platform-specific execution interface"""
54
+ pass
55
+
56
+ @abstractmethod
57
+ def _text2image(self, model: str, prompt: str, **kwargs) -> Image.Image:
58
+ """Platform-specific execution interface"""
59
+ pass
60
+
61
+ @abstractmethod
62
+ def _image2text(self, model: str, prompt: str, image: Image.Image, **kwargs) -> str:
63
+ """Platform-specific execution interface"""
64
+ pass
65
+
66
+ @abstractmethod
67
+ def _image2data(self, model: str, response_model: BaseModel, prompt: str, image: Image.Image, **kwargs) -> Any:
68
+ """Platform-specific execution interface"""
69
+ pass
70
+
71
+ @abstractmethod
72
+ def _image2image(self, model: str, prompt: str, image: Image.Image, **kwargs) -> Image.Image:
73
+ """Platform-specific execution interface"""
74
+ pass
75
+
76
+
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: polymage
3
+ Version: 0.0.1
4
+ Summary: polymage : a multimodal agent python library
5
+ Author-email: Fabrice Gaillard <fgaillard@w3architect.com>
6
+ License: Apache 2.0
7
+ Requires-Python: >=3.13
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: groq>=0.37.1
11
+ Requires-Dist: instructor>=1.13.0
12
+ Requires-Dist: ollama>=0.6.1
13
+ Requires-Dist: openai>=2.9.0
14
+ Requires-Dist: pillow>=12.0.0
15
+ Requires-Dist: requests>=2.32.5
16
+ Dynamic: license-file
17
+
18
+ # Multimodal Agents Framework
19
+
20
+ A modular, platform-agnostic Python library to orchestrate multimodal AI agents across platforms
21
+ and models (Gemma, moondream, Flux, HiDream, etc.)
22
+
23
+ Can run both on Local platforms
24
+ - Ollama (https://ollama.com), available for macOS, Windows, and Linux
25
+ - LmStudio (https://lmstudio.ai), available for macOS, Windows, and Linux
26
+ - DrawThings (https://drawthings.ai), available only on macOS
27
+
28
+ And on Cloud platforms
29
+ - Groq (https://groq.com/)
30
+ - Cloudflare (https://developers.cloudflare.com/workers-ai/)
31
+
32
+
33
+ ## ✨ Features
34
+
35
+ - Define agents with prompts + multimodal inputs (image, audio, video, text)
36
+ - Run same agent on multiple platforms/models for comparison
37
+ - Workflow orchestration : just python scripts or tools like Apache Airflow
38
+
39
+ ## 🚀 Quick Start
40
+
41
+ ### Clone the repo
42
+
43
+ ```bash
44
+ # clone the repo
45
+ git clone
46
+ ```
47
+
48
+ ### Use uv to create a virtual environment (https://docs.astral.sh/uv/)
49
+
50
+ uv is the best tool to manage multiple python version and multiple virtual python environment on your machine
51
+
52
+ Installation guide at https://docs.astral.sh/uv/getting-started/installation/
53
+
54
+ ```bash
55
+ uv venv
56
+ ```
57
+
58
+
59
+
60
+
61
+ ---
62
+
63
+ Apache 2.0 License — Happy building! 🚀
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/polymage/__init__.py
5
+ src/polymage/imageutils.py
6
+ src/polymage.egg-info/PKG-INFO
7
+ src/polymage.egg-info/SOURCES.txt
8
+ src/polymage.egg-info/dependency_links.txt
9
+ src/polymage.egg-info/requires.txt
10
+ src/polymage.egg-info/top_level.txt
11
+ src/polymage/agent/InstructAgent.py
12
+ src/polymage/agent/__init__.py
13
+ src/polymage/agent/agent.py
14
+ src/polymage/model/__init__.py
15
+ src/polymage/model/model.py
16
+ src/polymage/platform/__init__.py
17
+ src/polymage/platform/cloudflare.py
18
+ src/polymage/platform/drawthings.py
19
+ src/polymage/platform/groq.py
20
+ src/polymage/platform/lmstudio.py
21
+ src/polymage/platform/ollama.py
22
+ src/polymage/platform/platfom.py
@@ -0,0 +1,6 @@
1
+ groq>=0.37.1
2
+ instructor>=1.13.0
3
+ ollama>=0.6.1
4
+ openai>=2.9.0
5
+ pillow>=12.0.0
6
+ requests>=2.32.5
@@ -0,0 +1 @@
1
+ polymage