flock-core 0.2.4__py3-none-any.whl → 0.2.6__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 flock-core might be problematic. Click here for more details.

@@ -1,10 +1,11 @@
1
1
  """Mixin class for integrating with the dspy library."""
2
2
 
3
+ import inspect
3
4
  import sys
4
5
  from typing import Any, Literal
5
6
 
6
7
  from flock.core.logging.logging import get_logger
7
- from flock.core.util.input_resolver import split_top_level
8
+ from flock.core.util.input_resolver import get_callable_members, split_top_level
8
9
 
9
10
  logger = get_logger("flock")
10
11
 
@@ -68,15 +69,19 @@ class DSPyIntegrationMixin:
68
69
  # TODO: We have to find a way to avoid using eval here.
69
70
  # This is a security risk, as it allows arbitrary code execution.
70
71
 
71
- try:
72
- field_type = eval(type_str, sys.modules[__name__].__dict__)
73
- except Exception:
74
- field_type = eval(
75
- type_str, sys.modules["__main__"].__dict__
76
- )
72
+ field_type = dspy.PythonInterpreter(
73
+ sys.modules[__name__].__dict__
74
+ | sys.modules["__main__"].__dict__
75
+ ).execute(type_str)
76
+
77
+ # try:
78
+ # field_type = eval(type_str, sys.modules[__name__].__dict__)
79
+ # except Exception:
80
+ # field_type = eval(
81
+ # type_str, sys.modules["__main__"].__dict__
82
+ # )
77
83
 
78
84
  except Exception:
79
- # If evaluation fails, default to str.
80
85
  field_type = str
81
86
 
82
87
  return name, field_type, desc
@@ -143,6 +148,14 @@ class DSPyIntegrationMixin:
143
148
  """
144
149
  import dspy
145
150
 
151
+ processed_tools = []
152
+ if self.tools:
153
+ for tool in self.tools:
154
+ if inspect.ismodule(tool) or inspect.isclass(tool):
155
+ processed_tools.extend(get_callable_members(tool))
156
+ else:
157
+ processed_tools.append(tool)
158
+
146
159
  dspy_solver = None
147
160
 
148
161
  if agent_type_override:
@@ -153,7 +166,7 @@ class DSPyIntegrationMixin:
153
166
  if agent_type_override == "ReAct":
154
167
  dspy.ReAct(
155
168
  signature,
156
- tools=self.tools,
169
+ tools=processed_tools,
157
170
  max_iters=10,
158
171
  )
159
172
  if agent_type_override == "Completion":
@@ -164,7 +177,7 @@ class DSPyIntegrationMixin:
164
177
  if self.tools:
165
178
  dspy_solver = dspy.ReAct(
166
179
  signature,
167
- tools=self.tools,
180
+ tools=processed_tools,
168
181
  max_iters=10,
169
182
  )
170
183
  else:
@@ -2,29 +2,14 @@
2
2
 
3
3
  import importlib
4
4
  import os
5
+ from typing import Literal
5
6
 
6
7
  from flock.core.logging.trace_and_logged import traced_and_logged
8
+ from flock.interpreter.python_interpreter import PythonInterpreter
7
9
 
8
10
 
9
11
  @traced_and_logged
10
12
  def web_search_tavily(query: str):
11
- """Performs a web search using the Tavily client.
12
-
13
- This function checks if the optional 'tavily' dependency is installed. If so,
14
- it creates a TavilyClient using the API key from the environment variable
15
- 'TAVILY_API_KEY' and performs a search with the provided query. The search response
16
- is returned if successful.
17
-
18
- Parameters:
19
- query (str): The search query string.
20
-
21
- Returns:
22
- Any: The search response obtained from the Tavily client.
23
-
24
- Raises:
25
- ImportError: If the 'tavily' dependency is not installed.
26
- Exception: Re-raises any exceptions encountered during the search.
27
- """
28
13
  if importlib.util.find_spec("tavily") is not None:
29
14
  from tavily import TavilyClient
30
15
 
@@ -41,22 +26,24 @@ def web_search_tavily(query: str):
41
26
 
42
27
 
43
28
  @traced_and_logged
44
- def get_web_content_as_markdown(url: str):
45
- """Fetches web content from a URL and converts it to Markdown.
29
+ def web_search_duckduckgo(
30
+ keywords: str, search_type: Literal["news", "web"] = "web"
31
+ ):
32
+ try:
33
+ from duckduckgo_search import DDGS
46
34
 
