swarmauri_llm_leptonai 0.6.0.dev154__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.
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_llm_leptonai
3
+ Version: 0.6.0.dev154
4
+ Summary: Swarmauri Lepton AI Model
5
+ License: Apache-2.0
6
+ Author: Jacob Stewart
7
+ Author-email: jacob@swarmauri.com
8
+ Requires-Python: >=3.10,<3.13
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: leptonai (>=0.22.0,<0.23.0)
15
+ Requires-Dist: swarmauri_base (>=0.6.0.dev154,<0.7.0)
16
+ Requires-Dist: swarmauri_core (>=0.6.0.dev154,<0.7.0)
17
+ Project-URL: Repository, http://github.com/swarmauri/swarmauri-sdk
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Swarmauri Example Community Package
@@ -0,0 +1 @@
1
+ # Swarmauri Example Community Package
@@ -0,0 +1,59 @@
1
+ [tool.poetry]
2
+ name = "swarmauri_llm_leptonai"
3
+ version = "0.6.0.dev154"
4
+ description = "Swarmauri Lepton AI Model"
5
+ authors = ["Jacob Stewart <jacob@swarmauri.com>"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ repository = "http://github.com/swarmauri/swarmauri-sdk"
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Programming Language :: Python :: 3.10",
12
+ "Programming Language :: Python :: 3.11",
13
+ "Programming Language :: Python :: 3.12"
14
+ ]
15
+
16
+ [tool.poetry.dependencies]
17
+ python = ">=3.10,<3.13"
18
+
19
+ # Swarmauri
20
+ swarmauri_core = {version = "^0.6.0.dev154"}
21
+ swarmauri_base = {version = "^0.6.0.dev154"}
22
+
23
+ # Dependencies
24
+ leptonai = "^0.22.0"
25
+
26
+ [tool.poetry.group.dev.dependencies]
27
+ flake8 = "^7.0"
28
+ pytest = "^8.0"
29
+ pytest-asyncio = ">=0.24.0"
30
+ pytest-xdist = "^3.6.1"
31
+ pytest-json-report = "^1.5.0"
32
+ python-dotenv = "*"
33
+ requests = "^2.32.3"
34
+
35
+ [build-system]
36
+ requires = ["poetry-core>=1.0.0"]
37
+ build-backend = "poetry.core.masonry.api"
38
+
39
+ [tool.pytest.ini_options]
40
+ norecursedirs = ["combined", "scripts"]
41
+
42
+ markers = [
43
+ "test: standard test",
44
+ "unit: Unit tests",
45
+ "integration: Integration tests",
46
+ "acceptance: Acceptance tests",
47
+ "experimental: Experimental tests"
48
+ ]
49
+ log_cli = true
50
+ log_cli_level = "INFO"
51
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
52
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
53
+ asyncio_default_fixture_loop_scope = "function"
54
+
55
+ [tool.poetry.plugins."swarmauri.llms"]
56
+ LeptonAIModel = "swarmauri_llm_leptonai.LeptonAIImgGenModel:LeptonAIModel"
57
+
58
+ [tool.poetry.plugins."swarmauri.image_gens"]
59
+ LeptonAIImgGenModel = "swarmauri_llm_leptonai.LeptonAIImgGenModel:LeptonAIImgGenModel"
@@ -0,0 +1,99 @@
1
+ import os
2
+ import asyncio
3
+ import requests
4
+ from io import BytesIO
5
+ from PIL import Image
6
+ from typing import List, Literal
7
+ from swarmauri_base.image_gens.ImageGenBase import ImageGenBase
8
+ from pydantic import Field, ConfigDict
9
+ from swarmauri_core.ComponentBase import ComponentBase
10
+
11
+
12
+ @ComponentBase.register_type(ImageGenBase, "LeptonAIImgGenModel")
13
+ class LeptonAIImgGenModel(ImageGenBase):
14
+ """
15
+ A model for generating images from text using Lepton AI's SDXL image generation model.
16
+ It returns the image as bytes.
17
+ Get your API KEY from Lepton AI.
18
+ """
19
+
20
+ api_key: str = Field(default_factory=lambda: os.environ.get("LEPTON_API_KEY"))
21
+ model_name: str = Field(default="sdxl")
22
+ type: Literal["LeptonAIImgGenModel"] = "LeptonAIImgGenModel"
23
+ base_url: str = Field(default="https://sdxl.lepton.run")
24
+
25
+ model_config = ConfigDict(protected_namespaces=())
26
+
27
+ def __init__(self, **data):
28
+ super().__init__(**data)
29
+ if self.api_key:
30
+ os.environ["LEPTON_API_KEY"] = self.api_key
31
+
32
+ def _send_request(self, prompt: str, **kwargs) -> bytes:
33
+ """Send a request to Lepton AI's API for image generation."""
34
+ client = requests.Session()
35
+ client.headers.update({"Authorization": f"Bearer {self.api_key}"})
36
+
37
+ payload = {
38
+ "prompt": prompt,
39
+ "height": kwargs.get("height", 1024),
40
+ "width": kwargs.get("width", 1024),
41
+ "guidance_scale": kwargs.get("guidance_scale", 5),
42
+ "high_noise_frac": kwargs.get("high_noise_frac", 0.75),
43
+ "seed": kwargs.get("seed", None),
44
+ "steps": kwargs.get("steps", 30),
45
+ "use_refiner": kwargs.get("use_refiner", False),
46
+ }
47
+
48
+ response = client.post(f"{self.base_url}/run", json=payload)
49
+ response.raise_for_status()
50
+ return response.content
51
+
52
+ def generate_image(self, prompt: str, **kwargs) -> bytes:
53
+ """Generates an image based on the prompt and returns the image as bytes."""
54
+ return self._send_request(prompt, **kwargs)
55
+
56
+ async def agenerate_image(self, prompt: str, **kwargs) -> bytes:
57
+ """Asynchronously generates an image based on the prompt and returns the image as bytes."""
58
+ loop = asyncio.get_event_loop()
59
+ return await loop.run_in_executor(None, self.generate_image, prompt, **kwargs)
60
+
61
+ def batch(self, prompts: List[str], **kwargs) -> List[bytes]:
62
+ """
63
+ Generates images for a batch of prompts.
64
+ Returns a list of image bytes.
65
+ """
66
+ image_bytes_list = []
67
+ for prompt in prompts:
68
+ image_bytes = self.generate_image(prompt=prompt, **kwargs)
69
+ image_bytes_list.append(image_bytes)
70
+ return image_bytes_list
71
+
72
+ async def abatch(
73
+ self, prompts: List[str], max_concurrent: int = 5, **kwargs
74
+ ) -> List[bytes]:
75
+ """
76
+ Asynchronously generates images for a batch of prompts.
77
+ Returns a list of image bytes.
78
+ """
79
+ semaphore = asyncio.Semaphore(max_concurrent)
80
+
81
+ async def process_prompt(prompt):
82
+ async with semaphore:
83
+ return await self.agenerate_image(prompt=prompt, **kwargs)
84
+
85
+ tasks = [process_prompt(prompt) for prompt in prompts]
86
+ return await asyncio.gather(*tasks)
87
+
88
+ @staticmethod
89
+ def save_image(image_bytes: bytes, filename: str):
90
+ """Utility method to save the image bytes to a file."""
91
+ with open(filename, "wb") as f:
92
+ f.write(image_bytes)
93
+ print(f"Image saved as {filename}")
94
+
95
+ @staticmethod
96
+ def display_image(image_bytes: bytes):
97
+ """Utility method to display the image using PIL."""
98
+ image = Image.open(BytesIO(image_bytes))
99
+ image.show()
@@ -0,0 +1,286 @@
1
+ import json
2
+ from openai import OpenAI, AsyncOpenAI
3
+ from typing import List, Dict, Literal, Optional, Iterator, AsyncIterator
4
+ import asyncio
5
+ from pydantic import Field
6
+ from swarmauri_core.typing import SubclassUnion
7
+ from swarmauri_base.messages.MessageBase import MessageBase
8
+ from swarmauri_base.llms.base.LLMBase import LLMBase
9
+
10
+ from swarmauri_standard.messages.AgentMessage import AgentMessage, UsageData
11
+ from swarmauri.utils.duration_manager import DurationManager
12
+ from swarmauri_core.ComponentBase import ComponentBase
13
+
14
+ @ComponentBase.register_type(LLMBase, "LeptonAIModel")
15
+ class LeptonAIModel(LLMBase):
16
+ """
17
+ Provider resources: https://www.lepton.ai/playground
18
+ """
19
+
20
+ api_key: str
21
+ allowed_models: List[str] = [
22
+ "llama2-13b",
23
+ "llama3-1-405b",
24
+ "llama3-1-70b",
25
+ "llama3-1-8b",
26
+ "llama3-70b",
27
+ "llama3-8b",
28
+ "mixtral-8x7b",
29
+ "mistral-7b",
30
+ "nous-hermes-llama2-13b",
31
+ "openchat-3-5",
32
+ "qwen2-72b",
33
+ "toppy-m-7b",
34
+ "wizardlm-2-7b",
35
+ "wizardlm-2-8x22b",
36
+ ]
37
+
38
+ name: str = "llama3-8b"
39
+ type: Literal["LeptonAIModel"] = "LeptonAIModel"
40
+ client: OpenAI = Field(default=None, exclude=True)
41
+ async_client: AsyncOpenAI = Field(default=None, exclude=True)
42
+
43
+ def __init__(self, **data):
44
+ super().__init__(**data)
45
+ url = f"https://{self.name}.lepton.run/api/v1/"
46
+ self.client = OpenAI(base_url=url, api_key=self.api_key)
47
+ self.async_client = AsyncOpenAI(base_url=url, api_key=self.api_key)
48
+
49
+ def _format_messages(
50
+ self, messages: List[SubclassUnion[MessageBase]]
51
+ ) -> List[Dict[str, str]]:
52
+ message_properties = ["content", "role", "name"]
53
+ formatted_messages = [
54
+ message.model_dump(include=message_properties, exclude_none=True)
55
+ for message in messages
56
+ ]
57
+ return formatted_messages
58
+
59
+ def _get_system_context(self, messages: List[SubclassUnion[MessageBase]]) -> str:
60
+ system_context = None
61
+ for message in messages:
62
+ if message.role == "system":
63
+ system_context = message.content
64
+ return system_context
65
+
66
+ def _prepare_messages(self, conversation):
67
+ formatted_messages = self._format_messages(conversation.history)
68
+ system_context = self._get_system_context(conversation.history)
69
+ if system_context:
70
+ formatted_messages = [
71
+ {"role": "system", "content": system_context},
72
+ formatted_messages[-1],
73
+ ]
74
+ return formatted_messages
75
+
76
+ def _prepare_usage_data(
77
+ self,
78
+ usage_data,
79
+ prompt_time: float = 0.0,
80
+ completion_time: float = 0.0,
81
+ ):
82
+ """
83
+ Prepares and extracts usage data and response timing.
84
+ """
85
+ total_time = prompt_time + completion_time
86
+
87
+ usage = UsageData(
88
+ prompt_tokens=usage_data.get("prompt_tokens", 0),
89
+ completion_tokens=usage_data.get("completion_tokens", 0),
90
+ total_tokens=usage_data.get("total_tokens", 0),
91
+ prompt_time=prompt_time,
92
+ completion_time=completion_time,
93
+ total_time=total_time,
94
+ )
95
+
96
+ return usage
97
+
98
+ def predict(
99
+ self,
100
+ conversation,
101
+ temperature: Optional[float] = 0.5,
102
+ max_tokens: Optional[int] = 256,
103
+ top_p: Optional[float] = 0.8,
104
+ stream: Optional[bool] = False,
105
+ ):
106
+ formatted_messages = self._prepare_messages(conversation)
107
+
108
+ with DurationManager() as prompt_timer:
109
+ response = self.client.chat.completions.create(
110
+ model=self.name,
111
+ messages=formatted_messages,
112
+ temperature=temperature,
113
+ max_tokens=max_tokens,
114
+ top_p=top_p,
115
+ stream=stream,
116
+ )
117
+
118
+ result = json.loads(response.model_dump_json())
119
+ message_content = result["choices"][0]["message"]["content"]
120
+ usage_data = result.get("usage", {})
121
+
122
+ usage = self._prepare_usage_data(
123
+ usage_data,
124
+ prompt_timer.duration,
125
+ )
126
+
127
+ conversation.add_message(AgentMessage(content=message_content, usage=usage))
128
+ return conversation
129
+
130
+ async def apredict(
131
+ self,
132
+ conversation,
133
+ temperature: Optional[float] = 0.5,
134
+ max_tokens: Optional[int] = 256,
135
+ top_p: Optional[float] = 0.8,
136
+ ):
137
+ """Asynchronous version of predict"""
138
+ formatted_messages = self._prepare_messages(conversation)
139
+
140
+ with DurationManager() as prompt_timer:
141
+ response = await self.async_client.chat.completions.create(
142
+ model=self.name,
143
+ messages=formatted_messages,
144
+ temperature=temperature,
145
+ max_tokens=max_tokens,
146
+ top_p=top_p,
147
+ )
148
+
149
+ result = json.loads(response.model_dump_json())
150
+ message_content = result["choices"][0]["message"]["content"]
151
+ usage_data = result.get("usage", {})
152
+
153
+ usage = self._prepare_usage_data(
154
+ usage_data,
155
+ prompt_timer.duration,
156
+ )
157
+
158
+ conversation.add_message(AgentMessage(content=message_content, usage=usage))
159
+ return conversation
160
+
161
+ def stream(
162
+ self,
163
+ conversation,
164
+ temperature: Optional[float] = 0.5,
165
+ max_tokens: Optional[int] = 256,
166
+ top_p: Optional[float] = 0.8,
167
+ ) -> Iterator[str]:
168
+ """Synchronously stream the response token by token"""
169
+ formatted_messages = self._prepare_messages(conversation)
170
+
171
+ with DurationManager() as prompt_timer:
172
+ stream = self.client.chat.completions.create(
173
+ model=self.name,
174
+ messages=formatted_messages,
175
+ temperature=temperature,
176
+ max_tokens=max_tokens,
177
+ top_p=top_p,
178
+ stream=True,
179
+ stream_options={"include_usage": True},
180
+ )
181
+
182
+ collected_content = []
183
+ usage_data = {}
184
+
185
+ with DurationManager() as completion_timer:
186
+ for chunk in stream:
187
+ if chunk.choices and chunk.choices[0].delta.content:
188
+ content = chunk.choices[0].delta.content
189
+ collected_content.append(content)
190
+ yield content
191
+
192
+ if hasattr(chunk, "usage") and chunk.usage is not None:
193
+ usage_data = chunk.usage
194
+
195
+ full_content = "".join(collected_content)
196
+ usage = self._prepare_usage_data(
197
+ usage_data.model_dump(),
198
+ prompt_timer.duration,
199
+ completion_timer.duration,
200
+ )
201
+
202
+ conversation.add_message(AgentMessage(content=full_content, usage=usage))
203
+
204
+ async def astream(
205
+ self,
206
+ conversation,
207
+ temperature: Optional[float] = 0.5,
208
+ max_tokens: Optional[int] = 256,
209
+ top_p: Optional[float] = 0.8,
210
+ ) -> AsyncIterator[str]:
211
+ """Asynchronously stream the response token by token"""
212
+ formatted_messages = self._prepare_messages(conversation)
213
+
214
+ with DurationManager() as prompt_timer:
215
+ stream = await self.async_client.chat.completions.create(
216
+ model=self.name,
217
+ messages=formatted_messages,
218
+ temperature=temperature,
219
+ max_tokens=max_tokens,
220
+ top_p=top_p,
221
+ stream=True,
222
+ stream_options={"include_usage": True},
223
+ )
224
+
225
+ usage_data = {}
226
+ collected_content = []
227
+
228
+ with DurationManager() as completion_timer:
229
+ async for chunk in stream:
230
+ if chunk.choices and chunk.choices[0].delta.content:
231
+ content = chunk.choices[0].delta.content
232
+ collected_content.append(content)
233
+ yield content
234
+
235
+ if hasattr(chunk, "usage") and chunk.usage is not None:
236
+ usage_data = chunk.usage
237
+
238
+ full_content = "".join(collected_content)
239
+
240
+ usage = self._prepare_usage_data(
241
+ usage_data.model_dump(),
242
+ prompt_timer.duration,
243
+ completion_timer.duration,
244
+ )
245
+ conversation.add_message(AgentMessage(content=full_content, usage=usage))
246
+
247
+ def batch(
248
+ self,
249
+ conversations: List,
250
+ temperature: Optional[float] = 0.5,
251
+ max_tokens: Optional[int] = 256,
252
+ top_p: Optional[float] = 0.8,
253
+ ) -> List:
254
+ """Synchronously process multiple conversations"""
255
+ return [
256
+ self.predict(
257
+ conv,
258
+ temperature=temperature,
259
+ max_tokens=max_tokens,
260
+ top_p=top_p,
261
+ )
262
+ for conv in conversations
263
+ ]
264
+
265
+ async def abatch(
266
+ self,
267
+ conversations: List,
268
+ temperature: Optional[float] = 0.5,
269
+ max_tokens: Optional[int] = 256,
270
+ top_p: Optional[float] = 0.8,
271
+ max_concurrent: int = 5,
272
+ ) -> List:
273
+ """Process multiple conversations in parallel with controlled concurrency"""
274
+ semaphore = asyncio.Semaphore(max_concurrent)
275
+
276
+ async def process_conversation(conv):
277
+ async with semaphore:
278
+ return await self.apredict(
279
+ conv,
280
+ temperature=temperature,
281
+ max_tokens=max_tokens,
282
+ top_p=top_p,
283
+ )
284
+
285
+ tasks = [process_conversation(conv) for conv in conversations]
286
+ return await asyncio.gather(*tasks)
@@ -0,0 +1,17 @@
1
+ from .LeptonAIImgGenModel import LeptonAIImgGenModel
2
+ from .LeptonAIModel import LeptonAIModel
3
+
4
+ __version__ = "0.6.0.dev26"
5
+ __long_desc__ = """
6
+
7
+ # Swarmauri LeptonAI Plugin
8
+
9
+ Components Included:
10
+ - LeptonAIModel
11
+ - LeptonAIImgGenModel
12
+
13
+ Visit us at: https://swarmauri.com
14
+ Follow us at: https://github.com/swarmauri
15
+ Star us at: https://github.com/swarmauri/swarmauri-sdk
16
+
17
+ """