blaxel 0.2.2__py3-none-any.whl → 0.2.3__py3-none-any.whl

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.
@@ -22,12 +22,15 @@ if os.getenv("BL_SERVER_PORT"):
22
22
 
23
23
 
24
24
  class PersistentWebSocket:
25
- def __init__(
26
- self, url: str, name: str, timeout: int = DEFAULT_TIMEOUT, timeout_enabled: bool = True
27
- ):
28
- self.url = url
25
+ def __init__(self, name: str, timeout: int = DEFAULT_TIMEOUT, timeout_enabled: bool = True):
29
26
  self.name = name
30
27
  self.timeout = timeout
28
+ self.type = "function"
29
+ self.pluralType = "functions"
30
+ if name.startswith("sandbox/") or name.startswith("sandboxes/"):
31
+ self.name = name.split("/")[1]
32
+ self.type = "sandbox"
33
+ self.pluralType = "sandboxes"
31
34
  self.session_exit_stack = AsyncExitStack()
32
35
  self.client_exit_stack = AsyncExitStack()
33
36
  self.session: ClientSession = None
@@ -37,6 +40,42 @@ class PersistentWebSocket:
37
40
  self.timeout_enabled = False
38
41
  else:
39
42
  self.timeout_enabled = timeout_enabled
43
+ self.use_fallback_url = False
44
+
45
+ @property
46
+ def _internal_url(self):
47
+ """Get the internal URL for the agent using a hash of workspace and agent name."""
48
+ hash = get_global_unique_hash(settings.workspace, self.type, self.name)
49
+ return f"{settings.run_internal_protocol}://bl-{settings.env}-{hash}.{settings.run_internal_hostname}"
50
+
51
+ @property
52
+ def _forced_url(self):
53
+ """Get the forced URL from environment variables if set."""
54
+ return get_forced_url(self.type, self.name)
55
+
56
+ @property
57
+ def _external_url(self):
58
+ return f"{settings.run_url}/{settings.workspace}/{self.pluralType}/{self.name}"
59
+
60
+ @property
61
+ def _fallback_url(self):
62
+ if self._external_url != self._url:
63
+ return self._external_url
64
+ return None
65
+
66
+ @property
67
+ def _url(self):
68
+ if self.use_fallback_url:
69
+ return self._fallback_url
70
+ logger.debug(f"Getting URL for {self.name}")
71
+ if self._forced_url:
72
+ logger.debug(f"Forced URL found for {self.name}: {self._forced_url}")
73
+ return self._forced_url
74
+ if settings.run_internal_hostname:
75
+ logger.debug(f"Internal hostname found for {self.name}: {self._internal_url}")
76
+ return self._internal_url
77
+ logger.debug(f"No URL found for {self.name}, using external URL")
78
+ return self._external_url
40
79
 
41
80
  def with_metas(self, metas: dict[str, Any]):
42
81
  self.metas = metas
@@ -44,7 +83,7 @@ class PersistentWebSocket:
44
83
 
45
84
  async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> CallToolResult:
46
85
  try:
47
- await self._initialize()
86
+ await self.initialize()
48
87
  if self.timeout_enabled:
49
88
  self._remove_timer()
50
89
  logger.debug(f"Calling tool {tool_name} with arguments {arguments}")
@@ -70,7 +109,7 @@ class PersistentWebSocket:
70
109
 
71
110
  async def list_tools(self):
72
111
  logger.debug(f"Listing tools for {self.name}")
73
- await self._initialize()
112
+ await self.initialize()
74
113
  logger.debug(f"Initialized websocket for {self.name}")
75
114
  if self.timeout_enabled:
76
115
  self._remove_timer()
@@ -87,17 +126,23 @@ class PersistentWebSocket:
87
126
  def get_tools(self):
88
127
  return self.tools_cache
89
128
 
90
- async def _initialize(self):
129
+ async def initialize(self, fallback: bool = False):
91
130
  if not self.session:
