camel-ai 0.2.35__py3-none-any.whl → 0.2.36__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.

Potentially problematic release.


This version of camel-ai might be problematic. Click here for more details.

@@ -0,0 +1,224 @@
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+
15
+ import logging
16
+ import os
17
+ from datetime import datetime
18
+ from typing import Any, Dict, List, Optional
19
+ from uuid import UUID
20
+
21
+ from camel.memories.records import MemoryRecord
22
+ from camel.messages import BaseMessage
23
+ from camel.storages.key_value_storages import BaseKeyValueStorage
24
+ from camel.types import OpenAIBackendRole, RoleType
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class Mem0Storage(BaseKeyValueStorage):
30
+ r"""A concrete implementation of the :obj:`BaseKeyValueStorage` using Mem0
31
+ as the backend. This storage system uses Mem0's text capabilities to store,
32
+ search, and manage text with context.
33
+
34
+ Args:
35
+ agent_id (str): Default agent ID to associate memories with.
36
+ api_key (str, optional): The API key for authentication. If not
37
+ provided, will try to get from environment variable MEM0_API_KEY
38
+ (default: :obj:`None`).
39
+ user_id (str, optional): Default user ID to associate memories with
40
+ (default: :obj:`None`).
41
+ metadata (Dict[str, Any], optional): Default metadata to include with
42
+ all memories (default: :obj:`None`).
43
+
44
+ References:
45
+ https://docs.mem0.ai
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ agent_id: str,
51
+ api_key: Optional[str] = None,
52
+ user_id: Optional[str] = None,
53
+ metadata: Optional[Dict[str, Any]] = None,
54
+ ) -> None:
55
+ try:
56
+ from mem0 import MemoryClient
57
+ except ImportError as exc:
58
+ logger.error(
59
+ "Please install `mem0` first. You can install it by "
60
+ "running `pip install mem0ai`."
61
+ )
62
+ raise exc
63
+
64
+ self.api_key = api_key or os.getenv("MEM0_API_KEY")
65
+ if not self.api_key:
66
+ raise ValueError(
67
+ "API key must be provided either through constructor "
68
+ "or MEM0_API_KEY environment variable."
69
+ )
70
+
71
+ self.client = MemoryClient(api_key=self.api_key)
72
+ self.agent_id = agent_id
73
+ self.user_id = user_id
74
+ self.metadata = metadata or {}
75
+
76
+ def _prepare_options(
77
+ self,
78
+ agent_id: Optional[str] = None,
79
+ user_id: Optional[str] = None,
80
+ metadata: Optional[Dict[str, Any]] = None,
81
+ **kwargs: Any,
82
+ ) -> Dict[str, Any]:
83
+ r"""Helper method to prepare options for Mem0 API calls.
84
+
85
+ Args:
86
+ agent_id (Optional[str], optional): Agent ID to use (default:
87
+ :obj:`None`).
88
+ user_id (Optional[str], optional): User ID to use (default:
89
+ :obj:`None`).
90
+ metadata (Optional[Dict[str, Any]], optional): Additional metadata
91
+ to include (default: :obj:`None`).
92
+ **kwargs (Any): Additional keyword arguments.
93
+
94
+ Returns:
95
+ Dict[str, Any]: Prepared options dictionary for API calls.
96
+ """
97
+ options = {
98
+ "agent_id": agent_id or self.agent_id,
99
+ "user_id": user_id or self.user_id,
100
+ "metadata": {**self.metadata, **(metadata or {})},
101
+ "output_format": "v1.1",
102
+ **kwargs,
103
+ }
104
+ return {k: v for k, v in options.items() if v is not None}
105
+
106
+ def _prepare_filters(
107
+ self,
108
+ agent_id: Optional[str] = None,
109
+ user_id: Optional[str] = None,
110
+ filters: Optional[Dict[str, Any]] = None,
111
+ ) -> Dict[str, Any]:
112
+ r"""Helper method to prepare filters for Mem0 API calls.
113
+
114
+ Args:
115
+ agent_id (Optional[str], optional): Agent ID to filter by
116
+ (default: :obj:`None`).
117
+ user_id (Optional[str], optional): User ID to filter by (default:
118
+ :obj:`None`).
119
+ filters (Optional[Dict[str, Any]], optional): Additional filters
120
+ (default: :obj:`None`).
121
+
122
+ Returns:
123
+ Dict[str, Any]: Prepared filters dictionary for API calls.
124
+ """
125
+ base_filters: Dict[str, Any] = {"AND": []}
126
+ if filters:
127
+ base_filters["AND"].append(filters)
128
+ if agent_id or self.agent_id:
129
+ base_filters["AND"].append({"agent_id": agent_id or self.agent_id})
130
+ if user_id or self.user_id:
131
+ base_filters["AND"].append({"user_id": user_id or self.user_id})
132
+ return base_filters if base_filters["AND"] else {}
133
+
134
+ def _prepare_messages(
135
+ self,
136
+ records: List[Dict[str, Any]],
137
+ ) -> List[Dict[str, Any]]:
138
+ r"""Prepare messages from records for Mem0 API calls.
139
+
140
+ Args:
141
+ records (List[Dict[str, Any]]): List of record dictionaries.
142
+
143
+ Returns:
144
+ List[Dict[str, Any]]: List of prepared message dictionaries.
145
+ """
146
+ messages = []
147
+ for record in records:
148
+ content = record["message"]["content"]
149
+ role = record["role_at_backend"].value
150
+ messages.append({"role": role, "content": content})
151
+ return messages
152
+
153
+ def save(self, records: List[Dict[str, Any]]) -> None:
154
+ r"""Saves a batch of records to the Mem0 storage system.
155
+
156
+ Args:
157
+ records (List[Dict[str, Any]]): A list of dictionaries, where each
158
+ dictionary represents a unique record to be stored.
159
+ """
160
+ try:
161
+ messages = self._prepare_messages(records)
162
+
163
+ options = self._prepare_options(
164
+ agent_id=self.agent_id,
165
+ user_id=self.user_id,
166
+ metadata=self.metadata,
167
+ )
168
+ self.client.add(messages, **options)
169
+ except Exception as e:
170
+ logger.error(f"Error adding memory: {e}")
171
+ logger.error(f"Error: {e}")
172
+
173
+ def load(self) -> List[Dict[str, Any]]:
174
+ r"""Loads all stored records from the Mem0 storage system.
175
+
176
+ Returns:
177
+ List[Dict[str, Any]]: A list of dictionaries, where each dictionary
178
+ represents a stored record.
179
+ """
180
+ try:
181
+ filters = self._prepare_filters(
182
+ agent_id=self.agent_id,
183
+ user_id=self.user_id,
184
+ )
185
+ results = self.client.get_all(version="v2", **filters)
186
+
187
+ # Transform results into MemoryRecord objects
188
+ transformed_results = []
189
+ for result in results:
190
+ memory_record = MemoryRecord(
191
+ uuid=UUID(result["id"]),
192
+ message=BaseMessage(
193
+ role_name="user",
194
+ role_type=RoleType.USER,
195
+ meta_dict={},
196
+ content=result["memory"],
197
+ ),
198
+ role_at_backend=OpenAIBackendRole.USER,
199
+ extra_info=result.get("metadata", {}),
200
+ timestamp=datetime.fromisoformat(
201
+ result["created_at"]
202
+ ).timestamp(),
203
+ agent_id=result.get("agent_id", ""),
204
+ )
205
+ transformed_results.append(memory_record.to_dict())
206
+
207
+ return transformed_results
208
+ except Exception as e:
209
+ logger.error(f"Error searching memories: {e}")
210
+ return []
211
+
212
+ def clear(
213
+ self,
214
+ ) -> None:
215
+ r"""Removes all records from the Mem0 storage system."""
216
+ try:
217
+ filters = self._prepare_filters(
218
+ agent_id=self.agent_id,
219
+ user_id=self.user_id,
220
+ )
221
+ self.client.delete_users(**filters)
222
+ except Exception as e:
223
+ logger.error(f"Error deleting memories: {e}")
224
+ logger.error(f"Error: {e}")
@@ -450,9 +450,9 @@ class QdrantStorage(BaseVectorStorage):
450
450
  search_filter = Filter(must=cast(List[Condition], must_conditions))
451
451
 
452
452
  # Execute the search with optional filter
453
- search_result = self._client.search(
453
+ search_result = self._client.query_points(
454
454
  collection_name=self.collection_name,
455
- query_vector=query.query_vector,
455
+ query=query.query_vector,
456
456
  with_payload=True,
457
457
  with_vectors=True,
458
458
  limit=query.top_k,
@@ -467,7 +467,7 @@ class QdrantStorage(BaseVectorStorage):
467
467
  payload=point.payload,
468
468
  vector=point.vector, # type: ignore[arg-type]
469
469
  )
470
- for point in search_result
470
+ for point in search_result.points
471
471
  ]
472
472
 
473
473
  return query_results
@@ -438,6 +438,7 @@ class BaseBrowser:
438
438
  sync_playwright,
439
439
  )
440
440
 
441
+ self._ensure_browser_installed()
441
442
  self.history: list = []
442
443
  self.headless = headless
443
444
  self.playwright = sync_playwright().start()
@@ -914,6 +915,48 @@ class BaseBrowser:
914
915
  markdown_content = html2text(html_content)
915
916
  return markdown_content
916
917
 
918
+ def _ensure_browser_installed(self) -> None:
919
+ r"""Ensure the browser is installed."""
920
+ import platform
921
+ import subprocess
922
+ import sys
923
+
924
+ try:
925
+ from playwright.sync_api import sync_playwright
926
+
927
+ with sync_playwright() as p:
928
+ browser = p.chromium.launch()
929
+ browser.close()
930
+ except Exception:
931
+ logger.info("Installing Chromium browser...")
932
+ try:
933
+ subprocess.run(
934
+ [
935
+ sys.executable,
936
+ "-m",
937
+ "playwright",
938
+ "install",
939
+ "chromium",
940
+ ],
941
+ check=True,
942
+ capture_output=True,
943
+ )
944
+ if platform.system().lower() == "linux":
945
+ subprocess.run(
946
+ [
947
+ sys.executable,
948
+ "-m",
949
+ "playwright",
950
+ "install-deps",
951
+ "chromium",
952
+ ],
953
+ check=True,
954
+ capture_output=True,
955
+ )
956
+ logger.info("Chromium browser installation completed")
957
+ except subprocess.CalledProcessError as e:
958
+ raise RuntimeError(f"Failed to install browser: {e.stderr}")
959
+
917
960
 
918
961
  class BrowserToolkit(BaseToolkit):
919
962
  r"""A class for browsing the web and interacting with web pages.
