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 | dspy/experimental/__init__.py | .py | from dspy.adapters.types.citation import Citations
from dspy.adapters.types.document import Document
__all__ = [
"Citations",
"Document",
]
| 8 | 149 |
dspy | dspy/clients/provider.py | .py | from abc import abstractmethod
from concurrent.futures import Future
from threading import Thread
from typing import TYPE_CHECKING, Any
from dspy.clients.utils_finetune import TrainDataFormat
if TYPE_CHECKING:
from dspy.clients.lm import LM
class TrainingJob(Future):
"""A future representing an asynchronous... | 293 | 10,569 |
dspy | dspy/clients/openai.py | .py | import time
from datetime import datetime
from typing import Any
import openai
from dspy.clients.provider import Provider, TrainingJob
from dspy.clients.utils_finetune import TrainDataFormat, TrainingStatus, save_data
class TrainingJobOpenAI(TrainingJob):
def __init__(self, *args, **kwargs):
super().__i... | 228 | 8,518 |
dspy | dspy/clients/lm.py | .py | import functools
import logging
import os
import re
import threading
import warnings
from typing import Any, Literal, cast
import anyio.from_thread
from anyio.streams.memory import MemoryObjectSendStream
import dspy
from dspy.clients._litellm import get_litellm, is_litellm_context_window_error
from dspy.clients.cache... | 843 | 33,781 |
dspy | dspy/clients/databricks.py | .py | import logging
import os
import re
import time
from typing import TYPE_CHECKING, Any
import orjson
import requests
from dspy.clients.provider import Provider, TrainingJob
from dspy.clients.utils_finetune import TrainDataFormat, get_finetune_directory
if TYPE_CHECKING:
from databricks.sdk import WorkspaceClient
... | 357 | 14,546 |
dspy | dspy/clients/__init__.py | .py | import logging
import os
from pathlib import Path
from typing import Any
from dspy.clients._litellm import get_litellm
from dspy.clients.base_lm import BaseLM, inspect_history
from dspy.clients.cache import Cache
from dspy.clients.embedding import Embedder
from dspy.clients.lm import LM
from dspy.clients.provider impo... | 124 | 4,064 |
dspy | dspy/clients/_litellm.py | .py | from __future__ import annotations
import functools
import sys
import types
from typing import Any
from dspy.utils.lazy_import import require
@functools.cache
def _configure_litellm_defaults(litellm: types.ModuleType) -> None:
"""Apply DSPy's global LiteLLM defaults once when LiteLLM is first imported."""
l... | 43 | 1,730 |
dspy | dspy/clients/lm_local.py | .py | import datetime
import logging
import random
import socket
import string
import subprocess
import threading
import time
from typing import TYPE_CHECKING, Any
import requests
from dspy.clients.provider import Provider, TrainingJob
from dspy.clients.utils_finetune import TrainDataFormat, save_data
if TYPE_CHECKING:
... | 437 | 15,752 |
dspy | dspy/clients/embedding.py | .py | from __future__ import annotations
from typing import Any, Callable
from dspy.clients._litellm import get_litellm
from dspy.clients.cache import request_cache
from dspy.utils.lazy_import import require
np = require("numpy")
def _get_litellm():
return get_litellm(feature="dspy.Embedder")
class Embedder:
"... | 187 | 7,809 |
dspy | dspy/clients/openai_format.py | .py | """Translate between DSPy's LM types and OpenAI-shaped JSON.
This module does not call any provider. It only maps data shapes:
```text
LMRequest -> OpenAI Chat / Responses / text-completion kwargs
provider response -> LMResponse
```
The concrete OpenAI backends import these functions, then add transport,
streaming, ... | 1,033 | 42,222 |
dspy | dspy/clients/disk_serialization.py | .py | """Restricted pickle deserialization for disk cache.
Provides a RestrictedDisk subclass that overrides diskcache's fetch to use
a restricted unpickler.
Trust model:
- litellm.types.* and openai.types.* are trusted by module prefix (pydantic
data models only, forward-compatible with library upgrades)
- numpy reconst... | 89 | 2,964 |
dspy | dspy/clients/cache.py | .py | import copy
import inspect
import logging
import os
import threading
from functools import wraps
from hashlib import sha256
from typing import Any
import cloudpickle
import orjson
import pydantic
from cachetools import LRUCache
from diskcache import FanoutCache
from dspy.clients.disk_serialization import (
Deseri... | 314 | 12,293 |
dspy | dspy/clients/base_lm.py | .py | import copy as copy_module
import datetime
import importlib
import inspect
import uuid
import warnings
from typing import Any, Literal, TextIO
from dspy.clients.openai_format import (
completion_to_lm_response,
cost_from_response,
lm_response_from_legacy_outputs,
responses_to_lm_response,
to_openai... | 883 | 37,329 |
dspy | dspy/clients/utils_finetune.py | .py | import os
from enum import Enum
from typing import TYPE_CHECKING, Any, Literal, TypedDict
import orjson
import dspy
from dspy.utils.caching import DSPY_CACHEDIR
if TYPE_CHECKING:
from dspy.adapters.base import Adapter
class TrainingStatus(str, Enum):
not_started = "not_started"
pending = "pending"
... | 179 | 5,476 |
dspy | dspy/retrievers/__init__.py | .py | from dspy.retrievers.embeddings import Embeddings, EmbeddingsWithScores
from dspy.retrievers.retrieve import Retrieve
__all__ = ["Embeddings", "EmbeddingsWithScores", "Retrieve"]
| 5 | 180 |
dspy | dspy/retrievers/embeddings.py | .py | from __future__ import annotations
import json
import os
from typing import Any
from dspy.utils.lazy_import import require
from dspy.utils.unbatchify import Unbatchify
np = require("numpy")
class Embeddings:
"""DSPy Embeddings retriever.
This class retrieves the top-k most similar passages from a corpus u... | 262 | 9,364 |
dspy | dspy/retrievers/weaviate_rm.py | .py |
import dspy
from dspy.dsp.utils import dotdict
from dspy.primitives.prediction import Prediction
try:
from uuid import uuid4
import weaviate
from weaviate.util import get_valid_uuid
except ImportError as err:
raise ImportError(
"The 'weaviate' extra is required to use WeaviateRM. Install it w... | 139 | 5,964 |
dspy | dspy/retrievers/retrieve.py | .py | import random
from dspy.predict.parameter import Parameter
from dspy.primitives.prediction import Prediction
from dspy.utils.callback import with_callbacks
def single_query_passage(passages):
passages_dict = {key: [] for key in list(passages[0].keys())}
for docs in passages:
for key, value in docs.it... | 68 | 2,039 |
dspy | dspy/retrievers/databricks_rm.py | .py | import json
import os
from dataclasses import dataclass
from importlib.util import find_spec
from typing import Any
import requests
import dspy
from dspy.primitives.prediction import Prediction
_databricks_sdk_installed = find_spec("databricks.sdk") is not None
@dataclass
class Document:
page_content: str
... | 453 | 20,552 |
dspy | dspy/datasets/__init__.py | .py | from dspy.datasets.alfworld import AlfWorld
from dspy.datasets.colors import Colors
from dspy.datasets.dataloader import DataLoader
from dspy.datasets.dataset import Dataset
from dspy.datasets.hotpotqa import HotPotQA
from dspy.datasets.math import MATH
__all__ = [
"Colors",
"DataLoader",
"Dataset",
"H... | 15 | 344 |
dspy | dspy/datasets/math.py | .py | import random
import re
class MATH:
def __init__(self, subset):
from datasets import load_dataset
import dspy
ds = load_dataset("DigitalLearningGmbH/MATH-lighteval", subset)
# NOTE: Defaults to sub-splitting MATH's 'test' split into train/dev/test, presuming that current
... | 65 | 1,900 |
dspy | dspy/datasets/dataloader.py | .py | import random
from collections.abc import Mapping
from typing import TYPE_CHECKING
import dspy
from dspy.datasets.dataset import Dataset
if TYPE_CHECKING:
import pandas as pd
class DataLoader(Dataset):
def __init__(self):
pass
def from_huggingface(
self,
dataset_name: str,
... | 199 | 7,350 |
dspy | dspy/datasets/hotpotqa.py | .py | import random
from dspy.datasets.dataset import Dataset
class HotPotQA(Dataset):
def __init__(
self,
*args,
only_hard_examples=True,
keep_details="dev_titles",
unofficial_dev=True,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
assert on... | 94 | 3,343 |
dspy | dspy/datasets/dataset.py | .py | from __future__ import annotations
import random
import uuid
from collections.abc import Iterable
from typing import Any
from dspy import Example
from dspy.dsp.utils import dotdict
class Dataset:
def __init__(
self,
train_seed: int = 0,
train_size: int | None = None,
eval_seed: i... | 140 | 4,795 |
dspy | dspy/datasets/colors.py | .py | import random
from dspy.datasets.dataset import Dataset
### A bunch of colors, originally from matplotlib
all_colors = [
"alice blue",
"dodger blue",
"light sky blue",
"deep sky blue",
"sky blue",
"steel blue",
"light steel blue",
"medium blue",
"navy blue",
"blue",
"royal ... | 175 | 3,555 |
dspy | dspy/datasets/gsm8k.py | .py | import random
import tqdm
class GSM8K:
def __init__(self):
self.do_shuffle = False
from datasets import load_dataset
dataset = load_dataset("gsm8k", "main")
hf_official_train = dataset["train"]
hf_official_test = dataset["test"]
official_train = []
offic... | 81 | 2,401 |
dspy | dspy/datasets/alfworld/alfworld.py | .py | import os
import queue
import random
def env_worker(inq, outq):
"""
Worker process: creates a single AlfredTWEnv instance,
handles 'init' (with task idx) and 'step' (with action).
"""
try:
import io
from contextlib import redirect_stderr, redirect_stdout
import alfworld.a... | 156 | 4,482 |
dspy | dspy/core/types.py | .py | """Normalized request, response, and stream types for DSPy language models."""
from __future__ import annotations
import json
import mimetypes
from collections.abc import AsyncIterator, Callable, Iterator, Mapping
from dataclasses import dataclass
from dataclasses import field as dataclass_field
from pprint import pf... | 2,064 | 72,630 |
dspy | dspy/core/__init__.py | .py | """Core typed request/response objects used by DSPy internals."""
from dspy.core.types import *
from dspy.core.types import __all__ as __all__
| 5 | 144 |
dspy | dspy/predict/react_v2.py | .py | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable, get_args
import pydantic
import dspy
from dspy.adapters.types.tool import Tool, ToolCallResults, ToolCalls
from dspy.primitives.module import Module
from dspy.primitives.prediction import Prediction
from dspy.signature... | 247 | 9,902 |
dspy | dspy/predict/parameter.py | .py | class Parameter:
pass
| 3 | 26 |
dspy | dspy/predict/code_act.py | .py | import inspect
import logging
import warnings
from typing import Callable
import dspy
from dspy.adapters.types.tool import Tool
from dspy.predict.program_of_thought import ProgramOfThought
from dspy.predict.react import ReAct
from dspy.primitives.code_interpreter import CodeInterpreter, _validate_interpreter_factory
f... | 155 | 6,905 |
dspy | dspy/predict/multi_chain_comparison.py | .py | from dspy.predict.predict import Predict
from dspy.primitives.module import Module
from dspy.signatures import InputField, OutputField
from dspy.signatures.signature import ensure_signature
class MultiChainComparison(Module):
def __init__(self, signature, M=3, temperature=0.7, **config): # noqa: N803
sup... | 54 | 1,899 |
dspy | dspy/predict/predict.py | .py | import logging
import random
import types
from typing import Any, Literal, Union, get_args, get_origin
from pydantic import BaseModel
from pydantic_core import PydanticUndefined
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.adapters.utils import annotation_allows_none
from dspy.clients.base_lm import B... | 406 | 16,181 |
dspy | dspy/predict/aggregation.py | .py | from dspy.evaluate import normalize_text
from dspy.primitives.prediction import Completions, Prediction
def default_normalize(s):
return normalize_text(s) or None
def majority(prediction_or_completions, normalize=default_normalize, field=None):
"""
Returns the most common completion for the target field... | 55 | 1,832 |
dspy | dspy/predict/parallel.py | .py | import threading
from typing import Any
from dspy.dsp.utils.settings import settings
from dspy.primitives.example import Example
from dspy.utils.parallelizer import ParallelExecutor
class Parallel:
def __init__(
self,
num_threads: int | None = None,
max_errors: int | None = None,
... | 128 | 5,209 |
dspy | dspy/predict/best_of_n.py | .py | from typing import Callable
import dspy
from dspy.predict.predict import Module, Prediction
class BestOfN(Module):
"""Runs a module up to N times and returns the highest-scoring prediction.
At each attempt, the module is called with a different rollout ID at
``temperature=1.0`` to encourage output diver... | 84 | 3,209 |
dspy | dspy/predict/__init__.py | .py | from dspy.predict.aggregation import majority
from dspy.predict.best_of_n import BestOfN
from dspy.predict.chain_of_thought import ChainOfThought
from dspy.predict.code_act import CodeAct
from dspy.predict.knn import KNN
from dspy.predict.multi_chain_comparison import MultiChainComparison
from dspy.predict.parallel imp... | 31 | 834 |
dspy | dspy/predict/program_of_thought.py | .py | import json
import logging
import re
import warnings
from collections.abc import Callable, Iterator
from contextlib import contextmanager
import dspy
from dspy.primitives.code_interpreter import (
CodeExecutionError,
CodeInterpreter,
FinalOutput,
_create_interpreter,
_validate_interpreter,
_val... | 231 | 9,498 |
dspy | dspy/predict/refine.py | .py | import inspect
import textwrap
from typing import Callable
import orjson
import dspy
from dspy.adapters.utils import get_field_description_string
from dspy.predict.predict import Prediction
from dspy.signatures import InputField, OutputField, Signature
from .predict import Module
class OfferFeedback(Signature):
... | 220 | 9,795 |
dspy | dspy/predict/react.py | .py | import logging
from typing import TYPE_CHECKING, Any, Callable, Literal
import dspy
from dspy.adapters.types.tool import Tool
from dspy.primitives.module import Module
from dspy.signatures.signature import ensure_signature
from dspy.utils.exceptions import ContextWindowExceededError, format_error_for_lm
logger = logg... | 240 | 11,702 |
dspy | dspy/predict/chain_of_thought.py | .py | from typing import Any
from pydantic.fields import FieldInfo
import dspy
from dspy.primitives.module import Module
from dspy.signatures.signature import Signature, ensure_signature
# NOTE: This restores the legacy rationale_field behavior after PR #8822.
class ChainOfThought(Module):
"""A module that reasons s... | 56 | 2,224 |
dspy | dspy/predict/rlm.py | .py | """
Recursive Language Model (RLM) module for DSPy.
RLMs are an inference strategy where LLMs treat long contexts as part of an external
environment rather than feeding them directly to the model. The LLM writes Python code
to programmatically examine, decompose, and recursively call sub-LLMs over snippets.
Reference... | 821 | 36,792 |
dspy | dspy/predict/knn.py | .py | from dspy.clients import Embedder
from dspy.primitives import Example
from dspy.utils.lazy_import import require
np = require("numpy")
class KNN:
def __init__(self, k: int, trainset: list[Example], vectorizer: Embedder):
"""
A k-nearest neighbors retriever that finds similar examples from a train... | 54 | 1,975 |
dspy | dspy/predict/flex/ctx.py | .py | from __future__ import annotations
import ast
import types
import typing
from dataclasses import dataclass, field
from typing import Any, get_args, get_origin
@dataclass
class FlexContext:
"""Signature + tools that the baseline and code-optimization prompts render from."""
signature_cls: type
tools: lis... | 177 | 7,600 |
dspy | dspy/predict/flex/flex.py | .py | from __future__ import annotations
from typing import Any, Callable
from dspy.clients.base_lm import BaseLM
from dspy.dsp.utils.settings import settings
from dspy.predict.flex.bridge import BridgeRuntime
from dspy.predict.flex.ctx import FlexContext
from dspy.predict.parameter import Parameter
from dspy.predict.predi... | 169 | 7,023 |
dspy | dspy/predict/flex/bridge.py | .py | """Host side of the dspy.Flex sandbox bridge.
A ``Flex`` never executes its optimizer-authored ``module_src`` in the host process. Instead,
every ``forward``:
1. creates a fresh interpreter from the Flex's ``interpreter_factory`` (``BridgeRuntime.forward``);
2. injects the sandbox-side shim (``_sandbox_shim.py``), wh... | 366 | 16,557 |
dspy | dspy/predict/flex/__init__.py | .py | from dspy.predict.flex.flex import Flex
__all__ = ["Flex"]
| 4 | 60 |
dspy | dspy/predict/flex/_sandbox_shim.py | .py | """Sandbox side of the dspy.Flex bridge: a stand-in ``dspy`` module for optimizer-authored code.
``BridgeRuntime.forward`` executes this source in each per-forward interpreter before the bound
``module_src``, so the generated module runs sandboxed while predictors are built and called on
the host:
- ``dspy.Predict`` ... | 128 | 4,392 |
dspy | dspy/predict/flex/primitives_doc.py | .py | PRIMITIVES_CATALOG: str = """\
You are authoring ONE Python source string: a single `dspy.Module` subclass that
implements the user's signature. It has exactly two methods:
1) `def __init__(self):` — calls `super().__init__()` and assigns each predictor it
needs to an attribute, e.g. `self.classify = dspy.Predict("... | 246 | 13,216 |
dspy | dspy/predict/avatar/signatures.py | .py | import dspy
from dspy.predict.avatar.models import Action
class Actor(dspy.Signature):
"""You will be given `Tools` which will be a list of tools to use to accomplish the `Goal`. Given the user query, your task is to decide which tool to use and what input values to provide.
You will output action needed to ... | 21 | 828 |
dspy | dspy/predict/avatar/models.py | .py | from typing import Any
from pydantic import BaseModel, Field
class Tool(BaseModel):
tool: Any
name: str
desc: str | None
input_type: str | None = None
def __str__(self) -> str:
return f"{self.name}{f'(valid_input: {self.input_type})' if self.input_type else ''}: {self.desc}"
def __r... | 28 | 658 |
dspy | dspy/predict/avatar/avatar.py | .py | from copy import deepcopy
from pydantic.fields import FieldInfo
import dspy
from dspy.predict.avatar.models import Action, ActionOutput, Tool
from dspy.predict.avatar.signatures import Actor
from dspy.signatures.signature import ensure_signature
def get_number_with_suffix(number: int) -> str:
if number == 1:
... | 164 | 5,399 |
dspy | dspy/utils/callback.py | .py | import functools
import inspect
import logging
import uuid
from typing import Any, Callable
import dspy
import dspy.utils.callback_context as callback_context
ACTIVE_CALL_ID = callback_context.ACTIVE_CALL_ID
logger = logging.getLogger(__name__)
_INTERPRETER_OPERATIONS = {
"execute": "execute",
"invoke_tool"... | 456 | 16,868 |
dspy | dspy/utils/syncify.py | .py | import asyncio
from types import MethodType
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from dspy.primitives.module import Module
def run_async(coro):
"""Run an async coroutine from a synchronous context."""
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = Non... | 61 | 1,997 |
dspy | dspy/utils/mcp.py | .py | from typing import TYPE_CHECKING, Any
from dspy.adapters.types.tool import Tool, convert_input_schema_to_tool_args
if TYPE_CHECKING:
import mcp
def _convert_mcp_tool_result(call_tool_result: "mcp.types.CallToolResult") -> str | list[Any]:
from mcp.types import TextContent
text_contents: list[TextConten... | 48 | 1,527 |
dspy | dspy/utils/lazy_import.py | .py | """Lazy-import helpers for optional dependencies.
Optional deps must be importable lazily so that `import dspy` succeeds even
when they are absent. Call sites get a module-level binding that defers the
real import until first attribute access:
from dspy.utils.lazy_import import require
np = require("numpy") ... | 191 | 6,611 |
dspy | dspy/utils/parallelizer.py | .py | import contextlib
import copy
import logging
import signal
import sys
import threading
import time
import traceback
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
import tqdm
from dspy.dsp.utils.settings import settings, thread_local_overrides
from dspy.utils.callback_context import _bind_ac... | 262 | 10,054 |
dspy | dspy/utils/usage_tracker.py | .py | """Usage tracking utilities for DSPy."""
from collections import defaultdict
from contextlib import contextmanager
from typing import Any, Generator
from pydantic import BaseModel
from dspy.dsp.utils.settings import settings
class UsageTracker:
"""Tracks LM usage data within a context."""
def __init__(sel... | 75 | 2,701 |
dspy | dspy/utils/exceptions.py | .py | from __future__ import annotations
import traceback
from typing import Any
from dspy.signatures.signature import Signature
class DSPyError(Exception):
"""Base class for DSPy errors with structured metadata.
Args:
message: Human-readable error message.
code: Stable DSPy error code. Defaults ... | 284 | 9,119 |
dspy | dspy/utils/callback_context.py | .py | import functools
from contextvars import ContextVar
from typing import Callable
ACTIVE_CALL_ID = ContextVar("active_call_id", default=None)
_ACTIVE_COMPILES = ContextVar("active_compiles", default=())
def _bind_active_call_id(fn: Callable) -> Callable:
"""Bind the current callback call ID to each synchronous inv... | 22 | 624 |
dspy | dspy/utils/__init__.py | .py | import os
import requests
from dspy.streaming.messages import StatusMessage, StatusMessageProvider
from dspy.utils import exceptions
from dspy.utils.annotation import experimental
from dspy.utils.callback import BaseCallback, with_callbacks
from dspy.utils.dummies import DummyLM, DummyVectorizer, dummy_rm
from dspy.u... | 39 | 1,164 |
dspy | dspy/utils/hasher.py | .py | import hashlib
from pickle import dumps
from typing import Any
"""
The following class was pulled from the `datasets` package from Hugging Face.
The reason for vendoring this code is to avoid a hard dependency on `datasets`,
which is a large package that is not needed for the majority of use cases.
License: Apache Li... | 66 | 2,120 |
dspy | dspy/utils/langchain_tool.py | .py | from typing import TYPE_CHECKING, Any
from dspy.adapters.types.tool import Tool, convert_input_schema_to_tool_args
if TYPE_CHECKING:
from langchain.tools import BaseTool
def convert_langchain_tool(tool: "BaseTool") -> Tool:
"""Build a DSPy tool from a LangChain tool.
This function converts a LangC... | 48 | 1,504 |
dspy | dspy/utils/constants.py | .py | # Used to indicate whether the type of a field in a signature is originally not defined.
IS_TYPE_UNDEFINED = "IS_TYPE_UNDEFINED"
| 3 | 130 |
dspy | dspy/utils/logging_utils.py | .py | import logging
import logging.config
import sys
LOGGING_LINE_FORMAT = "%(asctime)s %(levelname)s %(name)s: %(message)s"
LOGGING_DATETIME_FORMAT = "%Y/%m/%d %H:%M:%S"
class DSPyLoggingStream:
"""
A Python stream for use with event logging APIs throughout DSPy (`eprint()`,
`logger.info()`, etc.). This stre... | 74 | 2,123 |
dspy | dspy/utils/inspect_history.py | .py | from __future__ import annotations
import json
import sys
from contextlib import suppress
from typing import Any, TextIO
def _green(text: str, end: str = "\n", *, use_colors: bool = True) -> str:
if use_colors:
return "\x1b[32m" + str(text).lstrip() + "\x1b[0m" + end
return str(text).lstrip() + end
... | 108 | 5,248 |
dspy | dspy/utils/annotation.py | .py | import inspect
import re
import types
from typing import Callable, ParamSpec, TypeVar, overload
P = ParamSpec("P")
R = TypeVar("R")
@overload
def experimental(f: Callable[P, R], version: str | None = None) -> Callable[P, R]: ...
@overload
def experimental(f: None = None, version: str | None = None) -> Callable[[Call... | 89 | 2,831 |
dspy | dspy/utils/dummies.py | .py | from __future__ import annotations
import random
from collections import defaultdict
from typing import Any
from dspy.adapters.chat_adapter import FieldInfoWithName, field_header_pattern
from dspy.clients.base_lm import BaseLM
from dspy.dsp.utils.utils import dotdict
from dspy.signatures.field import OutputField
from... | 215 | 7,721 |
dspy | dspy/utils/caching.py | .py | import os
from pathlib import Path
_DEFAULT_CACHE_DIR = os.path.join(Path.home(), ".dspy_cache")
DSPY_CACHEDIR = os.environ.get("DSPY_CACHEDIR") or _DEFAULT_CACHE_DIR
def create_subdir_in_cachedir(subdir: str) -> str:
"""Create a subdirectory in the DSPy cache directory."""
subdir = os.path.join(DSPY_CACHEDI... | 14 | 425 |
dspy | dspy/utils/unbatchify.py | .py | import queue
import threading
import time
from concurrent.futures import Future
from typing import Any, Callable
class Unbatchify:
def __init__(
self,
batch_fn: Callable[[list[Any]], list[Any]],
max_batch_size: int = 32,
max_wait_time: float = 0.1
):
"""
Initial... | 113 | 3,608 |
dspy | dspy/utils/asyncify.py | .py | import functools
from typing import TYPE_CHECKING, Any, Awaitable, Callable
import anyio
from anyio import CapacityLimiter
if TYPE_CHECKING:
from dspy.primitives.module import Module
_limiter = None
def get_async_max_workers():
import dspy
return dspy.settings.async_max_workers
def get_limiter():
... | 66 | 2,080 |
dspy | dspy/utils/saving.py | .py | import logging
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import cloudpickle
import orjson
if TYPE_CHECKING:
from dspy.primitives.module import Module
logger = logging.getLogger(__name__)
def get_dependency_versions():
import dspy
cloudpickle_version = ".".join(cloudpickle.__... | 62 | 2,178 |
dspy | dspy/utils/magicattr.py | .py | """
Compatibility layer for magicattr that works with Python 3.14+
This module provides a patched version of magicattr's functionality
that is compatible with Python 3.14's removal of ast.Num and ast.Str.
Based on magicattr 0.1.6 by Jairus Martin (MIT License)
https://github.com/frmdstryr/magicattr
"""
import ast
imp... | 128 | 4,082 |
dspy | dspy/propose/utils.py | .py | import inspect
import json
import re
import dspy
try:
from IPython.core.magics.code import extract_symbols
except ImportError:
# Won't be able to read code from jupyter notebooks
extract_symbols = None
from dspy.predict.parameter import Parameter
from dspy.teleprompt.utils import get_signature, new_getfi... | 190 | 7,311 |
dspy | dspy/propose/__init__.py | .py | from dspy.propose.grounded_proposer import GroundedProposer
__all__ = [
"GroundedProposer",
]
| 6 | 99 |
dspy | dspy/propose/propose_base.py | .py | from abc import ABC, abstractmethod
class Proposer(ABC):
def __init__(self):
pass
@abstractmethod
def propose_instructions_for_program(self):
pass
def propose_instruction_for_predictor(self):
pass
| 14 | 241 |
dspy | dspy/propose/grounded_proposer.py | .py | import random
import dspy
from dspy.propose.dataset_summary_generator import create_dataset_summary
from dspy.propose.propose_base import Proposer
from dspy.propose.utils import (
create_example_string,
create_predictor_level_history_string,
get_dspy_source_code,
strip_prefix,
)
from dspy.teleprompt.ut... | 418 | 16,747 |
dspy | dspy/propose/dataset_summary_generator.py | .py | import re
import dspy
from dspy.propose.utils import strip_prefix
class ObservationSummarizer(dspy.Signature):
("""Given a series of observations I have made about my dataset, please summarize them into a brief 2-3 sentence summary which highlights only the most important details.""")
observations = dspy.Inp... | 100 | 5,056 |
dspy | dspy/primitives/python_interpreter.py | .py | """
Local interpreter for secure Python code execution using Deno/Pyodide.
This module provides PythonInterpreter, which runs Python code in a sandboxed
WASM environment using Deno and Pyodide. It implements the Interpreter
protocol defined in interpreter.py.
"""
import asyncio
import dataclasses
import functools
imp... | 891 | 37,501 |
dspy | dspy/primitives/base_module.py | .py | import copy
import logging
from collections import deque
from collections.abc import Generator
from pathlib import Path
import cloudpickle
import orjson
from dspy.utils.saving import get_dependency_versions
# NOTE: Note: It's important (temporary decision) to maintain named_parameters that's different in behavior fr... | 293 | 13,235 |
dspy | dspy/primitives/example.py | .py | from pydantic import BaseModel
class Example:
"""A flexible data container for DSPy examples and training data with named fields.
An `Example` is roughly one row from a HuggingFace dataset or pandas
`DataFrame`. It behaves a lot like a dictionary or dot-access record: you
can read fields with `exampl... | 353 | 12,494 |
dspy | dspy/primitives/sandbox_serializable.py | .py | """Abstract base class for RLM sandbox-serializable types.
Types that subclass :class:`SandboxSerializable` can be injected into the
REPL environment used by :class:`dspy.RLM`. Subclasses implement four
abstract methods describing how a value enters and appears inside the
sandbox, and inherit:
- ``__get_pydantic_core... | 128 | 4,944 |
dspy | dspy/primitives/prediction.py | .py | from dspy.primitives.example import Example
class Prediction(Example):
"""A prediction object that contains the output of a DSPy module.
Prediction inherits from Example.
To allow feedback-augmented scores, Prediction supports comparison operations
(<, >, <=, >=) for Predictions with a `scor... | 174 | 6,195 |
dspy | dspy/primitives/__init__.py | .py | from dspy.primitives.base_module import BaseModule
from dspy.primitives.code_interpreter import CodeExecutionError, CodeInterpreter, CodeInterpreterError, FinalOutput
from dspy.primitives.example import Example
from dspy.primitives.module import Module
from dspy.primitives.prediction import Completions, Prediction
from... | 22 | 697 |
dspy | dspy/primitives/repl_types.py | .py | """
REPL data types for RLM and interpreter interactions.
These types represent the state and history of REPL-based execution:
- REPLVariable: Metadata about variables available in the REPL
- REPLEntry: A single interaction (reasoning, code, output)
- REPLHistory: Container for the full interaction history
"""
from _... | 161 | 5,571 |
dspy | dspy/primitives/code_interpreter.py | .py | """
Abstract interpreter interface for code execution environments.
This module defines the CodeInterpreter protocol that allows RLM and other
code-executing modules to work with different interpreter implementations:
- PythonInterpreter: Local Deno/Pyodide WASM interpreter
- MockInterpreter: Scriptable responses for ... | 180 | 6,794 |
dspy | dspy/primitives/module.py | .py | import inspect
import logging
from typing import Any, TextIO
from dspy.dsp.utils.settings import settings
from dspy.predict.parallel import Parallel
from dspy.primitives.base_module import BaseModule
from dspy.primitives.example import Example
from dspy.primitives.prediction import Prediction
from dspy.utils import ma... | 355 | 13,329 |
dspy | dspy/adapters/two_step_adapter.py | .py | from typing import Any
import json_repair
from dspy.adapters.base import Adapter
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.adapters.types import ToolCalls
from dspy.adapters.utils import get_field_description_string
from dspy.clients.base_lm import BaseLM
from dspy.signatures.field import InputFiel... | 245 | 9,265 |
dspy | dspy/adapters/utils.py | .py | import ast
import enum
import inspect
import json
import types
from collections.abc import Mapping
from typing import TYPE_CHECKING, Annotated, Any, Literal, Union, get_args, get_origin
import json_repair
import pydantic
from pydantic import TypeAdapter
from pydantic.fields import FieldInfo
from dspy.adapters.types.b... | 337 | 12,745 |
dspy | dspy/adapters/json_adapter.py | .py | import json
import logging
from typing import Any, get_origin
import json_repair
import pydantic
import regex
from pydantic.fields import FieldInfo
from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName
from dspy.adapters.types.tool import ToolCalls
from dspy.adapters.utils import (
apply_output_fi... | 312 | 13,594 |
dspy | dspy/adapters/chat_adapter.py | .py | import re
import textwrap
from typing import Any, NamedTuple
from pydantic.fields import FieldInfo
from dspy.adapters.base import Adapter
from dspy.adapters.types.tool import ToolCalls
from dspy.adapters.utils import (
apply_output_field_defaults,
format_field_value,
get_annotation_name,
get_field_des... | 300 | 13,069 |
dspy | dspy/adapters/__init__.py | .py | from dspy.adapters.base import Adapter
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.adapters.json_adapter import JSONAdapter
from dspy.adapters.two_step_adapter import TwoStepAdapter
from dspy.adapters.types import Audio, Code, File, History, Image, Reasoning, Tool, ToolCallResults, ToolCalls, Type
from... | 25 | 619 |
dspy | dspy/adapters/xml_adapter.py | .py | import re
from typing import Any
from pydantic.fields import FieldInfo
from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName
from dspy.adapters.utils import apply_output_field_defaults, format_field_value, translate_field_type
from dspy.signatures.signature import Signature
class XMLAdapter(ChatAdap... | 121 | 4,749 |
dspy | dspy/adapters/_legacy_type_markers.py | .py | """Private compatibility helpers for legacy `dspy.Type` marker serialization."""
from __future__ import annotations
import json
import re
from typing import Any
import json_repair
from dspy.adapters.types.base_type import CUSTOM_TYPE_END_IDENTIFIER, CUSTOM_TYPE_START_IDENTIFIER
from dspy.core.types import LMAudioPa... | 146 | 6,191 |
dspy | dspy/adapters/baml_adapter.py | .py | """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
"""
import inspect
import types
from typing import Any, Literal, Union, get_args, get_origin
from pydantic import BaseModel
from dspy.adapters.json_adap... | 271 | 10,580 |
dspy | dspy/adapters/base.py | .py | import json
import logging
from typing import Any, get_origin
import json_repair
from dspy.adapters._legacy_type_markers import (
_expand_legacy_custom_type_markers_in_chat_message,
_expand_legacy_custom_type_markers_in_lm_message,
)
from dspy.adapters.types import History, Type
from dspy.adapters.types.reaso... | 779 | 35,162 |
dspy | dspy/adapters/types/citation.py | .py | from typing import Any, Optional
import pydantic
from dspy.adapters.types.base_type import Type
from dspy.utils.annotation import experimental
@experimental(version="3.0.4")
class Citations(Type):
"""Citations extracted from an LM response with source references.
This type represents citations returned by ... | 222 | 7,947 |
dspy | dspy/adapters/types/image.py | .py | import base64
import io
import mimetypes
import os
import warnings
from functools import lru_cache
from typing import Any, Union
from urllib.parse import urlparse
import pydantic
import requests
from dspy.adapters.types.base_type import Type
try:
from PIL import Image as PILImage
from PIL import Unidentified... | 297 | 11,506 |
dspy | dspy/adapters/types/file.py | .py | import base64
import mimetypes
import os
from typing import Any
import pydantic
from dspy.adapters.types.base_type import Type
class File(Type):
"""A file input type for DSPy.
See https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages-user_message-content-array_of_content_parts-file... | 202 | 7,414 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.