Skip to content

Commit 62bcf12

Browse files
auto style fix (#8309)
1 parent 8fd1f61 commit 62bcf12

File tree

19 files changed

+53
-61
lines changed

19 files changed

+53
-61
lines changed

dspy/adapters/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from dspy.adapters.chat_adapter import ChatAdapter
33
from dspy.adapters.json_adapter import JSONAdapter
44
from dspy.adapters.two_step_adapter import TwoStepAdapter
5-
from dspy.adapters.types import History, Image, Audio, BaseType, Tool, ToolCalls
5+
from dspy.adapters.types import Audio, BaseType, History, Image, Tool, ToolCalls
66

77
__all__ = [
88
"Adapter",

dspy/adapters/types/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
from dspy.adapters.types.history import History
2-
from dspy.adapters.types.image import Image
31
from dspy.adapters.types.audio import Audio
42
from dspy.adapters.types.base_type import BaseType
3+
from dspy.adapters.types.history import History
4+
from dspy.adapters.types.image import Image
55
from dspy.adapters.types.tool import Tool, ToolCalls
66

77
__all__ = ["History", "Image", "Audio", "BaseType", "Tool", "ToolCalls"]

dspy/adapters/types/audio.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def validate_input(cls, values: Any) -> Any:
4848
"""
4949
if isinstance(values, cls):
5050
return {"data": values.data, "format": values.format}
51-
return encode_audio(values)
51+
return encode_audio(values)
5252

5353
@classmethod
5454
def from_url(cls, url: str) -> "Audio":
@@ -142,4 +142,4 @@ def encode_audio(audio: Union[str, bytes, dict, "Audio", Any], sampling_rate: in
142142
encoded = base64.b64encode(audio).decode("utf-8")
143143
return {"data": encoded, "format": format}
144144
else:
145-
raise ValueError(f"Unsupported type for encode_audio: {type(audio)}")
145+
raise ValueError(f"Unsupported type for encode_audio: {type(audio)}")

dspy/dsp/utils/dpr.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def __init__(self, **kwargs):
158158
annotators: None or empty set (only tokenizes).
159159
"""
160160
self._regexp = regex.compile(
161-
"(%s)|(%s)" % (self.ALPHA_NUM, self.NON_WS), # noqa: UP031
161+
"(%s)|(%s)" % (self.ALPHA_NUM, self.NON_WS),
162162
flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE,
163163
)
164164
if len(kwargs.get("annotators", {})) > 0:

dspy/predict/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
from dspy.predict.best_of_n import BestOfN
33
from dspy.predict.chain_of_thought import ChainOfThought
44
from dspy.predict.chain_of_thought_with_hint import ChainOfThoughtWithHint
5+
from dspy.predict.code_act import CodeAct
56
from dspy.predict.knn import KNN
67
from dspy.predict.multi_chain_comparison import MultiChainComparison
78
from dspy.predict.parallel import Parallel
89
from dspy.predict.predict import Predict
910
from dspy.predict.program_of_thought import ProgramOfThought
1011
from dspy.predict.react import ReAct, Tool
11-
from dspy.predict.code_act import CodeAct
1212
from dspy.predict.refine import Refine
1313

1414
__all__ = [

dspy/predict/code_act.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def factorial(n):
6868
self.extractor = dspy.ChainOfThought(extract_signature)
6969
# It will raises exception when dspy cannot find available deno instance by now.
7070
self.interpreter = PythonInterpreter()
71-
71+
7272
def _build_instructions(self, signature, tools):
7373
instructions = [f"{signature.instructions}\n"] if signature.instructions else []
7474
inputs = ", ".join([f"`{k}`" for k in signature.input_fields.keys()])
@@ -85,14 +85,14 @@ def _build_instructions(self, signature, tools):
8585

8686
for idx, tool in enumerate(tools.values()):
8787
instructions.append(f"({idx + 1}) {tool}")
88-
88+
8989
return instructions
9090

9191
def forward(self, **kwargs):
9292
# Define the tool funcitons in the interpreter
9393
for tool in self.tools.values():
9494
self.interpreter(inspect.getsource(tool.func))
95-
95+
9696
trajectory = {}
9797
max_iters = kwargs.pop("max_iters", self.max_iters)
9898
for idx in range(max_iters):
@@ -111,7 +111,7 @@ def forward(self, **kwargs):
111111
trajectory[f"code_output_{idx}"] = output
112112
else:
113113
trajectory[f"observation_{idx}"] = f"Failed to execute the generated code: {error}"
114-
114+
115115
if code_data.finished:
116116
break
117117

dspy/signatures/signature.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ class MySignature(dspy.Signature):
1919
import importlib
2020
import inspect
2121
import re
22+
import sys
2223
import types
2324
import typing
24-
import sys
2525
from copy import deepcopy
2626
from typing import Any, Dict, Optional, Tuple, Type, Union
2727

@@ -71,48 +71,48 @@ def _detect_custom_types_from_caller(signature_str):
7171

7272
# Get type references from caller frames by walking the stack
7373
found_types = {}
74-
74+
7575
needed_types = set()
7676
dotted_types = {}
77-
77+
7878
for type_name in type_names:
7979
parts = type_name.split('.')
8080
base_name = parts[0]
81-
81+
8282
if base_name not in typing.__dict__ and base_name not in __builtins__:
8383
if len(parts) > 1:
8484
dotted_types[type_name] = base_name
8585
needed_types.add(base_name)
8686
else:
8787
needed_types.add(type_name)
88-
88+
8989
if not needed_types:
9090
return None
91-
91+
9292
frame = None
9393
try:
9494
frame = sys._getframe(1) # Start one level up (skip this function)
95-
95+
9696
max_frames = 100
9797
frame_count = 0
98-
98+
9999
while frame and needed_types and frame_count < max_frames:
100100
frame_count += 1
101-
101+
102102
for type_name in list(needed_types):
103103
if type_name in frame.f_locals:
104104
found_types[type_name] = frame.f_locals[type_name]
105105
needed_types.remove(type_name)
106106
elif frame.f_globals and type_name in frame.f_globals:
107107
found_types[type_name] = frame.f_globals[type_name]
108108
needed_types.remove(type_name)
109-
109+
110110
# If we found all needed types, stop looking
111111
if not needed_types:
112112
break
113-
113+
114114
frame = frame.f_back
115-
115+
116116
if needed_types and frame_count >= max_frames:
117117
import logging
118118
logging.getLogger("dspy").warning(
@@ -132,7 +132,7 @@ def _detect_custom_types_from_caller(signature_str):
132132

133133
return found_types or None
134134

135-
def __new__(mcs, signature_name, bases, namespace, **kwargs): # noqa: N804
135+
def __new__(mcs, signature_name, bases, namespace, **kwargs):
136136
# At this point, the orders have been swapped already.
137137
field_order = [name for name, value in namespace.items() if isinstance(value, FieldInfo)]
138138
# Set `str` as the default type for all fields
@@ -283,10 +283,7 @@ def append(cls, name, field, type_=None) -> Type["Signature"]:
283283
def delete(cls, name) -> Type["Signature"]:
284284
fields = dict(cls.fields)
285285

286-
if name in fields:
287-
del fields[name]
288-
else:
289-
raise ValueError(f"Field `{name}` not found in `{cls.__name__}`.")
286+
fields.pop(name, None)
290287

291288
return Signature(fields, cls.instructions)
292289

@@ -411,7 +408,7 @@ class MyType:
411408
if custom_types:
412409
names = dict(typing.__dict__)
413410
names.update(custom_types)
414-
411+
415412
fields = _parse_signature(signature, names) if isinstance(signature, str) else signature
416413

417414
# Validate the fields, this is important because we sometimes forget the
@@ -549,15 +546,15 @@ def resolve_name(type_name: str):
549546
if isinstance(node, ast.Attribute):
550547
base = _parse_type_node(node.value, names)
551548
attr_name = node.attr
552-
549+
553550
if hasattr(base, attr_name):
554551
return getattr(base, attr_name)
555-
552+
556553
if isinstance(node.value, ast.Name):
557554
full_name = f"{node.value.id}.{attr_name}"
558555
if full_name in names:
559556
return names[full_name]
560-
557+
561558
raise ValueError(f"Unknown attribute: {attr_name} on {base}")
562559

563560
if isinstance(node, ast.Subscript):

dspy/teleprompt/grpo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def compile(
298298
num_student_predictors = len(student.predictors())
299299

300300
logging.info("Preparing the teacher program(s)... We will ensure that the provided programs have the same program structure as the student program.")
301-
if isinstance(teacher, list) and len(teacher) == 0 or teacher is None:
301+
if (isinstance(teacher, list) and len(teacher) == 0) or teacher is None:
302302
teacher = student
303303
teachers = teacher if isinstance(teacher, list) else [teacher]
304304
for t in teachers:

dspy/teleprompt/mipro_optimizer_v2.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
import sys
55
import textwrap
66
import time
7-
from typing import TYPE_CHECKING
87
from collections import defaultdict
9-
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple
8+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Tuple
109

1110
import numpy as np
1211

dspy/utils/langchain_tool.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ async def func(**kwargs):
2424
result = await tool.ainvoke(kwargs)
2525
return result
2626
except Exception as e:
27-
raise RuntimeError(f"Failed to call LangChain tool {tool.name}: {str(e)}")
28-
27+
raise RuntimeError(f"Failed to call LangChain tool {tool.name}: {e!s}")
28+
2929
# Get args_schema from the tool
3030
# https://python.langchain.com/api_reference/core/tools/langchain_core.tools.base.BaseTool.html#langchain_core.tools.base.BaseTool.args_schema
3131
args_schema = tool.args_schema
3232
args, _, arg_desc = convert_input_schema_to_tool_args(args_schema.model_json_schema())
33-
33+
3434
# The args_schema of Langchain tool is a pydantic model, so we can get the type hints from the model fields
3535
arg_types = {
3636
key: field.annotation if field.annotation is not None else Any
@@ -44,4 +44,4 @@ async def func(**kwargs):
4444
args=args,
4545
arg_types=arg_types,
4646
arg_desc=arg_desc
47-
)
47+
)

0 commit comments

Comments
 (0)