@@ -29,6 +29,7 @@ class CodeExecutionToolkit(BaseToolkit):
29
29
 
30
30
  Args:
31
31
  sandbox (str): The environment type used to execute code.
32
+ (default: `subprocess`)
32
33
  verbose (bool): Whether to print the output of the code execution.
33
34
  (default: :obj:`False`)
34
35
  unsafe_mode (bool): If `True`, the interpreter runs the code
@@ -43,7 +44,7 @@ class CodeExecutionToolkit(BaseToolkit):
43
44
  self,
44
45
  sandbox: Literal[
45
46
  "internal_python", "jupyter", "docker", "subprocess", "e2b"
46
- ] = "internal_python",
47
+ ] = "subprocess",
47
48
  verbose: bool = False,
48
49
  unsafe_mode: bool = False,
49
50
  import_white_list: Optional[List[str]] = None,
@@ -56,6 +56,8 @@ class _MCPServer(BaseToolkit):
56
56
  env (Dict[str, str]): Environment variables for the stdio mode command.
57
57
  (default: :obj:`'None'`)
58
58
  timeout (Optional[float]): Connection timeout. (default: :obj:`'None'`)
59
+ headers (Dict[str, str]): Headers for the HTTP request.
60
+ (default: :obj:`'None'`)
59
61
  """
60
62
 
61
63
  def __init__(
@@ -64,6 +66,7 @@ class _MCPServer(BaseToolkit):
64
66
  args: Optional[List[str]] = None,
65
67
  env: Optional[Dict[str, str]] = None,
66
68
  timeout: Optional[float] = None,
69
+ headers: Optional[Dict[str, str]] = None,
67
70
  ):
68
71
  from mcp import Tool
69
72
  from mcp.client.session import ClientSession
@@ -73,6 +76,7 @@ class _MCPServer(BaseToolkit):
73
76
  self.command_or_url = command_or_url
74
77
  self.args = args or []
75
78
  self.env = env or {}
79
+ self.headers = headers or {}
76
80
 
77
81
  self._mcp_tools: List[Tool] = []
78
82
  self._session: Optional['ClientSession'] = None
@@ -99,7 +103,10 @@ class _MCPServer(BaseToolkit):
99
103
  read_stream,
100
104
  write_stream,
101
105
  ) = await self._exit_stack.enter_async_context(
102
- sse_client(self.command_or_url)
106
+ sse_client(
107
+ self.command_or_url,
108
+ headers=self.headers,
109
+ )
103
110
  )
104
111
  else:
105
112
  command = self.command_or_url
@@ -343,6 +350,27 @@ class MCPToolkit(BaseToolkit):
343
350
  Either `servers` or `config_path` must be provided. If both are
344
351
  provided, servers from both sources will be combined.
345
352
 
353
+ For web servers in the config file, you can specify authorization
354
+ headers using the "headers" field to connect to protected MCP server
355
+ endpoints.
356
+
357
+ Example configuration:
358
+
359
+ .. code-block:: json
360
+
361
+ {
362
+ "mcpWebServers": {
363
+ "protected-server": {
364
+ "url": "https://example.com/mcp",
365
+ "timeout": 30,
366
+ "headers": {
367
+ "Authorization": "Bearer YOUR_TOKEN",
368
+ "X-API-Key": "YOUR_API_KEY"
369
+ }
370
+ }
371
+ }
372
+ }
373
+
346
374
  Attributes:
347
375
  servers (List[_MCPServer]): List of _MCPServer instances being managed.
348
376
  """