92
- logger.debug(f"Initializing websocket client for {self.url}")
93
- read, write = await self.client_exit_stack.enter_async_context(
94
- websocket_client(self.url, settings.headers)
95
- )
96
- self.session = cast(
97
- ClientSession,
98
- await self.session_exit_stack.enter_async_context(ClientSession(read, write)),
99
- )
100
- await self.session.initialize()
131
+ try:
132
+ logger.debug(f"Initializing websocket client for {self._url}")
133
+ read, write = await self.client_exit_stack.enter_async_context(
134
+ websocket_client(self._url, settings.headers)
135
+ )
136
+ self.session = cast(
137
+ ClientSession,
138
+ await self.session_exit_stack.enter_async_context(ClientSession(read, write)),
139
+ )
140
+ await self.session.initialize()
141
+ except Exception as e:
142
+ if not fallback:
143
+ self.use_fallback_url = True
144
+ return await self.initialize(fallback=True)
145
+ raise e
101
146
 
102
147
  def _reset_timer(self):
103
148
  self._remove_timer()
@@ -113,7 +158,7 @@ class PersistentWebSocket:
113
158
  self.session = None
114
159
 
115
160
  async def _close(self):
116
- logger.debug(f"Closing websocket client {self.url}")
161
+ logger.debug(f"Closing websocket client {self._url}")
117
162
  if self.session:
118
163
  self.session = None
119
164
  try:
@@ -129,8 +174,6 @@ class PersistentWebSocket:
129
174
 
130
175
  def convert_mcp_tool_to_blaxel_tool(
131
176
  websocket_client: PersistentWebSocket,
132
- name: str,
133
- url: str,
134
177
  tool: MCPTool,
135
178
  ) -> Tool:
