repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
dspy
tests/predict/test_refine.py
.py
import pytest import dspy from dspy.predict.predict import Predict from dspy.predict.refine import Refine from dspy.primitives.prediction import Prediction from dspy.utils.dummies import DummyLM class DummyModule(dspy.Module): def __init__(self, signature, forward_fn): super().__init__() self.pre...
81
2,855
dspy
tests/predict/test_react_v2.py
.py
import dspy from dspy.dsp.utils.utils import dotdict class ReasoningDummyLM(dspy.utils.DummyLM): @property def supports_reasoning(self): return True def test_react_v2_submit_tool_returns_original_output_fields(): react = dspy.ReActV2("question -> answer", tools=[]) assert react.tools["submi...
327
11,374
dspy
tests/predict/test_knn.py
.py
import pytest import dspy from dspy.predict import KNN from dspy.utils import DummyVectorizer pytestmark = pytest.mark.extra def mock_example(question: str, answer: str) -> dspy.Example: """Creates a mock DSP example with specified question and answer.""" return dspy.Example(question=question, answer=answer...
52
2,051
dspy
tests/predict/test_best_of_n.py
.py
import pytest import dspy from dspy.predict.best_of_n import BestOfN from dspy.predict.predict import Predict from dspy.primitives.prediction import Prediction from dspy.utils.dummies import DummyLM class DummyModule(dspy.Module): def __init__(self, signature, forward_fn): super().__init__() self...
81
2,880
dspy
tests/predict/test_aggregation.py
.py
from dspy.evaluate import normalize_text from dspy.predict.aggregation import majority from dspy.primitives.prediction import Completions, Prediction def test_majority_with_prediction(): prediction = Prediction.from_completions([{"answer": "2"}, {"answer": "2"}, {"answer": "3"}]) result = majority(prediction)...
44
1,511
dspy
tests/predict/test_predict.py
.py
import asyncio import copy import enum import logging import time import types from datetime import datetime from unittest.mock import patch import orjson import pydantic import pytest from litellm import ModelResponse from pydantic import BaseModel, HttpUrl import dspy from dspy import Predict, Signature from dspy.c...
1,783
64,509
dspy
tests/predict/test_multi_chain_comparison.py
.py
import dspy from dspy.utils.dummies import DummyLM class BasicQA(dspy.Signature): """Answer questions with short factoid answers.""" question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words") # Example completions generated by a model for reference completions = [ ds...
41
1,253
dspy
tests/predict/test_rlm.py
.py
""" Tests for the RLM (Recursive Language Model) module. Test organization: - Unit tests (no Deno required): MockInterpreter, RLM formatting, signatures - Integration tests (@pytest.mark.deno): PythonInterpreter with Deno """ import base64 from contextlib import contextmanager import pytest from dspy.adapters.types...
1,724
69,303
dspy
tests/predict/test_code_act.py
.py
import threading from unittest.mock import Mock import pytest import dspy from dspy import Signature from dspy.evaluate.metrics import answer_exact_match from dspy.predict import CodeAct from dspy.primitives.code_interpreter import CodeInterpreterError from dspy.utils import DummyLM from tests.mock_interpreter import...
288
10,175
dspy
tests/utils/test_settings.py
.py
import asyncio import sys import time from concurrent.futures import ThreadPoolExecutor from unittest import mock import pytest from litellm import Choices, Message, ModelResponse import dspy def test_basic_dspy_settings(): dspy.configure(lm=dspy.LM("openai/gpt-4o"), adapter=dspy.JSONAdapter(), callbacks=[lambd...
265
10,211
dspy
tests/utils/test_exceptions.py
.py
import dspy from dspy.utils.exceptions import ( AdapterParseError, ContextWindowExceededError, DSPyError, LMError, LMInvalidRequestError, format_error_for_lm, ) def test_lm_errors_are_exported_from_dspy(): assert dspy.DSPyError is not None assert dspy.LMError is LMError assert dspy...
175
6,081
dspy
tests/utils/test_lazy_import.py
.py
import sys import threading from concurrent.futures import ThreadPoolExecutor import pytest from dspy.utils.lazy_import import _INSTALL_HINTS, _detect_dspy_dist, _MissingModule, is_available, require def test_is_available_true_for_stdlib(): assert is_available("json") is True def test_is_available_false_for_m...
142
4,609
dspy
tests/utils/test_asyncify.py
.py
import asyncio import math from time import sleep, time import pytest import dspy from dspy.utils.asyncify import get_limiter @pytest.mark.anyio async def test_async_limiter(): limiter = get_limiter() assert limiter.total_tokens == 8, "Default async capacity should be 8" assert get_limiter() == limiter,...
53
2,007
dspy
tests/utils/test_saving.py
.py
import logging from unittest.mock import patch import pytest import dspy from dspy.utils import DummyLM def test_save_predict(tmp_path): predict = dspy.Predict("question->answer") predict.save(tmp_path, save_program=True) assert (tmp_path / "metadata.json").exists() assert (tmp_path / "program.pkl"...
176
6,372
dspy
tests/utils/test_unbatchify.py
.py
import time from concurrent.futures import Future from unittest.mock import MagicMock from dspy.utils.unbatchify import Unbatchify def simple_batch_processor(batch): """A simple batch function that adds 1 to each item.""" return [item + 1 for item in batch] def submit(self, input_item: any) -> Future: ...
73
2,103
dspy
tests/utils/test_annotation.py
.py
from dspy.utils.annotation import experimental def test_experimental_decorator_on_function(): @experimental def test_function(): """A test function.""" return "test" assert "Experimental: This function may change or be removed in a future release without warning." in test_function.__doc__...
93
3,102
dspy
tests/utils/test_magicattr.py
.py
import pytest from dspy.utils import magicattr class Test: l = [1, 2] a = [0, [1, 2, [3, 4]]] b = {"x": {"y": "y"}, "z": [1, 2]} z = "z" class Person: settings = { "autosave": True, "style": {"height": 30, "width": 200}, "themes": ["light", "dark"], } def __init...
128
3,209
dspy
tests/utils/test_parallelizer.py
.py
import threading import time from unittest import mock import pytest from dspy.utils.callback import ACTIVE_CALL_ID from dspy.utils.parallelizer import ParallelExecutor def test_worker_threads_independence(): def task(item): # Each thread maintains its own state by appending to a thread-local list ...
198
6,220
dspy
tests/utils/test_syncify.py
.py
import asyncio import dspy def test_syncify_in_place(): class MyProgram(dspy.Module): async def aforward(self, x: int) -> int: await asyncio.sleep(0.01) return x + 1 sync_program = dspy.syncify(MyProgram()) assert sync_program(1) == 2 assert sync_program(2) == 3 def...
58
1,869
dspy
tests/utils/test_mcp.py
.py
import asyncio import importlib import pytest from dspy.utils.mcp import convert_mcp_tool if importlib.util.find_spec("mcp") is None: pytest.skip(reason="mcp is not installed", allow_module_level=True) @pytest.mark.asyncio @pytest.mark.extra async def test_convert_mcp_tool(): from mcp import ClientSession,...
99
4,305
dspy
tests/utils/test_usage_tracker.py
.py
from unittest import mock from pydantic import BaseModel import dspy from dspy.utils.usage_tracker import UsageTracker, track_usage def test_add_usage_entry(): """Test adding usage entries to the tracker.""" tracker = UsageTracker() # Test with a single usage entry usage_entry = { "prompt_t...
395
14,778
dspy
tests/utils/test_langchain_tool.py
.py
import importlib import pytest if importlib.util.find_spec("langchain_core") is None: pytest.skip(reason="langchain_core is not installed", allow_module_level=True) from pydantic import BaseModel from dspy.utils.langchain_tool import convert_langchain_tool @pytest.mark.asyncio @pytest.mark.extra async def tes...
53
1,792
dspy
tests/utils/resources/mcp_server.py
.py
from mcp.server.fastmcp import FastMCP from pydantic import BaseModel mcp = FastMCP("test") class Profile(BaseModel): name: str age: int class Account(BaseModel): profile: Profile account_id: str @mcp.tool() def add(a: int, b: int) -> int: """Add two numbers""" return a + b @mcp.tool() ...
49
829
dspy
tests/propose/test_grounded_proposer.py
.py
import pytest import dspy from dspy.predict import Predict from dspy.propose.grounded_proposer import GroundedProposer from dspy.utils.dummies import DummyLM @pytest.mark.parametrize( "demo_candidates", [ None, [[[dspy.Example(question="What is the capital of France?", answer="Paris")]]], ...
66
2,067
dspy
tests/examples/test_baleen.py
.py
import dspy import dspy.evaluate from dspy.datasets import HotPotQA from dspy.dsp.utils import deduplicate from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt.bootstrap import BootstrapFewShot class GenerateAnswer(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy...
121
4,604
dspy
tests/reliability/utils.py
.py
import os from contextlib import contextmanager from functools import lru_cache, wraps from typing import Any, Dict, List, Union import pydantic import pytest import yaml import dspy JUDGE_MODEL_NAME = "judge" def assert_program_output_correct( program_input: Any, program_output: Any, grading_guideline...
153
5,549
dspy
tests/reliability/test_generated.py
.py
import os import pytest from tests.reliability.generate.utils import load_generated_cases, run_generated_case _DIR_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__))) @pytest.mark.reliability @pytest.mark.parametrize( "generated_case", load_generated_cases(_DIR_PATH), ids=lambda case: case....
18
409
dspy
tests/reliability/test_pydantic_models.py
.py
from enum import Enum from typing import Any, List, Literal import pydantic import pytest import dspy from tests.reliability.utils import assert_program_output_correct, known_failing_models @pytest.mark.reliability def test_qa_with_pydantic_answer_model(): class Answer(pydantic.BaseModel): value: str ...
191
10,011
dspy
tests/reliability/conftest.py
.py
import os import pytest import dspy from ..conftest import clear_settings from ..reliability.utils import get_adapter, parse_reliability_conf_yaml # Standard list of models that should be used for periodic DSPy reliability testing MODEL_LIST = [ "gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-o1-preview...
82
2,751
dspy
tests/reliability/complex_types/generated/test_many_types_1/program.py
.py
### Input models ### from datetime import datetime from enum import Enum from typing import List, Tuple from pydantic import BaseModel, Field class EnumField(Enum): option1 = "option1" option2 = "option2" option3 = "option3" class LiteralField(Enum): literalValue = "literalValue" class ObjectFi...
121
2,947
dspy
tests/reliability/complex_types/generated/test_nesting_2/program.py
.py
### Input models ### from datetime import datetime from pydantic import BaseModel, Field class Details(BaseModel): value: str = Field(..., description="Customer's value category") age: int = Field(..., description="Customer's age") class Customer(BaseModel): customer_id: str = Field(..., description=...
97
3,180
dspy
tests/reliability/complex_types/generated/test_nesting_1/program.py
.py
### Input models ### from pydantic import BaseModel, Field class Level5(BaseModel): field1: str = Field(..., description="A string field at the deepest level") field2: float = Field(..., description="A numerical field at the deepest level") class Level4(BaseModel): level5: Level5 class Level3(BaseMo...
91
2,339
dspy
tests/reliability/generate/utils.py
.py
import importlib.util import json import os import pathlib import random import re import shutil import sys import tempfile from contextlib import contextmanager from dataclasses import dataclass from functools import wraps from typing import Any, Dict, List, Optional, Tuple import pydantic from datamodel_code_generat...
713
29,350
dspy
tests/reliability/generate/__main__.py
.py
import argparse from tests.reliability.generate import generate_test_cases if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate test cases by specifying configuration and input instructions." ) parser.add_argument( "-d", "--dst_path", type=str, required=True, ...
30
1,051
dspy
tests/reliability/generate/__init__.py
.py
import os from typing import List, Optional from tests.reliability.generate.utils import ( GeneratedTestCase, generate_test_inputs, generate_test_program, load_generated_cases, load_generated_program, ) def generate_test_cases( dst_path: str, num_inputs: int = 1, program_instructions:...
39
1,231
dspy
tests/reliability/input_formats/generated/test_markdown_1/program.py
.py
### Input models ### from pydantic import BaseModel, Field class ProgramInputs(BaseModel): markdown_content: str = Field( ..., description="The content of the markdown document from which the table of contents will be generated.", ) ### Output models ### from pydantic import BaseModel, F...
50
1,515
dspy
tests/primitives/test_example.py
.py
import pytest import dspy from dspy import Example def test_example_initialization(): example = Example(a=1, b=2) assert example.a == 1 assert example.b == 2 def test_example_initialization_from_base(): base = Example(a=1, b=2) example = Example(base=base, c=3) assert example.a == 1 ass...
157
4,194
dspy
tests/primitives/test_python_interpreter.py
.py
import asyncio import dataclasses import io import json import os import random import shutil import subprocess import sys import threading import types from collections import namedtuple from datetime import datetime from enum import Enum from pathlib import Path from typing import NamedTuple import pytest from pydan...
1,626
60,535
dspy
tests/primitives/test_module.py
.py
import json import tempfile from pathlib import Path import pytest import dspy from dspy.primitives.example import Example from dspy.primitives.module import Module, set_attribute_by_name from dspy.utils import DummyLM class HopModule(dspy.Module): def __init__(self): super().__init__() self.pre...
246
8,563
dspy
tests/primitives/test_sandbox_serializable.py
.py
"""Tests for the SandboxSerializable ABC and build_repl_variable helper.""" import pytest import dspy from dspy.primitives.repl_types import REPLVariable from dspy.primitives.sandbox_serializable import SandboxSerializable, build_repl_variable # -- Stub implementations -- class ExampleSerializable(SandboxSerializa...
150
5,079
dspy
tests/primitives/test_base_module.py
.py
import asyncio import logging import os import threading from unittest.mock import patch import pytest from litellm import Choices, Message, ModelResponse from litellm.types.utils import Usage import dspy from dspy.primitives.prediction import Prediction from dspy.utils.dummies import DummyLM def test_deepcopy_basi...
545
20,910
dspy
tests/primitives/test_code_interpreter.py
.py
import dspy from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreterError def test_code_interpreter_error_is_dspy_error(): error = CodeInterpreterError("boom") assert isinstance(error, dspy.DSPyError) assert isinstance(error, RuntimeError) assert str(error) == "boom" assert...
22
625
dspy
tests/adapters/test_chat_adapter.py
.py
import json import re from typing import Literal from unittest import mock import pydantic import pytest from litellm.utils import ChatCompletionMessageToolCall, Choices, Function, Message, ModelResponse import dspy from dspy.experimental import Citations, Document from tests.adapters.conftest import format_messages_...
2,949
120,075
dspy
tests/adapters/test_resource_loading.py
.py
import base64 import pytest from pydantic import TypeAdapter, ValidationError import dspy def _forbid_host_io(monkeypatch): """Make any filesystem read or outbound request fail the test.""" def fail_open(*args, **kwargs): pytest.fail("resource handling attempted a filesystem read") def fail_re...
234
8,431
dspy
tests/adapters/test_document.py
.py
import pydantic import pytest from dspy.experimental import Document def test_document_validate_input(): # Create a `Document` instance with valid data. doc = Document(data="The Earth orbits the Sun.") assert doc.data == "The Earth orbits the Sun." with pytest.raises(pydantic.ValidationError): ...
58
1,676
dspy
tests/adapters/test_baml_adapter.py
.py
from typing import Literal from unittest import mock import pydantic import pytest from litellm import Choices, Message from litellm.files.main import ModelResponse import dspy from dspy.adapters.baml_adapter import COMMENT_SYMBOL, INDENTATION, BAMLAdapter from tests.adapters.conftest import format_messages_and_lm_kw...
644
23,973
dspy
tests/adapters/test_base_type.py
.py
import pydantic import dspy def test_basic_extract_custom_type_from_annotation(): class Event(dspy.Type): event_name: str start_date_time: str end_date_time: str | None location: str | None class ExtractEvent(dspy.Signature): """Extract all events from the email conte...
52
1,575
dspy
tests/adapters/test_code.py
.py
import inspect import pydantic import pytest import dspy def test_code_validate_input(): # Create a `dspy.Code` instance with valid code. code = dspy.Code["python"](code="print('Hello, world!')") assert code.code == "print('Hello, world!')" with pytest.raises(ValueError): # Try to create a ...
64
1,796
dspy
tests/adapters/test_audio.py
.py
import pytest from dspy.adapters.types.audio import _normalize_audio_format @pytest.mark.parametrize( "input_format, expected_format", [ # Case 1: Standard format (no change) ("wav", "wav"), ("mp3", "mp3"), # Case 2: The 'x-' prefix ("x-wav", "wav"), ("x-mp3",...
33
874
dspy
tests/adapters/test_two_step_adapter.py
.py
from unittest import mock import pytest import dspy from tests.adapters.conftest import format_messages_and_lm_kwargs def test_two_step_adapter_format_exact_messages_for_simple_signature_with_demo(): class QA(dspy.Signature): question: str = dspy.InputField() answer: str = dspy.OutputField() ...
236
8,697
dspy
tests/adapters/test_reasoning.py
.py
import pytest import dspy def test_reasoning_basic_operations(): reasoning = dspy.Reasoning(content="Hello World") # Test str conversion assert str(reasoning) == "Hello World" assert repr(reasoning) == "'Hello World'" # Test equality assert reasoning == "Hello World" assert reasoning ==...
130
3,957
dspy
tests/adapters/test_tool.py
.py
import asyncio from typing import Any import pytest from pydantic import BaseModel, TypeAdapter import dspy from dspy.adapters.types.tool import Tool, ToolCallResults, ToolCalls, convert_input_schema_to_tool_args from dspy.clients.openai_format import to_openai_chat_request from dspy.core.types import LMMessage, LMRe...
769
25,231
dspy
tests/adapters/test_xml_adapter.py
.py
import sys from unittest import mock import pydantic import pytest from litellm import Choices, Message, ModelResponse import dspy from dspy.adapters.chat_adapter import FieldInfoWithName from dspy.adapters.xml_adapter import XMLAdapter from tests.adapters.conftest import format_messages_and_lm_kwargs def test_xml_...
856
30,722
dspy
tests/adapters/test_json_adapter.py
.py
import enum from typing import Literal from unittest import mock import pydantic import pytest from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse from litellm.utils import ChatCompletionMessageToolCall, Choices, Function, Message, ModelResponse from openai.types.responses import ResponseOutpu...
1,719
70,130
dspy
tests/adapters/test_adapter_utils.py
.py
# ruff: noqa: UP007 from typing import Literal, Optional, Union import pytest from pydantic import BaseModel from dspy.adapters.utils import parse_value class Profile(BaseModel): name: str age: int def test_parse_value_str_annotation(): # Test basic string conversion assert parse_value(123, str) ...
108
3,704
dspy
tests/adapters/test_citation.py
.py
import pydantic import pytest import dspy from dspy.experimental import Citations def test_citation_validate_input(): citation = Citations.Citation( cited_text="The Earth orbits the Sun.", document_index=0, start_char_index=0, end_char_index=23, supported_text="The Earth o...
195
6,174
dspy
tests/adapters/conftest.py
.py
import dspy class StopAdapterCallCapture(BaseException): """Stop adapter execution after capturing the LM call. The exact-format tests assert the adapter-to-LM boundary: the messages and keyword arguments passed to the LM. Raising here avoids needing to craft a parseable LM response for every signatu...
56
1,672
dspy
dspy/__init__.py
.py
from dspy.predict import * from dspy.primitives import * from dspy.retrievers import * from dspy.signatures import * from dspy.teleprompt import * from dspy.predict.flex import Flex from dspy.evaluate import Evaluate # isort: skip from dspy.clients import * # isort: skip from dspy.adapters import Adapter, ChatAdapte...
66
1,945
dspy
dspy/__metadata__.py
.py
#replace_package_name_marker __name__="dspy" #replace_package_version_marker __version__="3.3.0" __description__="DSPy" __url__="https://github.com/stanfordnlp/dspy" __author__="Omar Khattab" __author_email__="okhattab@stanford.edu"
8
232
dspy
dspy/evaluate/__init__.py
.py
from dspy.evaluate.auto_evaluation import CompleteAndGrounded, SemanticF1 from dspy.evaluate.evaluate import Evaluate, EvaluationResult from dspy.evaluate.metrics import EM, answer_exact_match, answer_passage_match, normalize_text __all__ = [ "EM", "normalize_text", "answer_exact_match", "answer_passag...
15
417
dspy
dspy/evaluate/auto_evaluation.py
.py
from dspy.predict.chain_of_thought import ChainOfThought from dspy.primitives import Module from dspy.primitives.prediction import Prediction from dspy.signatures import InputField, OutputField, Signature class SemanticRecallPrecision(Signature): """ Compare a system's response to the ground truth to compute ...
124
5,620
dspy
dspy/evaluate/evaluate.py
.py
import csv import importlib import json import logging import types from typing import TYPE_CHECKING, Any, Callable if TYPE_CHECKING: import pandas as pd import tqdm import dspy from dspy.primitives.prediction import Prediction from dspy.utils.callback import with_callbacks from dspy.utils.parallelizer import Pa...
400
15,607
dspy
dspy/evaluate/metrics.py
.py
# TODO: This should move internally. Same for passage_match. dspy.metrics.answer_exact_match, dspy.metrics.answer_passage_match import re import string import unicodedata from collections import Counter from dspy.dsp.utils.utils import print_message def EM(prediction, answers_list): # noqa: N802 """Compute the...
349
11,629
dspy
dspy/dsp/colbertv2.py
.py
from typing import Any import requests from dspy.clients.cache import request_cache from dspy.dsp.utils import dotdict # TODO: Ideally, this takes the name of the index and looks up its port. class ColBERTv2: """Wrapper for the ColBERTv2 Retrieval.""" def __init__( self, url: str = "http:/...
233
8,934
dspy
dspy/dsp/utils/utils.py
.py
import copy import datetime import itertools import os from collections import defaultdict import tqdm def print_message(*s, condition=True, pad=False, sep=None): """Print a timestamped message to stdout. Args: *s: Values to print. condition: If False, don't print (default: True). ...
263
6,689
dspy
dspy/dsp/utils/dpr.py
.py
""" Source: DPR Implementation from Facebook Research https://github.com/facebookresearch/DPR/tree/master/dpr Original license: https://github.com/facebookresearch/DPR/blob/main/LICENSE """ import copy import logging import unicodedata import regex logger = logging.getLogger(__name__) class Tokens: """A class ...
250
7,282
dspy
dspy/dsp/utils/settings.py
.py
import asyncio import contextvars import copy import logging import threading from contextlib import contextmanager from typing import Any import cloudpickle from dspy.dsp.utils.utils import dotdict logger = logging.getLogger(__name__) DEFAULT_CONFIG = dotdict( lm=None, adapter=None, rm=None, branch...
324
11,988
dspy
dspy/streaming/streaming_listener.py
.py
from __future__ import annotations import inspect import re from collections import defaultdict from queue import Queue from typing import TYPE_CHECKING, Any import jiter from dspy.adapters.chat_adapter import ChatAdapter from dspy.adapters.json_adapter import JSONAdapter from dspy.adapters.types import Type from ds...
416
19,828
dspy
dspy/streaming/__init__.py
.py
from dspy.streaming.messages import StatusMessage, StatusMessageProvider, StreamResponse from dspy.streaming.streamify import apply_sync_streaming, streamify, streaming_response from dspy.streaming.streaming_listener import StreamListener __all__ = [ "StatusMessage", "StatusMessageProvider", "streamify", ...
14
419
dspy
dspy/streaming/messages.py
.py
import asyncio import concurrent.futures from dataclasses import dataclass from typing import Any import anyio.from_thread from dspy.dsp.utils.settings import settings from dspy.utils.callback import BaseCallback @dataclass class StreamResponse: predict_name: str signature_field_name: str chunk: str ...
185
5,887
dspy
dspy/streaming/streamify.py
.py
import asyncio import contextvars import logging import threading from asyncio import iscoroutinefunction from queue import Queue from typing import TYPE_CHECKING, Any, AsyncGenerator, Awaitable, Callable, Generator import orjson from anyio import create_memory_object_stream, create_task_group from anyio.streams.memor...
289
11,843
dspy
dspy/signatures/field.py
.py
import warnings import pydantic from dspy.utils.constants import IS_TYPE_UNDEFINED # The following arguments can be used in DSPy InputField and OutputField in addition # to the standard pydantic.Field arguments. We just hope pydanitc doesn't add these, # as it would give a name clash. DSPY_FIELD_ARG_NAMES = ["desc",...
128
4,548
dspy
dspy/signatures/utils.py
.py
from typing import Literal from pydantic.fields import FieldInfo def get_dspy_field_type(field: FieldInfo) -> Literal["input", "output"]: field_type = field.json_schema_extra.get("__dspy_field_type") if field_type is None: raise ValueError(f"Field {field} does not have a __dspy_field_type") retur...
11
333
dspy
dspy/signatures/__init__.py
.py
from dspy.signatures.field import InputField, OldField, OldInputField, OldOutputField, OutputField from dspy.signatures.signature import ( Signature, SignatureMeta, ensure_signature, infer_prefix, make_signature, ) __all__ = [ "InputField", "OutputField", "OldField", "OldInputField"...
22
450
dspy
dspy/signatures/signature.py
.py
"""Signature class for DSPy. You typically subclass the Signature class, like this: class MySignature(dspy.Signature): input: str = InputField(desc="...") output: int = OutputField(desc="...") You can call Signature("input1, input2 -> output1, output2") to create a new signature type. You can also...
866
34,839
dspy
dspy/teleprompt/grpo.py
.py
import logging import random import time from collections import Counter, deque from typing import Any, Callable, Literal from dspy.adapters.base import Adapter from dspy.adapters.chat_adapter import ChatAdapter from dspy.adapters.xml_adapter import XMLAdapter from dspy.clients.lm import LM from dspy.clients.utils_fin...
636
38,879
dspy
dspy/teleprompt/avatar_optimizer.py
.py
from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from random import sample from typing import Callable from pydantic import BaseModel from tqdm import tqdm import dspy from dspy.predict.avatar import ActionOutput from dspy.teleprompt.teleprompt import Teleprompter DEFAULT_MAX_EXAMPLES = 10...
218
8,767
dspy
dspy/teleprompt/signature_opt.py
.py
from .copro_optimizer import COPRO """ =============================================================== DEPRECATED!!! PLEASE USE COPRO INSTEAD. =============================================================== USAGE SUGGESTIONS: The following code can be used to compile a optimized signature teleprompter, and evaluate ...
53
2,664
dspy
dspy/teleprompt/random_search.py
.py
import random import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt.teleprompt import Teleprompter from .bootstrap import BootstrapFewShot from .vanilla import LabeledFewShot # TODO: Don't forget dealing with the raw demos. # TODO: Deal with the (pretty common) case of having a metric for filt...
169
7,372
dspy
dspy/teleprompt/utils.py
.py
import inspect import logging import math import os import random import shutil import sys try: from IPython.core.magics.code import extract_symbols except ImportError: # Won't be able to read code from jupyter notebooks extract_symbols = None import dspy from dspy.teleprompt.bootstrap import BootstrapFew...
464
15,427
dspy
dspy/teleprompt/mipro_optimizer_v2.py
.py
import logging import math import random from collections import defaultdict from typing import TYPE_CHECKING, Any, Callable, Literal import dspy from dspy.evaluate.evaluate import Evaluate from dspy.propose import GroundedProposer from dspy.teleprompt.teleprompt import Teleprompter from dspy.teleprompt.utils import (...
867
34,889
dspy
dspy/teleprompt/bootstrap.py
.py
import logging import random import threading import tqdm import dspy from dspy.teleprompt.teleprompt import Teleprompter from .vanilla import LabeledFewShot # TODO: metrics should return an object with __bool__ basically, but fine if they're more complex. # They can also be sortable. # TODO: Switch here from dspy...
273
12,139
dspy
dspy/teleprompt/teleprompt.py
.py
import asyncio import functools import inspect import threading from typing import Any import dspy.utils.callback_context as callback_context from dspy.primitives import Example, Module from dspy.utils.callback import with_callbacks def _compile_invocation_key(instance): try: task = asyncio.current_task(...
87
2,958
dspy
dspy/teleprompt/__init__.py
.py
from dspy.teleprompt.avatar_optimizer import AvatarOptimizer from dspy.teleprompt.bettertogether import BetterTogether from dspy.teleprompt.bootstrap import BootstrapFewShot from dspy.teleprompt.bootstrap_finetune import BootstrapFinetune from dspy.teleprompt.bootstrap_trace import bootstrap_trace_data from dspy.telepr...
36
1,215
dspy
dspy/teleprompt/bootstrap_finetune.py
.py
import logging from collections import defaultdict from typing import Any, Callable import dspy from dspy.adapters.base import Adapter from dspy.adapters.chat_adapter import ChatAdapter from dspy.clients.lm import LM from dspy.clients.utils_finetune import infer_data_format from dspy.dsp.utils.settings import settings...
325
13,429
dspy
dspy/teleprompt/bootstrap_trace.py
.py
import logging from dataclasses import dataclass from types import MethodType from typing import Any, Callable, TypedDict import dspy from dspy.evaluate.evaluate import Evaluate from dspy.primitives.example import Example from dspy.primitives.module import Module from dspy.primitives.prediction import Prediction from ...
154
5,916
dspy
dspy/teleprompt/ensemble.py
.py
import random from dspy.teleprompt.teleprompt import Teleprompter """ TODO: The EnsembledProgram should actually imitate the structure of the individual programs (IF they are all compatible). This allows compiling with an ensemble program as a (singular) teacher. Basically the top majority-compatible trace will end u...
41
1,359
dspy
dspy/teleprompt/bettertogether.py
.py
import inspect import logging import random from typing import Any, Callable import dspy from dspy.evaluate import Evaluate from dspy.primitives.example import Example from dspy.primitives.module import Module from dspy.teleprompt.bootstrap_finetune import ( BootstrapFinetune, all_predictors_have_lms, kill...
632
29,662
dspy
dspy/teleprompt/infer_rules.py
.py
import logging import math import random import dspy from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt import BootstrapFewShot logger = logging.getLogger(__name__) class InferRules(BootstrapFewShot): def __init__(self, num_candidates=10, num_rules=10, num_threads=None, teacher_settings=None, **kw...
153
6,398
dspy
dspy/teleprompt/simba.py
.py
from __future__ import annotations import logging import random from typing import Any, Callable import dspy from dspy.teleprompt.simba_utils import append_a_demo, append_a_rule, prepare_models_for_resampling, wrap_program from dspy.teleprompt.teleprompt import Teleprompter from dspy.utils.lazy_import import require ...
378
16,690
dspy
dspy/teleprompt/teleprompt_optuna.py
.py
from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt.teleprompt import Teleprompter from .bootstrap import BootstrapFewShot def _import_optuna(): try: import optuna except ModuleNotFoundError as exc: if exc.name == "optuna": raise ImportError( "Bootstra...
90
3,591
dspy
dspy/teleprompt/simba_utils.py
.py
import inspect import logging import textwrap from typing import Callable import orjson import dspy from dspy.adapters.utils import get_field_description_string from dspy.signatures import InputField, OutputField logger = logging.getLogger(__name__) def prepare_models_for_resampling(program: dspy.Module, n: int, te...
254
11,007
dspy
dspy/teleprompt/copro_optimizer.py
.py
import logging import statistics from collections import defaultdict import dspy from dspy.evaluate.evaluate import Evaluate from dspy.signatures import Signature from dspy.teleprompt.teleprompt import Teleprompter logger = logging.getLogger(__name__) """ USAGE SUGGESTIONS: The following code can be used to compile...
357
17,453
dspy
dspy/teleprompt/vanilla.py
.py
import random from dspy.teleprompt.teleprompt import Teleprompter class LabeledFewShot(Teleprompter): def __init__(self, k=16): self.k = k def compile(self, student, *, trainset, sample=True): self.student = student.reset_copy() self.trainset = trainset if len(self.trainset)...
31
963
dspy
dspy/teleprompt/knn_fewshot.py
.py
import types from typing import Any from dspy.clients import Embedder from dspy.predict.knn import KNN from dspy.primitives import Example from dspy.teleprompt import BootstrapFewShot from dspy.teleprompt.teleprompt import Teleprompter class KNNFewShot(Teleprompter): def __init__(self, k: int, trainset: list[Exa...
70
2,753
dspy
dspy/teleprompt/gepa/instruction_proposal.py
.py
import logging from typing import Any from gepa.core.adapter import ProposalFn import dspy from dspy.adapters.types.base_type import Type from dspy.teleprompt.gepa.gepa_utils import ReflectiveExample logger = logging.getLogger(__name__) class GenerateEnhancedMultimodalInstructionFromFeedback(dspy.Signature): "...
316
14,236
dspy
dspy/teleprompt/gepa/gepa_utils.py
.py
import logging import random from typing import Any, Callable, Protocol, TypedDict from gepa import EvaluationBatch, GEPAAdapter from gepa.core.adapter import ProposalFn from gepa.strategies.instruction_proposal import InstructionProposalSignature import dspy from dspy.adapters.chat_adapter import ChatAdapter from ds...
419
18,074
dspy
dspy/teleprompt/gepa/__init__.py
.py
from dspy.teleprompt.gepa.gepa import GEPA __all__ = ["GEPA"]
4
63
dspy
dspy/teleprompt/gepa/gepa.py
.py
import inspect import logging import math import random from dataclasses import dataclass from typing import Any, Literal, Optional, Protocol, Union from gepa import GEPAResult from gepa.core.adapter import ProposalFn from gepa.proposer.reflective_mutation.base import ReflectionComponentSelector from dspy.clients.lm ...
642
34,712
dspy
dspy/teleprompt/gepa/gepa_flex_utils.py
.py
from __future__ import annotations import inspect import logging from typing import Any from gepa import EvaluationBatch import dspy from dspy.predict.flex import Flex from dspy.predict.flex.ctx import _strip_code_fences from dspy.predict.flex.primitives_doc import PRIMITIVES_CATALOG from dspy.primitives import Pred...
256
11,754