@@ -442,6 +470,7 @@ class MCPToolkit(BaseToolkit):
442
470
  server = _MCPServer(
443
471
  command_or_url=cfg["url"],
444
472
  timeout=cfg.get("timeout", None),
473
+ headers=cfg.get("headers", {}),
445
474
  )
446
475
  all_servers.append(server)
447
476
 
camel/types/enums.py CHANGED
@@ -63,6 +63,11 @@ class ModelType(UnifiedModelType, Enum):
63
63
  GROQ_MIXTRAL_8_7B = "mixtral-8x7b-32768"
64
64
  GROQ_GEMMA_2_9B_IT = "gemma2-9b-it"
65
65
 
66
+ # OpenRouter models
67
+ OPENROUTER_LLAMA_3_1_405B = "meta-llama/llama-3.3-405b-instruct"
68
+ OPENROUTER_LLAMA_3_1_70B = "meta-llama/llama-3.3-70b-instruct"
69
+ OPENROUTER_OLYMPICODER_7B = "open-r1/olympiccoder-7b:free"
70
+
66
71
  # TogetherAI platform models support tool calling
67
72
  TOGETHER_LLAMA_3_1_8B = "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo"
68
73
  TOGETHER_LLAMA_3_1_70B = "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"
@@ -253,6 +258,7 @@ class ModelType(UnifiedModelType, Enum):
253
258
  self.is_together,