47
- This function uses the 'httpx' library to retrieve the content of the provided URL.
48
- It then converts the HTML content into Markdown using the 'markdownify' library.
35
+ if search_type == "news":
36
+ response = DDGS().news(keywords)
37
+ else:
38
+ response = DDGS().text(keywords)
49
39
 
50
- Parameters:
51
- url (str): The URL of the web page to fetch.
40
+ return response
41
+ except Exception:
42
+ raise
52
43
 
53
- Returns:
54
- str: The web page content converted into Markdown format.
55
44
 
56
- Raises:
57
- ImportError: If either 'httpx' or 'markdownify' dependencies are not installed.
58
- Exception: Re-raises any exceptions encountered during the HTTP request or conversion.
59
- """
45
+ @traced_and_logged
46
+ def get_web_content_as_markdown(url: str):
60
47
  if (
61
48
  importlib.util.find_spec("httpx") is not None
62
49
  and importlib.util.find_spec("markdownify") is not None
@@ -79,22 +66,6 @@ def get_web_content_as_markdown(url: str):
79
66
 
80
67
  @traced_and_logged
81
68
  def get_anything_as_markdown(url_or_file_path: str):
82
- """Converts the content of a URL or file into Markdown format.
83
-
84
- This function leverages the 'docling' library to convert various document types
85
- (retrieved from a URL or a local file) into Markdown. It uses the DocumentConverter
86
- from the 'docling.document_converter' module.
87
-
88
- Parameters:
89
- url_or_file_path (str): The URL or local file path of the document to convert.
90
-
91
- Returns:
92
- str: The converted document in Markdown format.
93
-
94
- Raises:
95
- ImportError: If the 'docling' dependency is not installed.
96
- Exception: Re-raises any exceptions encountered during the document conversion.
97
- """
98
69
  if importlib.util.find_spec("docling") is not None:
99
70
  from docling.document_converter import DocumentConverter
100
71
 
@@ -113,49 +84,53 @@ def get_anything_as_markdown(url_or_file_path: str):
113
84
 
114
85
  @traced_and_logged
115
86
  def evaluate_math(expression: str) -> float:
116
- """Evaluates a mathematical expression using the dspy interpreter.
117
-
118
- This function uses the 'dspy' library's PythonInterpreter to evaluate the provided
119
- mathematical expression.
120
-
121
- Parameters:
122
- expression (str): A string containing the mathematical expression to evaluate.
123
-
124
- Returns:
125
- float: The result of the evaluated expression.
126
-
127
- Raises:
128
- Exception: Re-raises any exceptions encountered during the evaluation.
129
- """
130
- import dspy
131
-
132
87
  try:
133
- result = dspy.PythonInterpreter({}).execute(expression)
88
+ result = PythonInterpreter(
89
+ {},
90
+ [
91
+ "os",
92
+ "math",
93
+ "random",
94
+ "datetime",
95
+ "time",
96
+ "string",
97
+ "collections",
98
+ "itertools",
99
+ "functools",
100
+ "typing",
101
+ "enum",
102
+ "json",
103
+ "ast",
104
+ ],
105
+ verbose=True,
106
+ ).execute(expression)
134
107
  return result
135
108
  except Exception:
136
109
  raise
137
110
 
138
111
 
139
112
  @traced_and_logged
140
- def code_eval(python_code: str) -> float:
141
- """Executes Python code using the dspy interpreter.
142
-
143
- This function takes a string of Python code, executes it using the 'dspy' PythonInterpreter,
144
- and returns the result.
145
-
146
- Parameters:
147
- python_code (str): A string containing Python code to execute.
148
-
149
- Returns:
150
- float: The result of the executed code.
151
-
152
- Raises:
153
- Exception: Re-raises any exceptions encountered during code execution.
154
- """
155
- import dspy
156
-
113
+ def code_eval(python_code: str) -> str:
157
114
  try:
158
- result = dspy.PythonInterpreter({}).execute(python_code)
115
+ result = PythonInterpreter(
116
+ {},
117
+ [
118
+ "os",
119
+ "math",
120
+ "random",
121
+ "datetime",
122
+ "time",
123
+ "string",
124
+ "collections",
125
+ "itertools",
126
+ "functools",
127
+ "typing",
128
+ "enum",
129
+ "json",
130
+ "ast",
131
+ ],
132
+ verbose=True,
133
+ ).execute(python_code)
159
134
  return result
160
135
  except Exception:
161
136
  raise
@@ -163,11 +138,6 @@ def code_eval(python_code: str) -> float:
163
138
 
164
139
  @traced_and_logged
165
140
  def get_current_time() -> str:
166
- """Retrieves the current time in ISO 8601 format.
167
-
168
- Returns:
169
- str: The current date and time as an ISO 8601 formatted string.
170
- """
171
141
  import datetime
172
142
 
173
143
  time = datetime.datetime.now().isoformat()
@@ -176,33 +146,12 @@ def get_current_time() -> str:
176
146
 
177
147
  @traced_and_logged
178
148
  def count_words(text: str) -> int:
179
- """Counts the number of words in the provided text.
180
-
181
- This function splits the input text by whitespace and returns the count of resulting words.
182
-
183
- Parameters:
184
- text (str): The text in which to count words.
185
-
186
- Returns:
187
- int: The number of words in the text.
188
- """
189
149
  count = len(text.split())
190
150
  return count
191
151
 
192
152
 
193
153
  @traced_and_logged
194
154
  def extract_urls(text: str) -> list[str]:
195
- """Extracts all URLs from the given text.
196
-
197
- This function uses a regular expression to find all substrings that match the typical
198
- URL pattern (starting with http or https).
199
-
200
- Parameters:
201
- text (str): The text from which to extract URLs.
202
-
203
- Returns:
204
- list[str]: A list of URLs found in the text.
205
- """
206
155
  import re
207
156
 
208
157
  url_pattern = r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+"
@@ -212,17 +161,6 @@ def extract_urls(text: str) -> list[str]:
212
161
 
213
162
  @traced_and_logged
214
163
  def extract_numbers(text: str) -> list[float]:
215
- """Extracts all numerical values from the provided text.
216
-
217
- This function uses a regular expression to find substrings that represent integers or decimals,
218
- converts them to floats, and returns them as a list.
219
-
220
- Parameters:
221
- text (str): The text from which to extract numerical values.
222
-
223
- Returns:
224
- list[float]: A list of numbers (as floats) found in the text.
225
- """
226
164
  import re
227
165
 
228
166
  numbers = [float(x) for x in re.findall(r"-?\d*\.?\d+", text)]
@@ -231,17 +169,6 @@ def extract_numbers(text: str) -> list[float]:
231
169
 
232
170
  @traced_and_logged
233
171
  def json_parse_safe(text: str) -> dict:
234
- """Safely parses a JSON string into a dictionary.
235
-
236
- This function attempts to load a JSON object from the given text. If parsing fails,
237
- it returns an empty dictionary instead of raising an exception.
238
-
239
- Parameters:
240
- text (str): The JSON-formatted string to parse.
241
-
242
- Returns:
243
- dict: The parsed JSON object as a dictionary, or an empty dictionary if parsing fails.
244
- """
245
172
  import json
246
173
 
247
174
  try:
@@ -253,18 +180,6 @@ def json_parse_safe(text: str) -> dict:
253
180
 
254
181
  @traced_and_logged
255
182
  def save_to_file(content: str, filename: str):
256
- """Saves the given content to a file.
257
-
258
- This function writes the provided content to a file specified by the filename.
259
- If the file cannot be written, an exception is raised.
260
-
261
- Parameters:
262
- content (str): The content to be saved.
263
- filename (str): The path to the file where the content will be saved.
264
-
265
- Raises:
266
- Exception: Re-raises any exceptions encountered during the file write operation.
267
- """
268
183
  try:
269
184
  with open(filename, "w") as f:
270
185
  f.write(content)
@@ -274,20 +189,6 @@ def save_to_file(content: str, filename: str):
274
189
 
275
190
  @traced_and_logged
276
191
  def read_from_file(filename: str) -> str:
277
- """Reads and returns the content of a file.
278
-
279
- This function opens the specified file, reads its content, and returns it as a string.
280
- If the file cannot be read, an exception is raised.
281
-
282
- Parameters:
283
- filename (str): The path to the file to be read.
284
-
285
- Returns:
286
- str: The content of the file.
287
-
288
- Raises:
289
- Exception: Re-raises any exceptions encountered during the file read operation.
290
- """
291
192
  try:
292
193
  with open(filename) as f:
293
194
  content = f.read()
@@ -10,23 +10,6 @@ from flock.core.logging.trace_and_logged import traced_and_logged
10
10
 
11
11
  @traced_and_logged
12
12
  def create_user_stories_as_github_issue(title: str, body: str) -> str:
13
- """Create a new GitHub issue representing a user story.
14
-
15
- This function creates an issue in a GitHub repository using the specified title and body.
16
- The title is used as the issue title, and the body should contain the full user story
17
- description along with a formatted list of acceptance criteria. The following
18
- environment variables must be set for this function to work correctly:
19
-
20
- - GITHUB_PAT: Personal Access Token for GitHub API authentication.
21
- - GITHUB_REPO: Repository identifier in the format "owner/repo".
22
-
23
- Parameters:
24
- title (str): The title for the GitHub issue (user story).
25
- body (str): The detailed description including acceptance criteria.
26
-
27
- Returns:
28
- str: A message indicating whether the issue was created successfully or not.
29
- """
30
13
  github_pat = os.getenv("GITHUB_PAT")
31
14
  github_repo = os.getenv("GITHUB_REPO")
32
15
 
@@ -49,22 +32,6 @@ def create_user_stories_as_github_issue(title: str, body: str) -> str:
49
32
 
50
33
  @traced_and_logged
51
34
  def upload_readme(content: str):
52
- """Upload or update the README.md file in a GitHub repository.
53
-
54
- This function uses the GitHub API to either create a new README.md file or update an
55
- existing one in the specified repository. It encodes the provided content to base64 before
56
- sending it via the API. The function requires the following environment variables to be set:
57
-
58
- - GITHUB_USERNAME: Your GitHub username.
59
- - GITHUB_REPO: The name of the repository.
60
- - GITHUB_PAT: Your GitHub Personal Access Token for authentication.
61
-
62
- Parameters:
63
- content (str): The text content to be written into the README.md file.
64
-
65
- Raises:
66
- ValueError: If any of the required environment variables are missing.
67
- """
68
35
  GITHUB_USERNAME = os.getenv("GITHUB_USERNAME")
69
36
  REPO_NAME = os.getenv("GITHUB_REPO")
70
37
  GITHUB_TOKEN = os.getenv("GITHUB_PAT")
@@ -3,6 +3,25 @@
3
3
  from flock.core.context.context import FlockContext
4
4
 
5
5
 
6
+ def get_callable_members(obj):
7
+ """Extract all callable (methods/functions) members from a module or class.
8
+ Returns a list of callable objects.
9
+ """
10
+ import inspect
11
+
12
+ # Get all members of the object
13
+ members = inspect.getmembers(obj)
14
+
15
+ # Filter for callable members that don't start with underscore (to exclude private/special methods)
16
+ callables = [
17
+ member[1]
18
+ for member in members
19
+ if inspect.isroutine(member[1]) and not member[0].startswith("_")
20
+ ]
21
+
22
+ return callables
23
+
24
+
6
25
  def split_top_level(s: str) -> list[str]:
7
26
  """Split a string on commas that are not enclosed within brackets, parentheses, or quotes.
8
27