136
179
  """Convert an MCP tool to a blaxel tool.
@@ -193,34 +236,6 @@ class BlTools:
193
236
  self.timeout = timeout
194
237
  self.timeout_enabled = timeout_enabled
195
238
 
196
- def _internal_url(self, name: str):
197
- """Get the internal URL for the agent using a hash of workspace and agent name."""
198
- hash = get_global_unique_hash(settings.workspace, "function", name)
199
- return f"{settings.run_internal_protocol}://bl-{settings.env}-{hash}.{settings.run_internal_hostname}"
200
-
201
- def _forced_url(self, name: str):
202
- """Get the forced URL from environment variables if set."""
203
- return get_forced_url("function", name)
204
-
205
- def _external_url(self, name: str):
206
- return f"{settings.run_url}/{settings.workspace}/functions/{name}"
207
-
208
- def _fallback_url(self, name: str):
209
- if self._external_url(name) != self._url(name):
210
- return self._external_url(name)
211
- return None
212
-
213
- def _url(self, name: str):
214
- logger.debug(f"Getting URL for {name}")
215
- if self._forced_url(name):
216
- logger.debug(f"Forced URL found for {name}: {self._forced_url(name)}")
217
- return self._forced_url(name)
218
- if settings.run_internal_hostname:
219
- logger.debug(f"Internal hostname found for {name}: {self._internal_url(name)}")
220
- return self._internal_url(name)
221
- logger.debug(f"No URL found for {name}, using external URL")
222
- return self._external_url(name)
223
-
224
239
  def get_tools(self) -> list[Tool]:
225
240
  """Get a list of all tools from all connected servers."""
226
241
  all_tools: list[Tool] = []
@@ -228,47 +243,21 @@ class BlTools:
228
243
  toolPersistances.get(name).with_metas(self.metas)
229
244
  websocket = toolPersistances.get(name)
230
245
  tools = websocket.get_tools()
231
- converted_tools = [
232
- convert_mcp_tool_to_blaxel_tool(websocket, name, self._url(name), tool)
233
- for tool in tools
234
- ]
246
+ converted_tools = [convert_mcp_tool_to_blaxel_tool(websocket, tool) for tool in tools]
235
247
  all_tools.extend(converted_tools)
236
248
  return all_tools
237
249
 
238
250
  async def connect(self, name: str):
239
251
  # Create and store the connection
240
- try:
241
- url = self._url(name)
242
- await self.connect_with_url(name, url)
243
- except Exception as e:
244
- if not self._fallback_url(name):
245
- raise e
246
- logger.warning(f"Error connecting to {name}: {e}\n{traceback.format_exc()}")
247
- url = self._fallback_url(name)
248
- try:
249
- await self.connect_with_url(name, url)
250
- except Exception as e:
251
- logger.error(
252
- f"Error connecting to {name} with fallback URL: {e}\n{traceback.format_exc()}"
253
- )
254
- raise e
255
-
256
- async def connect_with_url(self, name: str, url: str) -> None:
257
- """Initialize a session and load tools from it.
258
-
259
- Args:
260
- name: Name to identify this server connection
261
- url: The URL to connect to
262
- """
263
- logger.debug(f"Initializing session and loading tools from {url}")
252
+ logger.debug("Initializing session and loading tools")
264
253
 
265
254
  if not toolPersistances.get(name):
266
255
  logger.debug(f"Creating new persistent websocket for {name}")
267
256
  toolPersistances[name] = PersistentWebSocket(
268
- url, name, timeout=self.timeout, timeout_enabled=self.timeout_enabled
257
+ name, timeout=self.timeout, timeout_enabled=self.timeout_enabled
269
258
  )
270
259
  await toolPersistances[name].list_tools()
271
- logger.debug(f"Loaded {len(toolPersistances[name].get_tools())} tools from {url}")
260
+ logger.debug(f"Loaded {len(toolPersistances[name].get_tools())} tools")
272
261
  return toolPersistances[name].with_metas(self.metas)
273
262
 
274
263
  async def initialize(self) -> "BlTools":
blaxel/crewai/tools.py CHANGED
@@ -19,8 +19,8 @@ class CrewAITool(BaseTool):
19
19
  def _run(self, *args, **kwargs):
20
20
  return self._tool.sync_coroutine(**kwargs)
21
21
 
22
+
22
23
  async def bl_tools(tools_names: list[str], **kwargs) -> list[BaseTool]:
23
24
  tools = bl_tools_core(tools_names, **kwargs)
24
25
  await tools.initialize()
25
26
  return [CrewAITool(tool) for tool in tools.get_tools()]
26
- return [CrewAITool(tool) for tool in tools.get_tools()]
blaxel/livekit/tools.py CHANGED
@@ -8,23 +8,27 @@ def livekit_coroutine(tool: Tool):
8
8
  async def livekit_coroutine_wrapper(raw_arguments: dict[str, object]):
9
9
  result = await tool.coroutine(**raw_arguments)
10
10
  return result.model_dump_json()
11
+
11
12
  return livekit_coroutine_wrapper
12
13
 
14
+
13
15
  def get_livekit_tools(tools: list[Tool]) -> list[llm.FunctionTool]:
14
16
  livekit_tools = []
15
17
  for tool in tools:
16
- livekit_tools.append(function_tool(
17
- livekit_coroutine(tool),
18
- raw_schema={
19
- "name": tool.name,
20
- "description": tool.description,
21
- "parameters": tool.input_schema,
22
- },
23
- ))
18
+ livekit_tools.append(
19
+ function_tool(
20
+ livekit_coroutine(tool),
21
+ raw_schema={
22
+ "name": tool.name,
23
+ "description": tool.description,
24
+ "parameters": tool.input_schema,
25
+ },
26
+ )
27
+ )
24
28
  return livekit_tools
25
29
 
30
+
26
31
  async def bl_tools(tools_names: list[str], **kwargs) -> list[llm.FunctionTool]:
27
32
  tools = bl_tools_core(tools_names, **kwargs)
28
33
  await tools.initialize()
29
34
  return get_livekit_tools(tools.get_tools())
30
- return get_livekit_tools(tools.get_tools())
blaxel/openai/tools.py CHANGED
@@ -9,8 +9,8 @@ from blaxel.core.tools.types import Tool
9
9
 
10
10
  def get_openai_tool(tool: Tool) -> FunctionTool:
11
11
  async def openai_coroutine(
12
- _: RunContextWrapper,
13
- arguments: dict[str, Any],
12
+ _: RunContextWrapper,
13
+ arguments: dict[str, Any],
14
14
  ) -> Any:
15
15
  result = await tool.coroutine(**json.loads(arguments))
16
16
  return result
@@ -22,8 +22,8 @@ def get_openai_tool(tool: Tool) -> FunctionTool:
22
22
  on_invoke_tool=openai_coroutine,
23
23
  )
24
24
 
25
+
25
26
  async def bl_tools(tools_names: list[str], **kwargs) -> list[FunctionTool]:
26
27
  tools = bl_tools_core(tools_names, **kwargs)
27
28
  await tools.initialize()
28
29
  return [get_openai_tool(tool) for tool in tools.get_tools()]
29
- return [get_openai_tool(tool) for tool in tools.get_tools()]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: blaxel
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Blaxel - AI development platform SDK
5
5
  Project-URL: Homepage, https://blaxel.ai
6
6
  Project-URL: Documentation, https://docs.blaxel.ai
@@ -42,7 +42,7 @@ Requires-Dist: llama-index-llms-google-genai>=0.1.13; extra == 'all'
42
42
  Requires-Dist: llama-index-llms-groq>=0.3.1; extra == 'all'
43
43
  Requires-Dist: llama-index-llms-mistralai>=0.4.0; extra == 'all'
44
44
  Requires-Dist: llama-index-llms-openai>=0.3.42; extra == 'all'
45
- Requires-Dist: llama-index>=0.12.37; extra == 'all'
45
+ Requires-Dist: llama-index>=0.12.46; extra == 'all'
46
46
  Requires-Dist: openai-agents>=0.0.19; extra == 'all'
47
47
  Requires-Dist: opentelemetry-exporter-otlp>=1.28.0; extra == 'all'
48
48
  Requires-Dist: opentelemetry-instrumentation-anthropic==0.40.6; extra == 'all'
@@ -92,7 +92,7 @@ Requires-Dist: llama-index-llms-google-genai>=0.1.13; extra == 'llamaindex'
92
92
  Requires-Dist: llama-index-llms-groq>=0.3.1; extra == 'llamaindex'
93
93
  Requires-Dist: llama-index-llms-mistralai>=0.4.0; extra == 'llamaindex'
94
94
  Requires-Dist: llama-index-llms-openai>=0.3.42; extra == 'llamaindex'
95
- Requires-Dist: llama-index>=0.12.37; extra == 'llamaindex'
95
+ Requires-Dist: llama-index>=0.12.46; extra == 'llamaindex'
96
96
  Requires-Dist: opentelemetry-instrumentation-llamaindex>=0.40.7; extra == 'llamaindex'
97
97
  Provides-Extra: openai
98
98
  Requires-Dist: openai-agents>=0.0.19; extra == 'openai'
@@ -355,13 +355,13 @@ blaxel/core/sandbox/client/models/process_response.py,sha256=vXHK6NBnuf0KYVzpkaA
355
355
  blaxel/core/sandbox/client/models/process_response_status.py,sha256=hCE1gCtheV83T6PYURG3k-rPZSauvyTFhsxLEtudgYE,246
356
356
  blaxel/core/sandbox/client/models/subdirectory.py,sha256=obztIgi_XjT4pPoT1-dyOX6O8k0e4ERZUTiI9qgkhJM,1593
357
357
  blaxel/core/sandbox/client/models/success_response.py,sha256=ksioQ0qNV7yhXlySY3_3EycsJ1ec7LSxBMwIq4HnfVQ,1703
358
- blaxel/core/tools/__init__.py,sha256=9_pgKEU5GbPfqfGN4aZTkthnaV4AVYf63jIZw44peBQ,10167
358
+ blaxel/core/tools/__init__.py,sha256=OCZExds99o_j_GvAywaWFIGfY12abNZHcaiGOmAyh8o,9793
359
359
  blaxel/core/tools/common.py,sha256=JGK052v_fvwWBFYnIArlBnFFViYyFrqdDn3gdVf53EU,1332
360
360
  blaxel/core/tools/types.py,sha256=YPCGJ4vZDhqR0X2H_TWtc5chQScsC32nGTQdRKJlO8Y,707
361
361
  blaxel/crewai/__init__.py,sha256=HdAZxRDgC2zW-O5xYzb_Xuysb66_fMykNJVPxlTmFnY,123
362
362
  blaxel/crewai/model.py,sha256=VOLUE5tpz9tmYl7KU9L1kNUJ5uTci2rhRfPQ8HyCfWI,1785
363
363
  blaxel/crewai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
364
- blaxel/crewai/tools.py,sha256=wMMZvSrmhuoFRFux2j31PeSVMbElhs5e49jtvRNxZxY,848
364
+ blaxel/crewai/tools.py,sha256=HVMSRTVrc0ygiCCNkL6xa3i31IWwFlGKB6oC-6iWrK8,789
365
365
  blaxel/googleadk/__init__.py,sha256=WfYZvtkh5IF042qWLaiWjbDarJZCX9ghHGiTrat8eps,127
366
366
  blaxel/googleadk/model.py,sha256=ZSBGapgcrhRogc1kBFKfuLS36UUkcQL6nZD22yVUEJM,2236
367
367
  blaxel/googleadk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -374,7 +374,7 @@ blaxel/langgraph/custom/gemini.py,sha256=AkhpuVMXnh1CyJ0zR2NMTtxQFPPHtAdHf_cyNzV
374
374
  blaxel/livekit/__init__.py,sha256=byUwOJ6MHeSXOYXmaVoHnC3ZUmpkqJ55u5mQglXX-SQ,124
375
375
  blaxel/livekit/model.py,sha256=4HA6Jn4_jQ5QeH5mWMeopWybQDeiJcDRyh5kX5O9LHE,961
376
376
  blaxel/livekit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
377
- blaxel/livekit/tools.py,sha256=-TnlCRB1toKNJi6ix2HvteQ4TWMtxU_99hS8R7Xjvek,1048
377
+ blaxel/livekit/tools.py,sha256=QipxGDnKqma_ktzTUpKgzdp5x4bvpQnxEVoqSTBesu8,1053
378
378
  blaxel/llamaindex/__init__.py,sha256=iZ3QbZhlwKvP91ChcqSXVkpRrzurMxJoQfKdZFzE2AA,127
379
379
  blaxel/llamaindex/model.py,sha256=FYUCTA80LKC4-UfESh43htoHrsoZjwwVaxXD51T0IuE,2557
380
380
  blaxel/llamaindex/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -383,7 +383,7 @@ blaxel/llamaindex/custom/cohere.py,sha256=zoUv4NWwMZLZEynYTC3JuOvtinguRgtuRwS31w
383
383
  blaxel/openai/__init__.py,sha256=YkizVtcYL2m9v-z5B1EReYVu9n9V-DCxJhSB2mvqOs0,123
384
384
  blaxel/openai/model.py,sha256=lGz4zrV4sURPb6aLtroMRV5-CgfQUq15PeTgjc7QkTI,600
385
385
  blaxel/openai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
386
- blaxel/openai/tools.py,sha256=De6Gjiu9pnX-jVUiueCWvUl8hXcnLgrqcWjAIMDEbIo,894
386
+ blaxel/openai/tools.py,sha256=XnbQt8AvvmCHjoQIe3AhylmGi3bwTJIrdmXm--sldLg,834
387
387
  blaxel/pydantic/__init__.py,sha256=-UDZ5VSrlgfqErJuiuphcAFwesijzXxYLeyC7yHEDrE,128
388
388
  blaxel/pydantic/model.py,sha256=1oPf1EH01wvbgBS-w89L73nQrII6VNkZiRIuJYmrMms,3396
389
389
  blaxel/pydantic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -402,7 +402,7 @@ blaxel/telemetry/instrumentation/map.py,sha256=PCzZJj39yiYVYJrxLBNP-NW-tjjYyTijw
402
402
  blaxel/telemetry/instrumentation/utils.py,sha256=KInMYZH-mu9_wvetmf0EmgrfN3Sw8IWk2Y95v2u90_U,1901
403
403
  blaxel/telemetry/log/log.py,sha256=RvQByRjZMoP_dRaAZu8oK6DTegsHs-xV4W-UIqis6CA,2461
404
404
  blaxel/telemetry/log/logger.py,sha256=NPAS3g82ryROjvc_DEZaTIfrcehoLEZoP-JkLxADxc0,4113
405
- blaxel-0.2.2.dist-info/METADATA,sha256=PH7unMpL-kREYXRqTdJwkNB7Xkb2sbRh6e2Y09c0BWk,9875
406
- blaxel-0.2.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
407
- blaxel-0.2.2.dist-info/licenses/LICENSE,sha256=p5PNQvpvyDT_0aYBDgmV1fFI_vAD2aSV0wWG7VTgRis,1069
408
- blaxel-0.2.2.dist-info/RECORD,,
405
+ blaxel-0.2.3.dist-info/METADATA,sha256=QgO7ehwf9t_mx9IdU9orVDZIlufpL2pgIXkGWRzKKyg,9875
406
+ blaxel-0.2.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
407
+ blaxel-0.2.3.dist-info/licenses/LICENSE,sha256=p5PNQvpvyDT_0aYBDgmV1fFI_vAD2aSV0wWG7VTgRis,1069
408
+ blaxel-0.2.3.dist-info/RECORD,,
File without changes