254
259
  self.is_sambanova,
255
260
  self.is_groq,
261
+ self.is_openrouter,
256
262
  self.is_sglang,
257
263
  self.is_moonshot,
258
264
  self.is_siliconflow,
@@ -342,6 +348,15 @@ class ModelType(UnifiedModelType, Enum):
342
348
  ModelType.GROQ_GEMMA_2_9B_IT,
343
349
  }
344
350
 
351
+ @property
352
+ def is_openrouter(self) -> bool:
353
+ r"""Returns whether this type of models is served by OpenRouter."""
354
+ return self in {
355
+ ModelType.OPENROUTER_LLAMA_3_1_405B,
356
+ ModelType.OPENROUTER_LLAMA_3_1_70B,
357
+ ModelType.OPENROUTER_OLYMPICODER_7B,
358
+ }
359
+
345
360
  @property
346
361
  def is_together(self) -> bool:
347
362
  r"""Returns whether this type of models is served by Together AI."""
@@ -580,6 +595,7 @@ class ModelType(UnifiedModelType, Enum):
580
595
  ModelType.MOONSHOT_V1_8K,
581
596
  ModelType.GLM_4V_FLASH,
582
597
  ModelType.GLM_4_AIRX,
598
+ ModelType.OPENROUTER_OLYMPICODER_7B,
583
599
  }:
