Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

fix style (#8337)

Chen Qianb30c55cfbb9b
diff --git a/dspy/predict/code_act.py b/dspy/predict/code_act.py
index e59bd1987..90a7fcd3b 100644
--- a/dspy/predict/code_act.py
+++ b/dspy/predict/code_act.py
@@ -1,7 +1,7 @@
import inspect
-from typing import Callable, Union, Type, Optional
import logging
from inspect import Signature
+from typing import Callable, Optional, Type, Union
import dspy
from dspy.adapters.types.tool import Tool
@@ -68,7 +68,7 @@ class CodeAct(ReAct, ProgramOfThought):
self.extractor = dspy.ChainOfThought(extract_signature)
# It will raises exception when dspy cannot find available deno instance by now.
self.interpreter = interpreter or PythonInterpreter()
-
+
def _build_instructions(self, signature, tools):
instructions = [f"{signature.instructions}\n"] if signature.instructions else []
inputs = ", ".join([f"`{k}`" for k in signature.input_fields.keys()])
diff --git a/dspy/predict/program_of_thought.py b/dspy/predict/program_of_thought.py
index 9d7e3a325..bd7aa5e29 100644
--- a/dspy/predict/program_of_thought.py
+++ b/dspy/predict/program_of_thought.py
@@ -1,7 +1,7 @@
import json
import logging
import re
-from typing import Type, Union, Optional
+from typing import Optional, Type, Union
import dspy
from dspy.primitives.program import Module
diff --git a/dspy/primitives/python_interpreter.py b/dspy/primitives/python_interpreter.py
index 200d3bf26..1d56eb564 100644
--- a/dspy/primitives/python_interpreter.py
+++ b/dspy/primitives/python_interpreter.py
@@ -1,9 +1,9 @@
import json
import os
import subprocess
+from os import PathLike
from types import TracebackType
from typing import Any, Dict, List, Optional, Union
-from os import PathLike
class InterpreterError(RuntimeError):
@@ -66,7 +66,7 @@ class PythonInterpreter:
args.append(f"--allow-net={','.join(str(x) for x in self.enable_network_access)}")
if self.enable_write_paths:
args.append(f"--allow-write={','.join(str(x) for x in self.enable_write_paths)}")
-
+
args.append(self._get_runner_path())
# For runner.js to load in env vars
diff --git a/dspy/teleprompt/mipro_optimizer_v2.py b/dspy/teleprompt/mipro_optimizer_v2.py
index d80695c6e..f4013d48c 100644
--- a/dspy/teleprompt/mipro_optimizer_v2.py
+++ b/dspy/teleprompt/mipro_optimizer_v2.py
@@ -5,8 +5,7 @@ import sys
import textwrap
import time
from collections import defaultdict
-from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Literal,
- Optional, Tuple)
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple
import numpy as np
@@ -14,12 +13,16 @@ import dspy
from dspy.evaluate.evaluate import Evaluate
from dspy.propose import GroundedProposer
from dspy.teleprompt.teleprompt import Teleprompter
-from dspy.teleprompt.utils import (create_minibatch,
- create_n_fewshot_demo_sets,
- eval_candidate_program,
- get_program_with_highest_avg_score,
- get_signature, print_full_program,
- save_candidate_program, set_signature)
+from dspy.teleprompt.utils import (
+ create_minibatch,
+ create_n_fewshot_demo_sets,
+ eval_candidate_program,
+ get_program_with_highest_avg_score,
+ get_signature,
+ print_full_program,
+ save_candidate_program,
+ set_signature,
+)
if TYPE_CHECKING:
import optuna
diff --git a/tests/adapters/test_base_type.py b/tests/adapters/test_base_type.py
index 878e11cda..5a374406b 100644
--- a/tests/adapters/test_base_type.py
+++ b/tests/adapters/test_base_type.py
@@ -1,7 +1,9 @@
-import dspy
from typing import Optional
+
import pydantic
+import dspy
+
def test_basic_extract_custom_type_from_annotation():
class Event(dspy.BaseType):
diff --git a/tests/primitives/test_python_interpreter.py b/tests/primitives/test_python_interpreter.py
index d66ed0f66..b61cf2988 100644
--- a/tests/primitives/test_python_interpreter.py
+++ b/tests/primitives/test_python_interpreter.py
@@ -1,7 +1,9 @@
+import os
import random
import shutil
-import os
+
import pytest
+
from dspy.primitives.python_interpreter import InterpreterError, PythonInterpreter
# This test suite requires deno to be installed. Please install deno following https://docs.deno.com/runtime/getting_started/installation/
@@ -60,7 +62,7 @@ def test_final_answer_trick():
# They should maintain the same order
assert result == ["The result is", token], "The returned results are differ, `final_answer` trick doesn't work"
-
+
def test_enable_env_vars_flag():
os.environ["FOO_TEST_ENV"] = "test_value"
@@ -84,7 +86,7 @@ def test_read_file_access_control(tmp_path):
with PythonInterpreter(enable_read_paths=[str(testfile_path)]) as interpreter:
code = (
- f"with open({repr(virtual_path)}, 'r') as f:\n"
+ f"with open({virtual_path!r}, 'r') as f:\n"
f" data = f.read()\n"
f"data"
)
@@ -94,7 +96,7 @@ def test_read_file_access_control(tmp_path):
with PythonInterpreter(enable_read_paths=None) as interpreter:
code = (
f"try:\n"
- f" with open({repr(virtual_path)}, 'r') as f:\n"
+ f" with open({virtual_path!r}, 'r') as f:\n"
f" data = f.read()\n"
f"except Exception as e:\n"
f" data = str(e)\n"
@@ -110,7 +112,7 @@ def test_enable_write_flag(tmp_path):
with PythonInterpreter(enable_write_paths=None) as interpreter:
code = (
f"try:\n"
- f" with open({repr(virtual_path)}, 'w') as f:\n"
+ f" with open({virtual_path!r}, 'w') as f:\n"
f" f.write('blocked')\n"
f" result = 'wrote'\n"
f"except Exception as e:\n"
@@ -122,27 +124,27 @@ def test_enable_write_flag(tmp_path):
with PythonInterpreter(enable_write_paths=[str(testfile_path)]) as interpreter:
code = (
- f"with open({repr(virtual_path)}, 'w') as f:\n"
+ f"with open({virtual_path!r}, 'w') as f:\n"
f" f.write('allowed')\n"
f"'ok'"
)
result = interpreter.execute(code)
assert result == "ok", "Test file should be writable with enable_write_paths"
assert testfile_path.exists()
- with open(testfile_path, "r") as f:
+ with open(testfile_path) as f:
assert f.read() == "allowed", "Test file outputs should match content written during execution"
-
+
with open(testfile_path, "w") as f:
f.write("original_content")
with PythonInterpreter(enable_write_paths=[str(testfile_path)], sync_files=False) as interpreter:
code = (
- f"with open({repr(virtual_path)}, 'w') as f:\n"
+ f"with open({virtual_path!r}, 'w') as f:\n"
f" f.write('should_not_sync')\n"
f"'done_no_sync'"
)
result = interpreter.execute(code)
assert result == "done_no_sync"
- with open(testfile_path, "r") as f:
+ with open(testfile_path) as f:
assert f.read() == "original_content", "File should not be changed when sync_files is False"
@@ -153,7 +155,7 @@ def test_enable_net_flag():
with PythonInterpreter(enable_network_access=None) as interpreter:
code = (
"import js\n"
- f"resp = await js.fetch({repr(test_url)})\n"
+ f"resp = await js.fetch({test_url!r})\n"
"resp.status"
)
with pytest.raises(InterpreterError, match="PythonError"):
@@ -162,7 +164,7 @@ def test_enable_net_flag():
with PythonInterpreter(enable_network_access=["example.com"]) as interpreter:
code = (
"import js\n"
- f"resp = await js.fetch({repr(test_url)})\n"
+ f"resp = await js.fetch({test_url!r})\n"
"resp.status"
)
result = interpreter.execute(code)