584
600
  return 8_192
585
601
  elif self in {
@@ -686,6 +702,8 @@ class ModelType(UnifiedModelType, Enum):
686
702
  ModelType.SGLANG_QWEN_2_5_7B,
687
703
  ModelType.SGLANG_QWEN_2_5_32B,
688
704
  ModelType.SGLANG_QWEN_2_5_72B,
705
+ ModelType.OPENROUTER_LLAMA_3_1_70B,
706
+ ModelType.OPENROUTER_LLAMA_3_1_405B,
689
707
  }:
690
708
  return 131_072
691
709
  elif self in {
@@ -881,6 +899,7 @@ class ModelPlatformType(Enum):
881
899
  AZURE = "azure"
882
900
  ANTHROPIC = "anthropic"
883
901
  GROQ = "groq"
902
+ OPENROUTER = "openrouter"
884
903
  OLLAMA = "ollama"
885
904
  LITELLM = "litellm"
886
905
  ZHIPU = "zhipuai"
@@ -931,6 +950,11 @@ class ModelPlatformType(Enum):
931
950
  r"""Returns whether this platform is groq."""
932
951
  return self is ModelPlatformType.GROQ
933
952
 
953
+ @property
954
+ def is_openrouter(self) -> bool:
955
+ r"""Returns whether this platform is openrouter."""
956
+ return self is ModelPlatformType.OPENROUTER
957
+
934
958
  @property
935
959
  def is_ollama(self) -> bool:
936
960
  r"""Returns whether this platform is ollama."""
@@ -78,6 +78,11 @@ class UnifiedModelType(str):
78
78
  r"""Returns whether the model is a Groq served model."""
79
79
  return True
80
80
 
81
+ @property
82
+ def is_openrouter(self) -> bool:
83
+ r"""Returns whether the model is a OpenRouter served model."""
84
+ return True
85
+
81
86
  @property
82
87
  def is_zhipuai(self) -> bool:
83
88
  r"""Returns whether the model is a Zhipuai model."""
@@ -12,12 +12,11 @@
12
12
  # limitations under the License.
13
13
  # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  from .base import BaseVerifier
15
- from .models import VerificationOutcome, VerifierInput
15
+ from .models import VerificationOutcome
16
16
  from .python_verifier import PythonVerifier
17
17
 
18
18
  __all__ = [
19
19
  "BaseVerifier",
20
20
  "VerificationOutcome",
21
- "VerifierInput",
22
21
  "PythonVerifier",
23
22
  ]