index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
24,756
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/cohere.py
26,27
1,119
giveup_hdlr
28,33
27,33
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
if "rate limits" in details.message: return False return True
"""wrapper function that decides when to give up on retry""" if "rate limits" in details.message: return False return True
9
986
27
1,013
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
24,757
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/cohere.py
76,77
33,119
basic_request
Cohere
77,101
77,101
class Cohere(LM): """Wrapper around Cohere's API. Currently supported models include `command-r-plus`, `command-r`, `command`, `command-nightly`, `command-light`, `command-light-nightly`. """ def __init__( self, model: str = "command-r", api_key: Optional[str] = None, s...
class Cohere(LM): """Wrapper around Cohere's API. Currently supported models include `command-r-plus`, `command-r`, `command`, `command-nightly`, `command-light`, `command-light-nightly`. """ def __init__( self, model: str = "command-r", api_key: Optional[str] = None, s...
raw_kwargs = kwargs kwargs = { **self.kwargs, "stop_sequences": self.stop_sequences, "chat_history": [], "message": prompt, **kwargs, } kwargs.pop("num_generations") if "n" in kwargs.keys(): kwargs.pop("n") ...
raw_kwargs = kwargs kwargs = { **self.kwargs, "stop_sequences": self.stop_sequences, "chat_history": [], "message": prompt, **kwargs, } kwargs.pop("num_generations") if "n" in kwargs.keys(): kwargs.pop("n") ...
38
605
193
798
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import cohere cohere_api_error = cohere.errors.UnauthorizedError except ImportError: cohere_api_error = Exception # print("Not loading Cohere because it is not installed.") except AttributeError: cohere_api_error =...
24,758
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/colbertv2.py
38,40
1,77
colbertv2_get_request_v2
40,52
40,52
import functools from typing import Any, Optional, Union import requests from dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory from 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.""" d...
import functools from typing import Any, Optional, Union import requests from dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory from 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.""" d...
assert ( k <= 100 ), "Only k <= 100 is supported for the hosted ColBERTv2 server at the moment." payload = {"query": query, "k": k} res = requests.get(url, params=payload, timeout=10) topk = res.json()["topk"][:k] topk = [{**d, "long_text": d["text"]} for d in topk] return topk[:k]...
assert ( k <= 100 ), "Only k <= 100 is supported for the hosted ColBERTv2 server at the moment." payload = {"query": query, "k": k} res = requests.get(url, params=payload, timeout=10) topk = res.json()["topk"][:k] topk = [{**d, "long_text": d["text"]} for d in topk] return topk[:k]...
45
665
137
802
import functools from typing import Any, Optional, Union import requests from dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory from 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.""" d...
import functools from typing import Any, Optional, Union import requests from dsp.modules.cache_utils import CacheMemory, NotebookCacheMemory from 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.""" d...
24,759
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/dummy_lm.py
26,27
8,92
basic_request
DummyLM
28,81
27,81
class DummyLM(LM): """Dummy language model for unit testing purposes.""" def __init__(self, answers: Union[list[str], dict[str, str]], follow_examples: bool = False): """Initializes the dummy language model. Parameters: - answers: A list of strings or a dictionary with string keys and ...
class DummyLM(LM): """Dummy language model for unit testing purposes.""" def __init__(self, answers: Union[list[str], dict[str, str]], follow_examples: bool = False): """Initializes the dummy language model. Parameters: - answers: A list of strings or a dictionary with string keys and ...
dummy_response = {"choices": []} for _ in range(n): answer = None if self.follow_examples: prefix = prompt.split("\n")[-1] _instructions, _format, *examples, _output = prompt.split("\n---\n") examples_str = "\n".join(examples) ...
"""Generates a dummy response based on the prompt.""" dummy_response = {"choices": []} for _ in range(n): answer = None if self.follow_examples: prefix = prompt.split("\n")[-1] _instructions, _format, *examples, _output = prompt.split("\n-...
171
438
597
1,035
import re from typing import Union from dsp.modules import LM # This testing module was moved in PR #735 to patch Arize Phoenix logging class DummyLM(LM): """Dummy language model for unit testing purposes.""" def __init__(self, answers: Union[list[str], dict[str, str]], follow_examples: bool = False): ...
import re from typing import Union from dsp.modules import LM # This testing module was moved in PR #735 to patch Arize Phoenix logging class DummyLM(LM): """Dummy language model for unit testing purposes.""" def __init__(self, answers: Union[list[str], dict[str, str]], follow_examples: bool = False): ...
24,760
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/google.py
18,19
1,163
backoff_hdlr
20,27
19,27
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
"""Handler from https://pypi.org/project/backoff/""" print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
17
1,401
64
1,465
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
24,761
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/google.py
109,110
54,163
basic_request
Google
110,133
110,133
class Google(LM): """Wrapper around Google's API. Currently supported models include `gemini-pro-1.0`. """ def __init__( self, model: str = "models/gemini-1.0-pro", api_key: Optional[str] = None, safety_settings: Optional[Iterable] = BLOCK_ONLY_HIGH, **kwargs, ...
class Google(LM): """Wrapper around Google's API. Currently supported models include `gemini-pro-1.0`. """ def __init__( self, model: str = "models/gemini-1.0-pro", api_key: Optional[str] = None, safety_settings: Optional[Iterable] = BLOCK_ONLY_HIGH, **kwargs, ...
raw_kwargs = kwargs kwargs = { **self.kwargs, **kwargs, } # Google disallows "n" arguments n = kwargs.pop("n", None) if n is not None and n > 1 and kwargs['temperature'] == 0.0: kwargs['temperature'] = 0.7 response = self.llm....
raw_kwargs = kwargs kwargs = { **self.kwargs, **kwargs, } # Google disallows "n" arguments n = kwargs.pop("n", None) if n is not None and n > 1 and kwargs['temperature'] == 0.0: kwargs['temperature'] = 0.7 response = self.llm....
53
841
199
1,040
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
import os from collections.abc import Iterable from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import google.generativeai as genai from google.api_core.exceptions import GoogleAPICallError google_api_error = GoogleAPICallError except ImportError: google_api_error = ...
24,762
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/googlevertexai.py
24,25
1,178
giveup_hdlr
26,30
25,30
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
if "rate limits" in details.message: return False return True
"""wrapper function that decides when to give up on retry""" if "rate limits" in details.message: return False return True
9
1,724
25
1,749
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
24,763
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/googlevertexai.py
112,116
30,178
_prepare_params
GoogleVertexAI
116,122
116,122
class GoogleVertexAI(LM): """Wrapper around GoogleVertexAI's API. Currently supported models include `gemini-pro-1.0`. """ def __init__( self, model: str = "text-bison@002", **kwargs, ): """ Parameters ---------- model : str Which pre-trained mod...
class GoogleVertexAI(LM): """Wrapper around GoogleVertexAI's API. Currently supported models include `gemini-pro-1.0`. """ def __init__( self, model: str = "text-bison@002", **kwargs, ): """ Parameters ---------- model : str Which pre-trained mod...
stop_sequences = parameters.get('stop') params_mapping = {"n": "candidate_count", 'max_tokens':'max_output_tokens'} params = {params_mapping.get(k, k): v for k, v in parameters.items()} params = {**self.kwargs, "stop_sequences": stop_sequences, **params} return {k: params[k] for ...
stop_sequences = parameters.get('stop') params_mapping = {"n": "candidate_count", 'max_tokens':'max_output_tokens'} params = {params_mapping.get(k, k): v for k, v in parameters.items()} params = {**self.kwargs, "stop_sequences": stop_sequences, **params} return {k: params[k] for ...
33
1,372
125
1,497
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
"""Module for interacting with Google Vertex AI.""" from typing import Any, Dict import backoff from pydantic_core import PydanticCustomError from dsp.modules.lm import LM try: import vertexai # type: ignore[import-untyped] from vertexai.language_models import CodeGenerationModel, TextGenerationModel fr...
24,764
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/groq_client.py
18,19
1,159
backoff_hdlr
20,27
19,27
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): FILL_FUNC_BODYclass GroqLM(LM): """Wrapper ...
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): """Handler from https://pypi.org/project/ba...
print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
"""Handler from https://pypi.org/project/backoff/""" print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
17
1,406
64
1,470
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): FILL_FUNC_BODYclass GroqLM(LM): """Wrapper ...
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): """Handler from https://pypi.org/project/ba...
24,765
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/groq_client.py
72,73
27,159
basic_request
GroqLM
73,91
73,91
class GroqLM(LM): """Wrapper around groq's API. Args: model (str, optional): groq supported LLM model to use. Defaults to "mixtral-8x7b-32768". api_key (Optional[str], optional): API provider Authentication token. use Defaults to None. **kwargs: Additional arguments to pass to the API p...
class GroqLM(LM): """Wrapper around groq's API. Args: model (str, optional): groq supported LLM model to use. Defaults to "mixtral-8x7b-32768". api_key (Optional[str], optional): API provider Authentication token. use Defaults to None. **kwargs: Additional arguments to pass to the API p...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} kwargs["messages"] = [{"role": "user", "content": prompt}] response = self.chat_request(**kwargs) history = { "prompt": prompt, "response": response.choices[0].message.content, "kwargs":...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} kwargs["messages"] = [{"role": "user", "content": prompt}] response = self.chat_request(**kwargs) history = { "prompt": prompt, "response": response.choices[0].message.content, "kwargs":...
31
1,163
148
1,311
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): """Handler from https://pypi.org/project/ba...
import logging from typing import Any import backoff try: import groq from groq import Groq groq_api_error = (groq.APIError, groq.RateLimitError) except ImportError: groq_api_error = Exception from dsp.modules.lm import LM def backoff_hdlr(details): """Handler from https://pypi.org/project/ba...
24,767
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/hf.py
144,145
30,198
basic_request
HFModel
145,159
145,159
class HFModel(LM): def __init__( self, model: str, checkpoint: Optional[str] = None, is_client: bool = False, hf_device_map: Literal[ "auto", "balanced", "balanced_low_0", "sequential", ] = "auto", token: Optiona...
class HFModel(LM): def __init__( self, model: str, checkpoint: Optional[str] = None, is_client: bool = False, hf_device_map: Literal[ "auto", "balanced", "balanced_low_0", "sequential", ] = "auto", token: Optiona...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} response = self._generate(prompt, **kwargs) history = { "prompt": prompt, "response": response, "kwargs": kwargs, "raw_kwargs": raw_kwargs, } self.history.append(histor...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} response = self._generate(prompt, **kwargs) history = { "prompt": prompt, "response": response, "kwargs": kwargs, "raw_kwargs": raw_kwargs, } self.history.append(histor...
26
1,860
112
1,972
# from peft import PeftConfig, PeftModel # from transformers import AutoModelForSeq2SeqLM, AutoModelForCausalLM, AutoTokenizer, AutoConfig import os from typing import Literal, Optional from dsp.modules.lm import LM # from dsp.modules.finetuning.finetune_hf import preprocess_prompt def openai_to_hf(**kwargs): h...
# from peft import PeftConfig, PeftModel # from transformers import AutoModelForSeq2SeqLM, AutoModelForCausalLM, AutoTokenizer, AutoConfig import os from typing import Literal, Optional from dsp.modules.lm import LM # from dsp.modules.finetuning.finetune_hf import preprocess_prompt def openai_to_hf(**kwargs): h...
24,768
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/lm.py
31,32
4,113
print_red
LM
32,34
32,34
class LM(ABC): """Abstract class for language models.""" def __init__(self, model): self.kwargs = { "model": model, "temperature": 0.0, "max_tokens": 150, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "n": ...
class LM(ABC): """Abstract class for language models.""" def __init__(self, model): self.kwargs = { "model": model, "temperature": 0.0, "max_tokens": 150, "top_p": 1, "frequency_penalty": 0, "presence_penalty": 0, "n": ...
return "\x1b[31m" + str(text) + "\x1b[0m" + end
return "\x1b[31m" + str(text) + "\x1b[0m" + end
8
1,079
31
1,110
from abc import ABC, abstractmethod class LM(ABC): """Abstract class for language models.""" def __init__(self, model): self.kwargs = { "model": model, "temperature": 0.0, "max_tokens": 150, "top_p": 1, "frequency_penalty": 0, "p...
from abc import ABC, abstractmethod class LM(ABC): """Abstract class for language models.""" def __init__(self, model): self.kwargs = { "model": model, "temperature": 0.0, "max_tokens": 150, "top_p": 1, "frequency_penalty": 0, "p...
24,769
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/mistral.py
17,18
1,130
backoff_hdlr
19,26
18,26
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
"""Handler from https://pypi.org/project/backoff/""" print( "Backing off {wait:0.1f} seconds after {tries} tries " "calling function {target} with kwargs " "{kwargs}".format(**details), )
17
1,054
64
1,118
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
24,770
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/mistral.py
73,74
33,130
basic_request
Mistral
75,99
74,99
class Mistral(LM): """Wrapper around Mistral AI's API. Currently supported models include `mistral-small-latest`, `mistral-medium-latest`, `mistral-large-latest`. """ def __init__( self, model: str = "mistral-medium-latest", api_key: Optional[str] = None, **kwargs, ...
class Mistral(LM): """Wrapper around Mistral AI's API. Currently supported models include `mistral-small-latest`, `mistral-medium-latest`, `mistral-large-latest`. """ def __init__( self, model: str = "mistral-medium-latest", api_key: Optional[str] = None, **kwargs, ...
raw_kwargs = kwargs kwargs = { **self.kwargs, "messages": [ChatMessage(role="user", content=prompt)], **kwargs, } # Mistral disallows "n" arguments n = kwargs.pop("n", None) if n is not None and n > 1 and kwargs['temperature'] == 0.0: ...
"""Basic request to Mistral AI's API.""" raw_kwargs = kwargs kwargs = { **self.kwargs, "messages": [ChatMessage(role="user", content=prompt)], **kwargs, } # Mistral disallows "n" arguments n = kwargs.pop("n", None) if n is not ...
55
672
212
884
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
from typing import Any, Optional import backoff from dsp.modules.lm import LM try: import mistralai from mistralai.client import MistralClient from mistralai.exceptions import MistralAPIException from mistralai.models.chat_completion import ChatCompletionResponse, ChatMessage mistralai_api_error ...
24,772
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/ollama.py
77,78
19,195
basic_request
OllamaLocal
78,140
78,140
class OllamaLocal(LM): """Wrapper around a locally hosted Ollama model (API: https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values and https://github.com/jmorganca/ollama/blob/main/docs/api.md#generate-a-completion). Returns dictionary info in the OpenAI API style (https://...
class OllamaLocal(LM): """Wrapper around a locally hosted Ollama model (API: https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values and https://github.com/jmorganca/ollama/blob/main/docs/api.md#generate-a-completion). Returns dictionary info in the OpenAI API style (https://...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} request_info = post_request_metadata(self.model_name, prompt) request_info["choices"] = [] settings_dict = { "model": self.model_name, "options": {k: v for k, v in kwargs.items() if k not in ["n", "m...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} request_info = post_request_metadata(self.model_name, prompt) request_info["choices"] = [] settings_dict = { "model": self.model_name, "options": {k: v for k, v in kwargs.items() if k not in ["n", "m...
177
1,282
735
2,017
import datetime import hashlib from typing import Any, Literal import requests from dsp.modules.lm import LM def post_request_metadata(model_name, prompt): """Creates a serialized request object for the Ollama API.""" timestamp = datetime.datetime.now().timestamp() id_string = str(timestamp) + model_nam...
import datetime import hashlib from typing import Any, Literal import requests from dsp.modules.lm import LM def post_request_metadata(model_name, prompt): """Creates a serialized request object for the Ollama API.""" timestamp = datetime.datetime.now().timestamp() id_string = str(timestamp) + model_nam...
24,773
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/modules/watsonx.py
74,75
15,133
basic_request
Watsonx
75,90
75,90
class Watsonx(LM): """Wrapper around Watsonx AI's API. The constructor initializes the base class LM to support prompting requests to Watsonx models. This requires the following parameters: Args: model (str): the type of model to use from IBM Watsonx AI. credentials ([dict]): credential...
class Watsonx(LM): """Wrapper around Watsonx AI's API. The constructor initializes the base class LM to support prompting requests to Watsonx models. This requires the following parameters: Args: model (str): the type of model to use from IBM Watsonx AI. credentials ([dict]): credential...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} response = self.client.generate(prompt, params={**kwargs}) history = { "prompt": prompt, "response": response, "kwargs": kwargs, "raw_kwargs": raw_kwargs, } self.histo...
raw_kwargs = kwargs kwargs = {**self.kwargs, **kwargs} response = self.client.generate(prompt, params={**kwargs}) history = { "prompt": prompt, "response": response, "kwargs": kwargs, "raw_kwargs": raw_kwargs, } self.histo...
26
1,066
119
1,185
from typing import Any from dsp.modules.lm import LM ibm_watsonx_ai_api_error = False try: import ibm_watsonx_ai # noqa: F401 from ibm_watsonx_ai.foundation_models import Model # type: ignore except ImportError: ibm_watsonx_ai_api_error = Exception class Watsonx(LM): """Wrapper around Watsonx AI...
from typing import Any from dsp.modules.lm import LM ibm_watsonx_ai_api_error = False try: import ibm_watsonx_ai # noqa: F401 from ibm_watsonx_ai.foundation_models import Model # type: ignore except ImportError: ibm_watsonx_ai_api_error = Exception class Watsonx(LM): """Wrapper around Watsonx AI...
24,774
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/primitives/demonstrate.py
48,49
1,186
annotate
50,82
49,82
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
def do_augment(train, k=None, return_all=False): rdemos = [] ademos = [] for example in train: # tqdm.tqdm raw_example = dsp.Example(example) if (k is not None) and len(ademos) >= k: example = None for f in transformations: ...
"""Returns an Augment function that applies the provided transformations to the Examples""" def do_augment(train, k=None, return_all=False): rdemos = [] ademos = [] for example in train: # tqdm.tqdm raw_example = dsp.Example(example) if (k is not None) and len...
67
1,583
234
1,817
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
24,775
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/primitives/demonstrate.py
30,31
10,48
without
Example
32,35
31,35
class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): assert len(args) <= 1 super().__init__() if args: assert len(args) == 1 self.update(args[0]) self.update(**kwargs) ...
class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): assert len(args) <= 1 super().__init__() if args: assert len(args) == 1 self.update(args[0]) self.update(**kwargs) ...
keys = set(keys) return Example({k: v for k, v in self.items() if k not in keys})
"""Removes the provided keys from the example and returns a copy""" keys = set(keys) return Example({k: v for k, v in self.items() if k not in keys})
16
275
35
310
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
import random from typing import Any, Callable import numpy as np import dsp from dsp.utils import EM, F1, DPR_normalize, dotdict, has_answer, normalize_text class Example(dotdict): """A primitive datatype for representing an example""" demos: list[Any] def __init__(self, *args, **kwargs): ass...
24,776
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/primitives/inspect.py
22,23
9,92
inspect_func
FuncInspector
23,38
23,38
class FuncInspector: def __init__(self): self.calls = [] def inspect_inner(self, func, function_calls): def wrapper(*args, **kwargs): result = func(*args, **kwargs) self.merge_result(result, function_calls) return result return wrapper def inspect_func(self, func): FILL_FUNC_BODY...
class FuncInspector: def __init__(self): self.calls = [] def inspect_inner(self, func, function_calls): def wrapper(*args, **kwargs): result = func(*args, **kwargs) self.merge_result(result, function_calls) return result return wrapper def inspect_func(self, func): FILL_FUNC_BODY...
def wrapper(*args, **kwargs): result = func(*args, **kwargs) stack = inspect.stack() function_calls = [] for i in range(len(stack)): if stack[i][3] == "<module>": break if stack[i][3] != "wrapper": function_calls.append(stack[i][3]) function_calls.re...
def wrapper(*args, **kwargs): result = func(*args, **kwargs) stack = inspect.stack() function_calls = [] for i in range(len(stack)): if stack[i][3] == "<module>": break if stack[i][3] != "wrapper": function_calls.append(stack[i][3]) function_calls.re...
36
700
151
851
import inspect import json import random import string import requests class FuncInspector: def __init__(self): self.calls = [] def inspect_inner(self, func, function_calls): def wrapper(*args, **kwargs): result = func(*args, **kwargs) self.merge_result(result, function_calls) return ...
import inspect import json import random import string import requests class FuncInspector: def __init__(self): self.calls = [] def inspect_inner(self, func, function_calls): def wrapper(*args, **kwargs): result = func(*args, **kwargs) self.merge_result(result, function_calls) return ...
24,777
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/primitives/primitives.py
15,16
1,47
shallow_copy_example_args
16,24
16,24
from functools import wraps import dsp # applied right to left (innermost first, like function calls) def compose_decorators(*decorators): def decorator(func): for decorator in decorators[::-1]: func = decorator(func) return func return decorator def shallow_copy_example_args(fu...
from functools import wraps import dsp # applied right to left (innermost first, like function calls) def compose_decorators(*decorators): def decorator(func): for decorator in decorators[::-1]: func = decorator(func) return func return decorator def shallow_copy_example_args(fu...
@wraps(func) def wrapper(*args, **kwargs): args = [dsp.Example(arg) if isinstance(arg, dsp.Example) else arg for arg in args] kwargs = {key: dsp.Example(value) if isinstance(value, dsp.Example) else value for key, value in kwargs.items()} return func(*args, **kwargs) return wrapper ...
@wraps(func) def wrapper(*args, **kwargs): args = [dsp.Example(arg) if isinstance(arg, dsp.Example) else arg for arg in args] kwargs = {key: dsp.Example(value) if isinstance(value, dsp.Example) else value for key, value in kwargs.items()} return func(*args, **kwargs) return wrapper ...
35
340
113
453
from functools import wraps import dsp # applied right to left (innermost first, like function calls) def compose_decorators(*decorators): def decorator(func): for decorator in decorators[::-1]: func = decorator(func) return func return decorator def shallow_copy_example_args(fu...
from functools import wraps import dsp # applied right to left (innermost first, like function calls) def compose_decorators(*decorators): def decorator(func): for decorator in decorators[::-1]: func = decorator(func) return func return decorator def shallow_copy_example_args(fu...
24,778
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/primitives/search.py
27,28
1,72
retrieveRerankEnsemble
28,45
28,45
from collections.abc import Iterable import numpy as np import dsp def retrieve(query: str, k: int, **kwargs) -> list[str]: """Retrieves passages from the RM for the query and returns the top k passages.""" if not dsp.settings.rm: raise AssertionError("No RM is loaded.") passages = dsp.settings....
from collections.abc import Iterable import numpy as np import dsp def retrieve(query: str, k: int, **kwargs) -> list[str]: """Retrieves passages from the RM for the query and returns the top k passages.""" if not dsp.settings.rm: raise AssertionError("No RM is loaded.") passages = dsp.settings....
if not (dsp.settings.rm and dsp.settings.reranker): raise AssertionError("Both RM and Reranker are needed to retrieve & re-rank.") queries = [q for q in queries if q] passages = {} for query in queries: retrieved_passages = dsp.settings.rm(query, k=k*3,**kwargs) passages_cs_score...
if not (dsp.settings.rm and dsp.settings.reranker): raise AssertionError("Both RM and Reranker are needed to retrieve & re-rank.") queries = [q for q in queries if q] passages = {} for query in queries: retrieved_passages = dsp.settings.rm(query, k=k*3,**kwargs) passages_cs_score...
76
649
275
924
from collections.abc import Iterable import numpy as np import dsp def retrieve(query: str, k: int, **kwargs) -> list[str]: """Retrieves passages from the RM for the query and returns the top k passages.""" if not dsp.settings.rm: raise AssertionError("No RM is loaded.") passages = dsp.settings....
from collections.abc import Iterable import numpy as np import dsp def retrieve(query: str, k: int, **kwargs) -> list[str]: """Retrieves passages from the RM for the query and returns the top k passages.""" if not dsp.settings.rm: raise AssertionError("No RM is loaded.") passages = dsp.settings....
24,779
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/templates/utils.py
20,21
1,67
passages2textV2
22,45
21,45
from typing import Optional, Union def passages2text(passages: Union[str, list, tuple]) -> str: """Formats the given one or more passages into a single structured string.""" if isinstance(passages, str): return passages assert type(passages) in [list, tuple] if len(passages) == 0: re...
from typing import Optional, Union def passages2text(passages: Union[str, list, tuple]) -> str: """Formats the given one or more passages into a single structured string.""" if isinstance(passages, str): return passages assert type(passages) in [list, tuple] if len(passages) == 0: re...
if isinstance(passages, str): return passages assert type(passages) in [list, tuple] def psg2text(psg): try: title, snippet = psg.split("|", 1) return f"Title: {title.strip()} | Snippet: «{snippet.strip()}»" except Exception: pass ...
"""Formats the given one or more passages into a single structured string.""" if isinstance(passages, str): return passages assert type(passages) in [list, tuple] def psg2text(psg): try: title, snippet = psg.split("|", 1) return f"Title: {title.strip()} | Snippe...
49
428
223
651
from typing import Optional, Union def passages2text(passages: Union[str, list, tuple]) -> str: """Formats the given one or more passages into a single structured string.""" if isinstance(passages, str): return passages assert type(passages) in [list, tuple] if len(passages) == 0: re...
from typing import Optional, Union def passages2text(passages: Union[str, list, tuple]) -> str: """Formats the given one or more passages into a single structured string.""" if isinstance(passages, str): return passages assert type(passages) in [list, tuple] if len(passages) == 0: re...
24,780
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/utils/ann_utils.py
81,90
1,133
create_faiss_index
111,133
90,133
from typing import Tuple try: import faiss from faiss import Index except ImportError: raise ImportError( "You need to install FAISS library to perform ANN/KNN. Please check the official doc: " "https://github.com/facebookresearch/faiss/blob/main/INSTALL.md", ) def determine_devices(m...
from typing import Tuple try: import faiss from faiss import Index except ImportError: raise ImportError( "You need to install FAISS library to perform ANN/KNN. Please check the official doc: " "https://github.com/facebookresearch/faiss/blob/main/INSTALL.md", ) def determine_devices(m...
if n_objects < 20_000: # if less than 20_000 / (4 * sqrt(20_000)) ~= 35 points per cluster - make bruteforce # https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index#if-below-1m-vectors-ivfk index = _get_brute_index(emb_dim=emb_dim, dist_type=in_list_dist_type) else...
""" Create IVF index (with IP or L2 dist), without adding data and training Args: emb_dim: size of each embedding n_objects: size of a trainset for index. Used to determine optimal type of index and its settings (will use bruteforce if `n_objects` is less than 20_000). n_...
67
1,314
357
1,671
from typing import Tuple try: import faiss from faiss import Index except ImportError: raise ImportError( "You need to install FAISS library to perform ANN/KNN. Please check the official doc: " "https://github.com/facebookresearch/faiss/blob/main/INSTALL.md", ) def determine_devices(m...
from typing import Tuple try: import faiss from faiss import Index except ImportError: raise ImportError( "You need to install FAISS library to perform ANN/KNN. Please check the official doc: " "https://github.com/facebookresearch/faiss/blob/main/INSTALL.md", ) def determine_devices(m...
24,782
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/utils/settings_v2.py
68,69
1,83
main
69,81
69,81
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
parent_tid = threading.get_ident() with dsp_settings.context(a=10, b=20): # Setting main thread's context with ThreadPoolExecutor(max_workers=2) as executor: futures = {executor.submit(thread_wrapper, sample_program, parent_tid, arg) for arg in range(3)} for future in as_compl...
parent_tid = threading.get_ident() with dsp_settings.context(a=10, b=20): # Setting main thread's context with ThreadPoolExecutor(max_workers=2) as executor: futures = {executor.submit(thread_wrapper, sample_program, parent_tid, arg) for arg in range(3)} for future in as_compl...
39
660
164
824
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
24,783
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dsp/utils/settings_v2.py
30,32
7,54
context
Settings
32,54
32,54
class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to hold parent thread configurations self._parent_configs = {} # Using thread-local storage to ensure that each ...
class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to hold parent thread configurations self._parent_configs = {} # Using thread-local storage to ensure that each ...
current_config = copy.deepcopy(self._get_current_config()) # Deep copy the current configuration current_config.update(kwargs) if not hasattr(self._local, 'config_stack'): self._local.config_stack = [] self._local.config_stack.append(current_config) ...
current_config = copy.deepcopy(self._get_current_config()) # Deep copy the current configuration current_config.update(kwargs) if not hasattr(self._local, 'config_stack'): self._local.config_stack = [] self._local.config_stack.append(current_config) ...
56
277
230
507
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
import copy import threading from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager class Settings: def __init__(self): # A lock for ensuring thread-safety when accessing _parent_configs self._lock = threading.Lock() # Dictionary to h...
24,784
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/datasets/colors.py
24,25
8,34
sorted_by_suffix
Colors
25,34
25,34
class Colors(Dataset): def __init__(self, sort_by_suffix=True, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.sort_by_suffix = sort_by_suffix colors = self.sorted_by_suffix(all_colors) train_size = int(len(colors) * 0.6) # chosen to ensure that similar colors aren...
class Colors(Dataset): def __init__(self, sort_by_suffix=True, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.sort_by_suffix = sort_by_suffix colors = self.sorted_by_suffix(all_colors) train_size = int(len(colors) * 0.6) # chosen to ensure that similar colors aren...
if not self.sort_by_suffix: return colors if isinstance(colors[0], str): sorted_colors = sorted(colors, key=lambda x: x[::-1]) else: sorted_colors = sorted(colors, key=lambda x: x['color'][::-1]) return sorted_colors
if not self.sort_by_suffix: return colors if isinstance(colors[0], str): sorted_colors = sorted(colors, key=lambda x: x[::-1]) else: sorted_colors = sorted(colors, key=lambda x: x['color'][::-1]) return sorted_colors
23
244
101
345
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 blue', 'cadet blue', 'cornflower blue', 'medi...
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 blue', 'cadet blue', 'cornflower blue', 'medi...
24,785
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/datasets/dataloader.py
15,23
11,121
from_huggingface
DataLoader
23,49
23,49
class DataLoader(Dataset): def __init__(self,): pass def from_huggingface( self, dataset_name: str, *args, input_keys: Tuple[str] = (), fields: Tuple[str] = None, **kwargs, ) -> Union[Mapping[str, List[dspy.Example]], List[dspy.Example]]: FILL_FUNC_BO...
class DataLoader(Dataset): def __init__(self,): pass def from_huggingface( self, dataset_name: str, *args, input_keys: Tuple[str] = (), fields: Tuple[str] = None, **kwargs, ) -> Union[Mapping[str, List[dspy.Example]], List[dspy.Example]]: FILL_FUNC_BO...
if fields and not isinstance(fields, tuple): raise ValueError("Invalid fields provided. Please provide a tuple of fields.") if not isinstance(input_keys, tuple): raise ValueError("Invalid input keys provided. Please provide a tuple of input keys.") dataset = load_datase...
if fields and not isinstance(fields, tuple): raise ValueError("Invalid fields provided. Please provide a tuple of fields.") if not isinstance(input_keys, tuple): raise ValueError("Invalid input keys provided. Please provide a tuple of input keys.") dataset = load_datase...
111
1,059
384
1,443
import random from collections.abc import Mapping from typing import List, Tuple, Union from datasets import load_dataset import dspy from dspy.datasets.dataset import Dataset class DataLoader(Dataset): def __init__(self,): pass def from_huggingface( self, dataset_name: str, ...
import random from collections.abc import Mapping from typing import List, Tuple, Union from datasets import load_dataset import dspy from dspy.datasets.dataset import Dataset class DataLoader(Dataset): def __init__(self,): pass def from_huggingface( self, dataset_name: str, ...
24,786
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/datasets/dataset.py
88,91
8,115
prepare_by_seed
Dataset
91,115
91,115
class Dataset: def __init__(self, train_seed=0, train_size=None, eval_seed=0, dev_size=None, test_size=None): self.train_size = train_size self.train_seed = train_seed self.dev_size = dev_size self.dev_seed = eval_seed self.test_size = test_size self.test_seed = eval_...
class Dataset: def __init__(self, train_seed=0, train_size=None, eval_seed=0, dev_size=None, test_size=None): self.train_size = train_size self.train_seed = train_seed self.dev_size = dev_size self.dev_seed = eval_seed self.test_size = test_size self.test_seed = eval_...
data_args = dotdict(train_size=train_size, eval_seed=eval_seed, dev_size=dev_size, test_size=0, **kwargs) dataset = cls(**data_args) eval_set = dataset.dev eval_sets, train_sets = [], [] examples_per_seed = dev_size // len(train_seeds) if divide_eval_per_seed else dev_...
data_args = dotdict(train_size=train_size, eval_seed=eval_seed, dev_size=dev_size, test_size=0, **kwargs) dataset = cls(**data_args) eval_set = dataset.dev eval_sets, train_sets = [], [] examples_per_seed = dev_size // len(train_seeds) if divide_eval_per_seed else dev_...
58
1,001
325
1,326
import random import uuid from dsp.utils import dotdict from dspy import Example class Dataset: def __init__(self, train_seed=0, train_size=None, eval_seed=0, dev_size=None, test_size=None): self.train_size = train_size self.train_seed = train_seed self.dev_size = dev_size self.de...
import random import uuid from dsp.utils import dotdict from dspy import Example class Dataset: def __init__(self, train_seed=0, train_size=None, eval_seed=0, dev_size=None, test_size=None): self.train_size = train_size self.train_seed = train_seed self.dev_size = dev_size self.de...
24,787
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/evaluate/auto_evaluation.py
17,18
12,21
forward
AnswerCorrectness
18,21
18,21
class AnswerCorrectness(dspy.Module): def __init__(self): super().__init__() self.evaluate_correctness = dspy.ChainOfThought(AnswerCorrectnessSignature) def forward(self, question, gold_answer, predicted_answer): FILL_FUNC_BODY
class AnswerCorrectness(dspy.Module): def __init__(self): super().__init__() self.evaluate_correctness = dspy.ChainOfThought(AnswerCorrectnessSignature) def forward(self, question, gold_answer, predicted_answer): FILL_FUNC_BODY
return self.evaluate_correctness(question=question, gold_answer=gold_answer, predicted_answer=predicted_answer)
return self.evaluate_correctness(question=question, gold_answer=gold_answer, predicted_answer=predicted_answer)
4
85
37
122
import dspy class AnswerCorrectnessSignature(dspy.Signature): """Verify that the predicted answer matches the gold answer.""" question = dspy.InputField() gold_answer = dspy.InputField(desc="correct answer for question") predicted_answer = dspy.InputField(desc="predicted answer for question") is_...
import dspy class AnswerCorrectnessSignature(dspy.Signature): """Verify that the predicted answer matches the gold answer.""" question = dspy.InputField() gold_answer = dspy.InputField(desc="correct answer for question") predicted_answer = dspy.InputField(desc="predicted answer for question") is_...
24,788
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/evaluate/auto_evaluation.py
34,35
29,36
forward
AnswerFaithfulness
35,36
35,36
class AnswerFaithfulness(dspy.Module): def __init__(self): super().__init__() self.evaluate_faithfulness = dspy.ChainOfThought(AnswerFaithfulnessSignature) def forward(self, context, question, answer): FILL_FUNC_BODY
class AnswerFaithfulness(dspy.Module): def __init__(self): super().__init__() self.evaluate_faithfulness = dspy.ChainOfThought(AnswerFaithfulnessSignature) def forward(self, context, question, answer): FILL_FUNC_BODY
return self.evaluate_faithfulness(context=context, question=question, answer=answer)
return self.evaluate_faithfulness(context=context, question=question, answer=answer)
4
84
25
109
import dspy class AnswerCorrectnessSignature(dspy.Signature): """Verify that the predicted answer matches the gold answer.""" question = dspy.InputField() gold_answer = dspy.InputField(desc="correct answer for question") predicted_answer = dspy.InputField(desc="predicted answer for question") is_...
import dspy class AnswerCorrectnessSignature(dspy.Signature): """Verify that the predicted answer matches the gold answer.""" question = dspy.InputField() gold_answer = dspy.InputField(desc="correct answer for question") predicted_answer = dspy.InputField(desc="predicted answer for question") is_...
24,789
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/evaluate/metrics.py
6,7
1,23
answer_exact_match
7,14
7,14
# TODO: This should move internally. Same for passage_match. dspy.metrics.answer_exact_match, dspy.metrics.answer_passage_match import dsp def answer_exact_match(example, pred, trace=None, frac=1.0): FILL_FUNC_BODYanswer_exact_match_str = dsp.answer_match def answer_passage_match(example, pred, trace=None): ass...
# TODO: This should move internally. Same for passage_match. dspy.metrics.answer_exact_match, dspy.metrics.answer_passage_match import dsp def answer_exact_match(example, pred, trace=None, frac=1.0): FILL_FUNC_BODYanswer_exact_match_str = dsp.answer_match def answer_passage_match(example, pred, trace=None): ass...
assert(type(example.answer) is str or type(example.answer) is list) if type(example.answer) is str: return dsp.answer_match(pred.answer, [example.answer], frac=frac) else: # type(example.answer) is list return dsp.answer_match(pred.answer, example.answer, frac=frac)
assert(type(example.answer) is str or type(example.answer) is list) if type(example.answer) is str: return dsp.answer_match(pred.answer, [example.answer], frac=frac) else: # type(example.answer) is list return dsp.answer_match(pred.answer, example.answer, frac=frac)
24
203
104
307
# TODO: This should move internally. Same for passage_match. dspy.metrics.answer_exact_match, dspy.metrics.answer_passage_match import dsp def answer_exact_match(example, pred, trace=None, frac=1.0): FILL_FUNC_BODYanswer_exact_match_str = dsp.answer_match def answer_passage_match(example, pred, trace=None): ass...
# TODO: This should move internally. Same for passage_match. dspy.metrics.answer_exact_match, dspy.metrics.answer_passage_match import dsp def answer_exact_match(example, pred, trace=None, frac=1.0): FILL_FUNC_BODYanswer_exact_match_str = dsp.answer_match def answer_passage_match(example, pred, trace=None): ass...
24,790
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/experimental/synthesizer/config.py
16,18
6,25
validate_feedback_mode
SynthesizerArguments
18,25
18,25
class SynthesizerArguments(BaseModel): feedback_mode: Optional[str] = None num_example_for_feedback: Optional[int] = None input_lm_model: Optional[Any] = None output_lm_model: Optional[Any] = None output_teacher_module: Optional[Any] = None num_example_for_optim: Optional[int] = None @mod...
class SynthesizerArguments(BaseModel): feedback_mode: Optional[str] = None num_example_for_feedback: Optional[int] = None input_lm_model: Optional[Any] = None output_lm_model: Optional[Any] = None output_teacher_module: Optional[Any] = None num_example_for_optim: Optional[int] = None @mod...
if self.feedback_mode and self.feedback_mode not in ["human", "llm"]: raise ValueError("Feedback mode should be either 'human' or 'llm'.") if self.feedback_mode and not self.num_example_for_feedback: raise ValueError("Number of examples for feedback is required when feed...
if self.feedback_mode and self.feedback_mode not in ["human", "llm"]: raise ValueError("Feedback mode should be either 'human' or 'llm'.") if self.feedback_mode and not self.num_example_for_feedback: raise ValueError("Number of examples for feedback is required when feed...
37
137
101
238
from typing import Any, Optional from pydantic import BaseModel, model_validator class SynthesizerArguments(BaseModel): feedback_mode: Optional[str] = None num_example_for_feedback: Optional[int] = None input_lm_model: Optional[Any] = None output_lm_model: Optional[Any] = None output_teacher_mod...
from typing import Any, Optional from pydantic import BaseModel, model_validator class SynthesizerArguments(BaseModel): feedback_mode: Optional[str] = None num_example_for_feedback: Optional[int] = None input_lm_model: Optional[Any] = None output_lm_model: Optional[Any] = None output_teacher_mod...
24,791
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/experimental/synthesizer/utils.py
6,7
1,25
format_examples
7,25
7,25
from typing import List import dspy def format_examples(examples: List[dspy.Example]) -> str: FILL_FUNC_BODY
from typing import List import dspy def format_examples(examples: List[dspy.Example]) -> str: FILL_FUNC_BODY
if isinstance(examples, str): return examples formatted_example = "" for example in examples: input_keys = example.inputs().keys() label_keys = example.labels().keys() formatted_example += "Inputs:\n" for key in input_keys: formatted_example += f"{key}:...
if isinstance(examples, str): return examples formatted_example = "" for example in examples: input_keys = example.inputs().keys() label_keys = example.labels().keys() formatted_example += "Inputs:\n" for key in input_keys: formatted_example += f"{key}:...
42
43
161
204
from typing import List import dspy def format_examples(examples: List[dspy.Example]) -> str: FILL_FUNC_BODY
from typing import List import dspy def format_examples(examples: List[dspy.Example]) -> str: FILL_FUNC_BODY
24,792
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/experimental/synthetic_data.py
81,82
16,98
_prepare_fields
SyntheticDataGenerator
83,98
82,98
class SyntheticDataGenerator: def __init__(self, schema_class: Optional[BaseModel] = None, examples: Optional[List[dspy.Example]] = None): self.schema_class = schema_class self.examples = examples def generate(self, sample_size: int) -> List[dspy.Example]: """Generate synthetic examples...
class SyntheticDataGenerator: def __init__(self, schema_class: Optional[BaseModel] = None, examples: Optional[List[dspy.Example]] = None): self.schema_class = schema_class self.examples = examples def generate(self, sample_size: int) -> List[dspy.Example]: """Generate synthetic examples...
return { '__doc__': f"Generates the following outputs: {{{', '.join(properties.keys())}}}.", 'sindex': dspy.InputField(desc="a random string"), **{field_name: dspy.OutputField(desc=properties[field_name].get('description', 'No description')) for field_name in p...
"""Prepare fields to generate in an appropriate format.""" return { '__doc__': f"Generates the following outputs: {{{', '.join(properties.keys())}}}.", 'sindex': dspy.InputField(desc="a random string"), **{field_name: dspy.OutputField(desc=properties[field_name].get('...
59
835
208
1,043
import logging import random from typing import List, Optional from pydantic import BaseModel import dspy class DescriptionSignature(dspy.Signature): field_name = dspy.InputField(desc="name of a field") example = dspy.InputField(desc="an example value for the field") description = dspy.OutputField(desc=...
import logging import random from typing import List, Optional from pydantic import BaseModel import dspy class DescriptionSignature(dspy.Signature): field_name = dspy.InputField(desc="name of a field") example = dspy.InputField(desc="an example value for the field") description = dspy.OutputField(desc=...
24,793
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/aggregation.py
7,8
1,55
majority
13,55
8,55
from dsp.utils import normalize_text from dspy.primitives.prediction import Completions, Prediction default_normalize = lambda s: normalize_text(s) or None def majority(prediction_or_completions, normalize=default_normalize, field=None): FILL_FUNC_BODY
from dsp.utils import normalize_text from dspy.primitives.prediction import Completions, Prediction default_normalize = lambda s: normalize_text(s) or None def majority(prediction_or_completions, normalize=default_normalize, field=None): """ Returns the most common completion for the target field (or the...
assert any(isinstance(prediction_or_completions, t) for t in [Prediction, Completions, list]) input_type = type(prediction_or_completions) # Get the completions if isinstance(prediction_or_completions, Prediction): completions = prediction_or_completions.completions else: completio...
""" Returns the most common completion for the target field (or the last field) in the signature. When normalize returns None, that completion is ignored. In case of a tie, earlier completion are prioritized. """ assert any(isinstance(prediction_or_completions, t) for t in [Predicti...
126
141
436
577
from dsp.utils import normalize_text from dspy.primitives.prediction import Completions, Prediction default_normalize = lambda s: normalize_text(s) or None def majority(prediction_or_completions, normalize=default_normalize, field=None): FILL_FUNC_BODY
from dsp.utils import normalize_text from dspy.primitives.prediction import Completions, Prediction default_normalize = lambda s: normalize_text(s) or None def majority(prediction_or_completions, normalize=default_normalize, field=None): """ Returns the most common completion for the target field (or the...
24,794
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/chain_of_thought.py
73,74
31,86
load_state
ChainOfThought
74,86
74,86
class ChainOfThought(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(signature, **config) self.activated = activated signature = ensure_signature(self.signature) *_keys, last_key = signature.output_fields.keys() rati...
class ChainOfThought(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(signature, **config) self.activated = activated signature = ensure_signature(self.signature) *_keys, last_key = signature.output_fields.keys() rati...
super().load_state(state) # Reconstruct the signature. if "extended_signature_instructions" in state: instructions = state["extended_signature_instructions"] self.extended_signature = self.extended_signature.with_instructions(instructions) if...
super().load_state(state) # Reconstruct the signature. if "extended_signature_instructions" in state: instructions = state["extended_signature_instructions"] self.extended_signature = self.extended_signature.with_instructions(instructions) if...
30
465
163
628
import dsp import dspy from dspy.signatures.signature import ensure_signature from .predict import Predict # TODO: FIXME: Insert this right before the *first* output field. Also rewrite this to use the new signature system. # TODO: This shouldn't inherit from Predict. It should be a module that has one or two predic...
import dsp import dspy from dspy.signatures.signature import ensure_signature from .predict import Predict # TODO: FIXME: Insert this right before the *first* output field. Also rewrite this to use the new signature system. # TODO: This shouldn't inherit from Predict. It should be a module that has one or two predic...
24,795
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/chain_of_thought_with_hint.py
24,25
8,36
forward
ChainOfThoughtWithHint
25,36
25,36
class ChainOfThoughtWithHint(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(signature, **config) self.activated = activated signature = self.signature *keys, last_key = signature.fields.keys() rationale_type = rationa...
class ChainOfThoughtWithHint(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(signature, **config) self.activated = activated signature = self.signature *keys, last_key = signature.fields.keys() rationale_type = rationa...
signature = self.signature if self.activated is True or (self.activated is None and isinstance(dsp.settings.lm, dsp.GPT3)): if 'hint' in kwargs and kwargs['hint']: signature = self.extended_signature2 else: signature = self.extended_signature1 ...
signature = self.signature if self.activated is True or (self.activated is None and isinstance(dsp.settings.lm, dsp.GPT3)): if 'hint' in kwargs and kwargs['hint']: signature = self.extended_signature2 else: signature = self.extended_signature1 ...
30
256
119
375
import dsp import dspy from .predict import Predict # TODO: FIXME: Insert this right before the *first* output field. Also rewrite this to use the new signature system. class ChainOfThoughtWithHint(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(si...
import dsp import dspy from .predict import Predict # TODO: FIXME: Insert this right before the *first* output field. Also rewrite this to use the new signature system. class ChainOfThoughtWithHint(Predict): def __init__(self, signature, rationale_type=None, activated=True, **config): super().__init__(si...
24,796
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/multi_chain_comparison.py
35,36
8,55
forward
MultiChainComparison
36,55
36,55
class MultiChainComparison(Module): def __init__(self, signature, M=3, temperature=0.7, **config): super().__init__() self.M = M signature = ensure_signature(signature) *_, self.last_key = signature.output_fields.keys() for idx in range(M): signature = signatur...
class MultiChainComparison(Module): def __init__(self, signature, M=3, temperature=0.7, **config): super().__init__() self.M = M signature = ensure_signature(signature) *_, self.last_key = signature.output_fields.keys() for idx in range(M): signature = signatur...
attempts = [] for c in completions: rationale = c.rationale.strip().split("\n")[0].strip() answer = c[self.last_key].strip().split("\n")[0].strip() attempts.append( f"«I'm trying to {rationale} I'm not sure but my prediction is {answer}»", ...
attempts = [] for c in completions: rationale = c.rationale.strip().split("\n")[0].strip() answer = c[self.last_key].strip().split("\n")[0].strip() attempts.append( f"«I'm trying to {rationale} I'm not sure but my prediction is {answer}»", ...
48
261
199
460
import dspy from dspy.signatures.signature import ensure_signature from ..primitives.program import Module from .predict import Predict class MultiChainComparison(Module): def __init__(self, signature, M=3, temperature=0.7, **config): super().__init__() self.M = M signature = ensure_sign...
import dspy from dspy.signatures.signature import ensure_signature from ..primitives.program import Module from .predict import Predict class MultiChainComparison(Module): def __init__(self, signature, M=3, temperature=0.7, **config): super().__init__() self.M = M signature = ensure_sign...
24,797
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/predict.py
63,64
11,146
forward
Predict
64,131
64,131
class Predict(Parameter): def __init__(self, signature, **config): self.stage = random.randbytes(8).hex() self.signature = ensure_signature(signature) self.config = config self.reset() def reset(self): self.lm = None self.traces = [] self.train = [] ...
class Predict(Parameter): def __init__(self, signature, **config): self.stage = random.randbytes(8).hex() self.signature = ensure_signature(signature) self.config = config self.reset() def reset(self): self.lm = None self.traces = [] self.train = [] ...
# Extract the three privileged keyword arguments. new_signature = ensure_signature(kwargs.pop("new_signature", None)) signature = ensure_signature(kwargs.pop("signature", self.signature)) demos = kwargs.pop("demos", self.demos) config = dict(**self.config, **kwargs.pop("config", ...
# Extract the three privileged keyword arguments. new_signature = ensure_signature(kwargs.pop("new_signature", None)) signature = ensure_signature(kwargs.pop("signature", self.signature)) demos = kwargs.pop("demos", self.demos) config = dict(**self.config, **kwargs.pop("config", ...
319
665
899
1,564
import random from pydantic import BaseModel import dsp from dspy.predict.parameter import Parameter from dspy.primitives.prediction import Prediction from dspy.signatures.signature import ensure_signature, signature_to_template class Predict(Parameter): def __init__(self, signature, **config): self.sta...
import random from pydantic import BaseModel import dsp from dspy.predict.parameter import Parameter from dspy.primitives.prediction import Prediction from dspy.signatures.signature import ensure_signature, signature_to_template class Predict(Parameter): def __init__(self, signature, **config): self.sta...
24,798
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/predict/retry.py
34,35
9,75
forward
Retry
35,52
35,52
class Retry(Predict): def __init__(self, module): super().__init__(module.signature) self.module = module self.original_signature = module.signature self.original_forward = module.forward self.new_signature = self._create_new_signature(self.original_signature) def _creat...
class Retry(Predict): def __init__(self, module): super().__init__(module.signature) self.module = module self.original_signature = module.signature self.original_forward = module.forward self.new_signature = self._create_new_signature(self.original_signature) def _creat...
# Take into account the possible new signature, as in TypedPredictor new_signature = kwargs.pop("new_signature", None) if new_signature: self.original_signature = new_signature self.new_signature = self._create_new_signature(self.original_signature) # Convert the...
# Take into account the possible new signature, as in TypedPredictor new_signature = kwargs.pop("new_signature", None) if new_signature: self.original_signature = new_signature self.new_signature = self._create_new_signature(self.original_signature) # Convert the...
78
550
246
796
import copy import dsp import dspy from .predict import Predict class Retry(Predict): def __init__(self, module): super().__init__(module.signature) self.module = module self.original_signature = module.signature self.original_forward = module.forward self.new_signature =...
import copy import dsp import dspy from .predict import Predict class Retry(Predict): def __init__(self, module): super().__init__(module.signature) self.module = module self.original_signature = module.signature self.original_forward = module.forward self.new_signature =...
24,799
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/box.py
114,115
92,131
method
BoxType
115,123
115,123
class BoxType(type): # List of operations to override ops = [ # Arithmetic operations 'add', 'sub', 'mul', 'truediv', 'floordiv', 'mod', 'pow', 'lshift', 'rshift', 'and', 'or', 'xor', # 'r'-prefixed versions of arithmetic operations 'radd', 'rsub', 'rmul', 'rtruediv', 'r...
class BoxType(type): # List of operations to override ops = [ # Arithmetic operations 'add', 'sub', 'mul', 'truediv', 'floordiv', 'mod', 'pow', 'lshift', 'rshift', 'and', 'or', 'xor', # 'r'-prefixed versions of arithmetic operations 'radd', 'rsub', 'rmul', 'rtruediv', 'r...
if op in ['len', 'keys', 'values', 'items']: return getattr(self._value, op)() elif isinstance(other, Box): return Box(getattr(self._value, f'__{op}__')(other._value)) elif other is not None: return Box(getattr(s...
if op in ['len', 'keys', 'values', 'items']: return getattr(self._value, op)() elif isinstance(other, Box): return Box(getattr(self._value, f'__{op}__')(other._value)) elif other is not None: return Box(getattr(s...
27
368
114
482
""" TODO: If we want to have Prediction::{**keys, completions, box} where box.{key} will behave as a value but also include the completions internally. The main thing left is to determine the semantic (and then implement them) for applying operations on the object. If we have a string (query) and completions (5 quer...
""" TODO: If we want to have Prediction::{**keys, completions, box} where box.{key} will behave as a value but also include the completions internally. The main thing left is to determine the semantic (and then implement them) for applying operations on the object. If we have a string (query) and completions (5 quer...
24,800
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/module.py
14,15
10,115
named_parameters
BaseModule
18,50
15,50
class BaseModule: def __init__(self): pass def named_parameters(self): FILL_FUNC_BODY def named_sub_modules(self, type_=None, skip_compiled=False) -> Generator[tuple[str, "BaseModule"], None, None]: """Find all sub-modules in the module, as well as their names. Say self.children[4][...
class BaseModule: def __init__(self): pass def named_parameters(self): """ Unlike PyTorch, handles (non-recursive) lists of parameters too. """ FILL_FUNC_BODY def named_sub_modules(self, type_=None, skip_compiled=False) -> Generator[tuple[str, "BaseModule"], None, None]: ...
import dspy from dspy.predict.parameter import Parameter visited = set() named_parameters = [] def add_parameter(param_name, param_value): if isinstance(param_value, Parameter) and id(param_value) not in visited: visited.add(id(param_value)) ...
""" Unlike PyTorch, handles (non-recursive) lists of parameters too. """ import dspy from dspy.predict.parameter import Parameter visited = set() named_parameters = [] def add_parameter(param_name, param_value): if isinstance(param_value, Pa...
83
715
346
1,061
import copy from collections import deque from collections.abc import Generator import ujson # NOTE: Note: It's important (temporary decision) to maintain named_parameters that's different in behavior from # named_sub_modules for the time being. class BaseModule: def __init__(self): pass def named_p...
import copy from collections import deque from collections.abc import Generator import ujson # NOTE: Note: It's important (temporary decision) to maintain named_parameters that's different in behavior from # named_sub_modules for the time being. class BaseModule: def __init__(self): pass def named_p...
24,801
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/prediction.py
58,59
38,91
items
Completions
59,61
59,61
class Completions: def __init__(self, list_or_dict, signature=None): self.signature = signature if isinstance(list_or_dict, list): kwargs = {} for arg in list_or_dict: for k, v in arg.items(): kwargs.setdefault(k, []).append(v) els...
class Completions: def __init__(self, list_or_dict, signature=None): self.signature = signature if isinstance(list_or_dict, list): kwargs = {} for arg in list_or_dict: for k, v in arg.items(): kwargs.setdefault(k, []).append(v) els...
return self._completions.items()
return self._completions.items()
2
538
14
552
from dspy.primitives.example import Example class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None...
from dspy.primitives.example import Example class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None...
24,802
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/prediction.py
13,15
4,38
from_completions
Prediction
15,21
15,21
class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None): FILL_FUNC_BODY def __repr__(self): ...
class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None): FILL_FUNC_BODY def __repr__(self): ...
obj = cls() obj._completions = Completions(list_or_dict, signature=signature) obj._store = {k: v[0] for k, v in obj._completions.items()} return obj
obj = cls() obj._completions = Completions(list_or_dict, signature=signature) obj._store = {k: v[0] for k, v in obj._completions.items()} return obj
18
286
68
354
from dspy.primitives.example import Example class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None...
from dspy.primitives.example import Example class Prediction(Example): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self._demos del self._input_keys self._completions = None @classmethod def from_completions(cls, list_or_dict, signature=None...
24,803
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/python_interpreter.py
569,573
529,595
execute
CodePrompt
573,595
573,595
class CodePrompt(TextPrompt): r"""A class that represents a code prompt. It extends the :obj:`TextPrompt` class with a :obj:`code_type` property. Attributes: code_type (str, optional): The type of code. Defaults to None. """ def __new__(cls, *args: Any, **kwargs: Any) -> 'CodePrompt': ...
class CodePrompt(TextPrompt): r"""A class that represents a code prompt. It extends the :obj:`TextPrompt` class with a :obj:`code_type` property. Attributes: code_type (str, optional): The type of code. Defaults to None. """ def __new__(cls, *args: Any, **kwargs: Any) -> 'CodePrompt': ...
r"""Executes the code string by a given python interpreter. Args: interpreter (PythonInterpreter, optional): interpreter to be used during code execution. (default: :obj:`None`) user_variable (Optional[Dict[str, Any]]): variables that can be used ...
r"""Executes the code string by a given python interpreter. Args: interpreter (PythonInterpreter, optional): interpreter to be used during code execution. (default: :obj:`None`) user_variable (Optional[Dict[str, Any]]): variables that can be used ...
107
417
281
698
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== # Licensed under the Apache License, Version 2.0 (the “License”); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== # Licensed under the Apache License, Version 2.0 (the “License”); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
24,805
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/primitives/python_interpreter.py
504,506
494,529
key_words
TextPrompt
507,512
506,512
class TextPrompt(str): r"""A class that represents a text prompt. The :obj:`TextPrompt` class extends the built-in :obj:`str` class to provide a property for retrieving the set of keywords in the prompt. Attributes: key_words (set): A set of strings representing the keywords in the ...
class TextPrompt(str): r"""A class that represents a text prompt. The :obj:`TextPrompt` class extends the built-in :obj:`str` class to provide a property for retrieving the set of keywords in the prompt. Attributes: key_words (set): A set of strings representing the keywords in the ...
# Regex to find format placeholders within the string, excluding escaped braces pattern = re.compile(r"\{([^{}]+)\}") found = pattern.findall(self) return set(found)
"""Returns a set of strings representing the keywords in the prompt.""" # Regex to find format placeholders within the string, excluding escaped braces pattern = re.compile(r"\{([^{}]+)\}") found = pattern.findall(self) return set(found)
20
332
63
395
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== # Licensed under the Apache License, Version 2.0 (the “License”); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. =========== # Licensed under the Apache License, Version 2.0 (the “License”); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
24,806
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/clarifai_rm.py
59,62
19,97
forward
ClarifaiRM
79,97
62,97
class ClarifaiRM(dspy.Retrieve): """ Retrieval module uses clarifai to return the Top K relevant pasages for the given query. Assuming that you have ingested the source documents into clarifai App, where it is indexed and stored. Args: clarifai_user_id (str): Clarifai unique user_id. cl...
class ClarifaiRM(dspy.Retrieve): """ Retrieval module uses clarifai to return the Top K relevant pasages for the given query. Assuming that you have ingested the source documents into clarifai App, where it is indexed and stored. Args: clarifai_user_id (str): Clarifai unique user_id. cl...
queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) passages = [] queries = [q for q in queries if q] for query in queries: search_response = self.clarifai_search.query(ranks=[{"text_raw": qu...
"""Uses clarifai-python SDK search function and retrieves top_k similar passages for given query, Args: query_or_queries : single query or list of queries k : Top K relevant documents to return Returns: passages in format of dotdict Examples: ...
60
734
212
946
"""Clarifai as retriver to retrieve hits""" import os from concurrent.futures import ThreadPoolExecutor from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict try: from clarifai.client.search import Search except ImportError as err: raise ImportError( "Clar...
"""Clarifai as retriver to retrieve hits""" import os from concurrent.futures import ThreadPoolExecutor from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict try: from clarifai.client.search import Search except ImportError as err: raise ImportError( "Clar...
24,807
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/databricks_rm.py
90,91
12,148
forward
DatabricksRM
100,148
91,148
class DatabricksRM(dspy.Retrieve): """ A retrieval module that uses Databricks Vector Search Endpoint to return the top-k embeddings for a given query. Args: databricks_index_name (str): Databricks vector search index to query databricks_endpoint (str): Databricks index endpoint url ...
class DatabricksRM(dspy.Retrieve): """ A retrieval module that uses Databricks Vector Search Endpoint to return the top-k embeddings for a given query. Args: databricks_index_name (str): Databricks vector search index to query databricks_endpoint (str): Databricks index endpoint url ...
headers = { "Authorization": f"Bearer {self.databricks_token}", "Content-Type": "application/json", } payload = { "columns": self.columns, "num_results": self.k, } if query_type == 'vector': if not isinstance(query, list...
"""Search with Databricks Vector Search Client for self.k top results for query Args: query (Union[str, List[float]]): query to search for. query_type (str): 'vector' for Direct Vector Access Index and Delta Sync Index using self-managed vectors or 'text' for Delta Sync Index us...
156
1,301
592
1,893
import json import os from collections import defaultdict from typing import List, Union import requests import dspy from dspy.primitives.prediction import Prediction class DatabricksRM(dspy.Retrieve): """ A retrieval module that uses Databricks Vector Search Endpoint to return the top-k embeddings for a gi...
import json import os from collections import defaultdict from typing import List, Union import requests import dspy from dspy.primitives.prediction import Prediction class DatabricksRM(dspy.Retrieve): """ A retrieval module that uses Databricks Vector Search Endpoint to return the top-k embeddings for a gi...
24,808
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/faiss_rm.py
109,110
26,155
forward
FaissRM
118,155
110,155
class FaissRM(dspy.Retrieve): """A retrieval module that uses an in-memory Faiss to return the top passages for a given query. Args: document_chunks: the input text chunks vectorizer: an object that is a subclass of BaseSentenceVectorizer k (int, optional): The number of top passages to...
class FaissRM(dspy.Retrieve): """A retrieval module that uses an in-memory Faiss to return the top passages for a given query. Args: document_chunks: the input text chunks vectorizer: an object that is a subclass of BaseSentenceVectorizer k (int, optional): The number of top passages to...
queries = [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries queries = [q for q in queries if q] # Filter empty queries embeddings = self._vectorizer(queries) emb_npa = np.array(embeddings) # For single query, just look up the top k passages if...
"""Search the faiss index for k or self.k top passages for query. Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. Returns: dspy.Prediction: An object containing the retrieved passages. """ queries = [query_or_queries] ...
227
1,194
652
1,846
"""Retriever model for faiss: https://github.com/facebookresearch/faiss. Author: Jagane Sundar: https://github.com/jagane. """ from typing import Optional, Union import numpy as np import dspy from dsp.modules.sentence_vectorizer import SentenceTransformersVectorizer from dsp.utils import dotdict try: import fa...
"""Retriever model for faiss: https://github.com/facebookresearch/faiss. Author: Jagane Sundar: https://github.com/jagane. """ from typing import Optional, Union import numpy as np import dspy from dsp.modules.sentence_vectorizer import SentenceTransformersVectorizer from dsp.utils import dotdict try: import fa...
24,809
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/marqo_rm.py
61,62
14,97
forward
MarqoRM
70,97
62,97
class MarqoRM(dspy.Retrieve): """ A retrieval module that uses Marqo to return the top passages for a given query. Assumes that a Marqo index has been created and populated with the following payload: - document: The text of the passage Args: marqo_index_name (str): The name of the mar...
class MarqoRM(dspy.Retrieve): """ A retrieval module that uses Marqo to return the top passages for a given query. Assumes that a Marqo index has been created and populated with the following payload: - document: The text of the passage Args: marqo_index_name (str): The name of the mar...
queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) queries = [q for q in queries if q] limit = k if k else self.k all_query_results = [] for query in queries: _result = self._marqo_c...
"""Search with Marqo for self.k top passages for query Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. Returns: dspy.Prediction: An object containing the retrieved passages. """ queries = ( [query_or_querie...
72
712
292
1,004
from collections import defaultdict from typing import List, Union import dspy from dsp.utils import dotdict try: import marqo except ImportError: raise ImportError( "The 'marqo' extra is required to use MarqoRM. Install it with `pip install dspy-ai[marqo]`", ) class MarqoRM(dspy.Retrieve): "...
from collections import defaultdict from typing import List, Union import dspy from dsp.utils import dotdict try: import marqo except ImportError: raise ImportError( "The 'marqo' extra is required to use MarqoRM. Install it with `pip install dspy-ai[marqo]`", ) class MarqoRM(dspy.Retrieve): "...
24,810
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/milvus_rm.py
18,19
1,108
openai_embedding_function
19,29
19,29
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
from openai import OpenAI client = OpenAI() response = client.embeddings.create( input=texts, model="text-embedding-3-small", ) return [x.embedding for x in response.data]
from openai import OpenAI client = OpenAI() response = client.embeddings.create( input=texts, model="text-embedding-3-small", ) return [x.embedding for x in response.data]
19
1,156
78
1,234
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
24,811
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/milvus_rm.py
87,88
29,108
forward
MilvusRM
88,108
88,108
class MilvusRM(dspy.Retrieve): """ A retrieval module that uses Milvus to return passages for a given query. Assumes that a Milvus collection has been created and populated with the following field: - text: The text of the passage Args: collection_name (str): The name of the Milvus col...
class MilvusRM(dspy.Retrieve): """ A retrieval module that uses Milvus to return passages for a given query. Assumes that a Milvus collection has been created and populated with the following field: - text: The text of the passage Args: collection_name (str): The name of the Milvus col...
if isinstance(query_or_queries, str): query_or_queries = [query_or_queries] query_embeddings = self.embedding_function(query_or_queries) k = k or self.top_k milvus_res = self.milvus_client.search( collection_name=self.collection_name, data=query_embe...
if isinstance(query_or_queries, str): query_or_queries = [query_or_queries] query_embeddings = self.embedding_function(query_or_queries) k = k or self.top_k milvus_res = self.milvus_client.search( collection_name=self.collection_name, data=query_embe...
53
782
259
1,041
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
""" Retriever model for Milvus or Zilliz Cloud """ from typing import Callable, List, Optional, Union import dspy from dsp.utils import dotdict try: from pymilvus import MilvusClient except ImportError: raise ImportError( "The pymilvus library is required to use MilvusRM. Install it with `pip install...
24,812
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/mongodb_atlas_rm.py
30,33
1,120
build_vector_search_pipeline
33,47
33,47
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
return [ { "$vectorSearch": { "index": index_name, "path": "embedding", "queryVector": query_vector, "numCandidates": num_candidates, "limit": limit, }, }, {"$project": {"_id": 0, "text": ...
return [ { "$vectorSearch": { "index": index_name, "path": "embedding", "queryVector": query_vector, "numCandidates": num_candidates, "limit": limit, }, }, {"$project": {"_id": 0, "text": ...
26
1,014
122
1,136
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
24,813
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/mongodb_atlas_rm.py
110,111
71,120
forward
MongoDBAtlasRM
111,120
111,120
class MongoDBAtlasRM(dspy.Retrieve): def __init__( self, db_name: str, collection_name: str, index_name: str, k: int = 5, embedding_provider: str = "openai", embedding_model: str = "text-embedding-ada-002", ): super().__init__(k=k) self.db_...
class MongoDBAtlasRM(dspy.Retrieve): def __init__( self, db_name: str, collection_name: str, index_name: str, k: int = 5, embedding_provider: str = "openai", embedding_model: str = "text-embedding-ada-002", ): super().__init__(k=k) self.db_...
query_vector = self.embedder([query_or_queries]) pipeline = build_vector_search_pipeline( index_name=self.index_name, query_vector=query_vector[0], num_candidates=self.k * 10, limit=self.k, ) contents = self.client[self.db_name][self.collec...
query_vector = self.embedder([query_or_queries]) pipeline = build_vector_search_pipeline( index_name=self.index_name, query_vector=query_vector[0], num_candidates=self.k * 10, limit=self.k, ) contents = self.client[self.db_name][self.collec...
18
465
135
600
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
import os from typing import Any, List import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy try: from pymongo import MongoClient from pymongo.errors import ( ConfigurationError, Connection...
24,814
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/neo4j_rm.py
140,141
55,159
forward
Neo4jRM
141,159
141,159
class Neo4jRM(dspy.Retrieve): """ Implements a retriever that utilizes Neo4j for retrieving passages. This class manages a connection to a Neo4j database using official Neo4j Python drivers and requires the database credentials (username, password, URI, and optionally the database name) to be set as env...
class Neo4jRM(dspy.Retrieve): """ Implements a retriever that utilizes Neo4j for retrieving passages. This class manages a connection to a Neo4j database using official Neo4j Python drivers and requires the database credentials (username, password, URI, and optionally the database name) to be set as env...
if not isinstance(query_or_queries, list): query_or_queries = [query_or_queries] query_vectors = self.embedder(query_or_queries) contents = [] retrieval_query = self.retrieval_query or f"RETURN node.{self.text_node_property} AS text, score" for vector in query_vectors...
if not isinstance(query_or_queries, list): query_or_queries = [query_or_queries] query_vectors = self.embedder(query_or_queries) contents = [] retrieval_query = self.retrieval_query or f"RETURN node.{self.text_node_property} AS text, score" for vector in query_vectors...
71
1,175
280
1,455
import os from typing import Any, List, Optional, Union import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy from dsp.utils import dotdict try: from neo4j import GraphDatabase from neo4j.exceptions import...
import os from typing import Any, List, Optional, Union import backoff from openai import ( APITimeoutError, InternalServerError, OpenAI, RateLimitError, UnprocessableEntityError, ) import dspy from dsp.utils import dotdict try: from neo4j import GraphDatabase from neo4j.exceptions import...
24,815
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/pgvector_rm.py
94,95
21,154
forward
PgVectorRM
103,145
95,145
class PgVectorRM(dspy.Retrieve): """ Implements a retriever that (as the name suggests) uses pgvector to retrieve passages, using a raw SQL query and a postgresql connection managed by psycopg2. It needs to register the pgvector extension with the psycopg2 connection Returns a list of dspy.Example...
class PgVectorRM(dspy.Retrieve): """ Implements a retriever that (as the name suggests) uses pgvector to retrieve passages, using a raw SQL query and a postgresql connection managed by psycopg2. It needs to register the pgvector extension with the psycopg2 connection Returns a list of dspy.Example...
# Embed query query_embedding = self._get_embeddings(query) retrieved_docs = [] fields = sql.SQL(',').join([ sql.Identifier(f) for f in self.fields ]) if self.include_similarity: similarity_field = ( sql.SQL(',') + ...
"""Search with PgVector for self.k top passages for query using cosine similarity Args: query (str): The query to search for include_similarity (bool): Whether or not to include the similarity for each record Returns: dspy.Prediction: an object containing th...
102
1,147
427
1,574
import warnings from typing import Callable, Optional import dspy try: import psycopg2 from pgvector.psycopg2 import register_vector from psycopg2 import sql except ImportError: raise ImportError( "The 'pgvector' extra is required to use PgVectorRM. Install it with `pip install dspy-ai[pgvecto...
import warnings from typing import Callable, Optional import dspy try: import psycopg2 from pgvector.psycopg2 import register_vector from psycopg2 import sql except ImportError: raise ImportError( "The 'pgvector' extra is required to use PgVectorRM. Install it with `pip install dspy-ai[pgvecto...
24,816
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/qdrant_rm.py
56,57
16,90
forward
QdrantRM
65,90
57,90
class QdrantRM(dspy.Retrieve): """ A retrieval module that uses Qdrant to return the top passages for a given query. Assumes that a Qdrant collection has been created and populated with the following payload: - document: The text of the passage Args: qdrant_collection_name (str): The n...
class QdrantRM(dspy.Retrieve): """ A retrieval module that uses Qdrant to return the top passages for a given query. Assumes that a Qdrant collection has been created and populated with the following payload: - document: The text of the passage Args: qdrant_collection_name (str): The n...
queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) queries = [q for q in queries if q] # Filter empty queries k = k if k is not None else self.k batch_results = self._qdrant_client.query_batch( ...
"""Search with Qdrant for self.k top passages for query Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. k (Optional[int]): The number of top passages to retrieve. Defaults to self.k. Returns: dspy.Prediction: An object cont...
104
604
304
908
from collections import defaultdict from typing import List, Optional, Union import dspy from dsp.utils import dotdict try: import fastembed from qdrant_client import QdrantClient except ImportError: raise ImportError( "The 'qdrant' extra is required to use QdrantRM. Install it with `pip install d...
from collections import defaultdict from typing import List, Optional, Union import dspy from dsp.utils import dotdict try: import fastembed from qdrant_client import QdrantClient except ImportError: raise ImportError( "The 'qdrant' extra is required to use QdrantRM. Install it with `pip install d...
24,817
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/ragatouille_rm.py
42,43
14,63
forward
RAGatouilleRM
51,63
43,63
class RAGatouilleRM(dspy.Retrieve): """A retrieval model that uses RAGatouille library to return the top passages for a given query. Assumes that you already have an index created with RAGatouille. Reference: https://github.com/bclavie/RAGatouille Args: index_root (str): Folder path where you ...
class RAGatouilleRM(dspy.Retrieve): """A retrieval model that uses RAGatouille library to return the top passages for a given query. Assumes that you already have an index created with RAGatouille. Reference: https://github.com/bclavie/RAGatouille Args: index_root (str): Folder path where you ...
k = k if k is not None else self.k queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) queries = [q for q in queries if q] passages = [] for query in queries: results = self.model.sear...
"""Search with RAGAtouille based index for self.k top passages for query Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. k (Optional[int]): The number of top passages to retrieve. Defaults to self.k. Returns: dspy.Predictio...
48
532
150
682
from typing import Optional, Union import dspy from dsp.utils.utils import dotdict try: from ragatouille import RAGPretrainedModel except ImportError: raise Exception( "You need to install RAGAtouille library, Please use the command: pip install ragatouille", ) class RAGatouilleRM(dspy.Retrieve)...
from typing import Optional, Union import dspy from dsp.utils.utils import dotdict try: from ragatouille import RAGPretrainedModel except ImportError: raise Exception( "You need to install RAGAtouille library, Please use the command: pip install ragatouille", ) class RAGatouilleRM(dspy.Retrieve)...
24,818
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/retrieve.py
21,22
9,43
dump_state
Retrieve
22,25
22,25
class Retrieve(Parameter): name = "Search" input_variable = "query" desc = "takes a search query and returns one or more potentially relevant passages from a corpus" def __init__(self, k=3): self.stage = random.randbytes(8).hex() self.k = k def reset(self): pass def du...
class Retrieve(Parameter): name = "Search" input_variable = "query" desc = "takes a search query and returns one or more potentially relevant passages from a corpus" def __init__(self, k=3): self.stage = random.randbytes(8).hex() self.k = k def reset(self): pass def du...
state_keys = ["k"] return {k: getattr(self, k) for k in state_keys}
state_keys = ["k"] return {k: getattr(self, k) for k in state_keys}
11
372
33
405
import random from typing import List, Optional, Union import dsp from dspy.predict.parameter import Parameter from dspy.primitives.prediction import Prediction class Retrieve(Parameter): name = "Search" input_variable = "query" desc = "takes a search query and returns one or more potentially relevant pa...
import random from typing import List, Optional, Union import dsp from dspy.predict.parameter import Parameter from dspy.primitives.prediction import Prediction class Retrieve(Parameter): name = "Search" input_variable = "query" desc = "takes a search query and returns one or more potentially relevant pa...
24,819
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/vectara_rm.py
14,15
1,164
remove_snippet
15,17
15,17
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: FILL_FUNC_BODYclass VectaraRM(dspy.Retrieve): """ A retrieval mo...
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: FILL_FUNC_BODYclass VectaraRM(dspy.Retrieve): """ A retrieval mo...
return s.replace(START_SNIPPET, "").replace(END_SNIPPET, "")
return s.replace(START_SNIPPET, "").replace(END_SNIPPET, "")
4
1,757
30
1,787
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: FILL_FUNC_BODYclass VectaraRM(dspy.Retrieve): """ A retrieval mo...
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: FILL_FUNC_BODYclass VectaraRM(dspy.Retrieve): """ A retrieval mo...
24,820
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/vectara_rm.py
132,133
17,164
forward
VectaraRM
141,164
133,164
class VectaraRM(dspy.Retrieve): """ A retrieval module that uses Vectara to return the top passages for a given query. Assumes that a Vectara corpus has been created and populated with the following payload: - document: The text of the passage Args: vectara_customer_id (str): Vectara C...
class VectaraRM(dspy.Retrieve): """ A retrieval module that uses Vectara to return the top passages for a given query. Assumes that a Vectara corpus has been created and populated with the following payload: - document: The text of the passage Args: vectara_customer_id (str): Vectara C...
queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) queries = [q for q in queries if q] # Filter empty queries k = k if k is not None else self.k all_res = [] limit = 3*k if len(queries)...
"""Search with Vectara for self.k top passages for query Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. k (Optional[int]): The number of top passages to retrieve. Defaults to self.k. Returns: dspy.Prediction: An object con...
84
1,433
259
1,692
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: return s.replace(START_SNIPPET, "").replace(END_SNIPPET, "") class ...
import json import os from collections import defaultdict from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict START_SNIPPET = "<%START%>" END_SNIPPET = "<%END%>" def remove_snippet(s: str) -> str: return s.replace(START_SNIPPET, "").replace(END_SNIPPET, "") class ...
24,821
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/weaviate_rm.py
65,66
16,99
forward
WeaviateRM
74,99
66,99
class WeaviateRM(dspy.Retrieve): """ A retrieval module that uses Weaviate to return the top passages for a given query. Assumes that a Weaviate collection has been created and populated with the following payload: - content: The text of the passage Args: weaviate_collection_name (str)...
class WeaviateRM(dspy.Retrieve): """ A retrieval module that uses Weaviate to return the top passages for a given query. Assumes that a Weaviate collection has been created and populated with the following payload: - content: The text of the passage Args: weaviate_collection_name (str)...
k = k if k is not None else self.k queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) queries = [q for q in queries if q] passages = [] for query in queries: collection = self._weavi...
"""Search with Weaviate for self.k top passages for query Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. k (Optional[int]): The number of top passages to retrieve. Defaults to self.k. Returns: dspy.Prediction: An object co...
85
863
308
1,171
from typing import List, Optional, Union import dspy from dsp.utils import dotdict try: import weaviate import weaviate.classes as wvc from weaviate.collections.classes.grpc import HybridFusion except ImportError: raise ImportError( "The 'weaviate' extra is required to use WeaviateRM. Install ...
from typing import List, Optional, Union import dspy from dsp.utils import dotdict try: import weaviate import weaviate.classes as wvc from weaviate.collections.classes.grpc import HybridFusion except ImportError: raise ImportError( "The 'weaviate' extra is required to use WeaviateRM. Install ...
24,822
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/retrieve/you_rm.py
20,21
10,49
forward
YouRM
30,49
21,49
class YouRM(dspy.Retrieve): def __init__(self, ydc_api_key=None, k=3): super().__init__(k=k) if not ydc_api_key and not os.environ.get("YDC_API_KEY"): raise RuntimeError("You must supply ydc_api_key or set environment variable YDC_API_KEY") elif ydc_api_key: self.ydc_...
class YouRM(dspy.Retrieve): def __init__(self, ydc_api_key=None, k=3): super().__init__(k=k) if not ydc_api_key and not os.environ.get("YDC_API_KEY"): raise RuntimeError("You must supply ydc_api_key or set environment variable YDC_API_KEY") elif ydc_api_key: self.ydc_...
k = k if k is not None else self.k queries = ( [query_or_queries] if isinstance(query_or_queries, str) else query_or_queries ) docs = [] for query in queries: headers = {"X-API-Key": self.ydc_api_key} results = request...
"""Search with You.com for self.k top passages for query or queries Args: query_or_queries (Union[str, List[str]]): The query or queries to search for. k (Optional[int]): The number of context strings to return, if not already specified in self.k Returns: ds...
53
305
211
516
import os from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict class YouRM(dspy.Retrieve): def __init__(self, ydc_api_key=None, k=3): super().__init__(k=k) if not ydc_api_key and not os.environ.get("YDC_API_KEY"): raise RuntimeError("You ...
import os from typing import List, Optional, Union import requests import dspy from dsp.utils import dotdict class YouRM(dspy.Retrieve): def __init__(self, ydc_api_key=None, k=3): super().__init__(k=k) if not ydc_api_key and not os.environ.get("YDC_API_KEY"): raise RuntimeError("You ...
24,823
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/signatures/field.py
37,38
1,76
new_to_old_field
38,45
38,45
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
return (OldInputField if field.json_schema_extra["__dspy_field_type"] == "input" else OldOutputField)( prefix=field.json_schema_extra["prefix"], desc=field.json_schema_extra["desc"], format=field.json_schema_extra.get("format"), )
return (OldInputField if field.json_schema_extra["__dspy_field_type"] == "input" else OldOutputField)( prefix=field.json_schema_extra["prefix"], desc=field.json_schema_extra["desc"], format=field.json_schema_extra.get("format"), )
12
803
90
893
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
24,824
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/signatures/field.py
53,54
45,68
finalize
OldField
55,61
54,61
class OldField: """A more ergonomic datatype that infers prefix and desc if omitted.""" def __init__(self, *, prefix=None, desc=None, input, format=None): self.prefix = prefix # This can be None initially and set later self.desc = desc self.format = format def finalize(self, key, ...
class OldField: """A more ergonomic datatype that infers prefix and desc if omitted.""" def __init__(self, *, prefix=None, desc=None, input, format=None): self.prefix = prefix # This can be None initially and set later self.desc = desc self.format = format def finalize(self, key, ...
if self.prefix is None: self.prefix = inferred_prefix + ":" if self.desc is None: self.desc = f"${{{key}}}"
"""Set the prefix if it's not provided explicitly.""" if self.prefix is None: self.prefix = inferred_prefix + ":" if self.desc is None: self.desc = f"${{{key}}}"
16
192
53
245
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
import pydantic # 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", "prefix", "format", "parser", "__dspy_field_type"] def move_kwargs...
24,827
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/ensemble.py
20,21
10,41
compile
Ensemble
21,41
21,41
class Ensemble(Teleprompter): def __init__(self, *, reduce_fn=None, size=None, deterministic=False): """A common reduce_fn is dspy.majority.""" assert deterministic is False, "TODO: Implement example hashing for deterministic ensemble." self.reduce_fn = reduce_fn self.size = size ...
class Ensemble(Teleprompter): def __init__(self, *, reduce_fn=None, size=None, deterministic=False): """A common reduce_fn is dspy.majority.""" assert deterministic is False, "TODO: Implement example hashing for deterministic ensemble." self.reduce_fn = reduce_fn self.size = size ...
size = self.size reduce_fn = self.reduce_fn import dspy class EnsembledProgram(dspy.Module): def __init__(self): super().__init__() self.programs = programs def forward(self, *args, **kwargs): programs = random.sa...
size = self.size reduce_fn = self.reduce_fn import dspy class EnsembledProgram(dspy.Module): def __init__(self): super().__init__() self.programs = programs def forward(self, *args, **kwargs): programs = random.sa...
44
124
170
294
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...
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...
24,828
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/ensemble.py
31,32
26,40
forward
EnsembledProgram
32,40
32,40
class EnsembledProgram(dspy.Module): def __init__(self): super().__init__() self.programs = programs def forward(self, *args, **kwargs): FILL_FUNC_BODY
class EnsembledProgram(dspy.Module): def __init__(self): super().__init__() self.programs = programs def forward(self, *args, **kwargs): FILL_FUNC_BODY
programs = random.sample(self.programs, size) if size else self.programs outputs = [prog(*args, **kwargs) for prog in programs] if reduce_fn: return reduce_fn(outputs) return outputs
programs = random.sample(self.programs, size) if size else self.programs outputs = [prog(*args, **kwargs) for prog in programs] if reduce_fn: return reduce_fn(outputs) return outputs
22
61
73
134
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...
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...
24,829
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/finetune.py
64,81
50,190
compile
BootstrapFinetune
81,190
81,190
class BootstrapFinetune(Teleprompter): def __init__(self, metric=None, teacher_settings={}, multitask=True): self.metric = metric self.teacher_settings = teacher_settings self.multitask = multitask metric = metric or (lambda *args: True) self.teleprompter = BootstrapFewShot(...
class BootstrapFinetune(Teleprompter): def __init__(self, metric=None, teacher_settings={}, multitask=True): self.metric = metric self.teacher_settings = teacher_settings self.multitask = multitask metric = metric or (lambda *args: True) self.teleprompter = BootstrapFewShot(...
# It's usually better to supply a few-shot teacher, rather than uncompiled module (the student). if teacher is None: print( "WARNING: Using a vanilla teacher. " "Are you sure you want to use BootstrapFinetune without a compiled teacher?", ) ...
# It's usually better to supply a few-shot teacher, rather than uncompiled module (the student). if teacher is None: print( "WARNING: Using a vanilla teacher. " "Are you sure you want to use BootstrapFinetune without a compiled teacher?", ) ...
350
295
1,336
1,631
import os import random import time import ujson from datasets.fingerprint import Hasher import dsp from dspy.signatures.signature import signature_to_template from .bootstrap import BootstrapFewShot # from dspy.primitives import Example from .teleprompt import Teleprompter # from .vanilla import LabeledFewShot #...
import os import random import time import ujson from datasets.fingerprint import Hasher import dsp from dspy.signatures.signature import signature_to_template from .bootstrap import BootstrapFewShot # from dspy.primitives import Example from .teleprompt import Teleprompter # from .vanilla import LabeledFewShot #...
24,830
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/knn_fewshot.py
14,15
10,30
compile
KNNFewShot
15,30
15,30
class KNNFewShot(Teleprompter): def __init__(self, KNN, k: int, trainset: List[dsp.Example]): self.KNN = KNN(k, trainset) def compile(self, student, *, teacher=None, trainset, valset=None): FILL_FUNC_BODY
class KNNFewShot(Teleprompter): def __init__(self, KNN, k: int, trainset: List[dsp.Example]): self.KNN = KNN(k, trainset) def compile(self, student, *, teacher=None, trainset, valset=None): FILL_FUNC_BODY
student_copy = student.reset_copy() def forward_pass(*args, **kwargs): knn_trainset = self.KNN(**kwargs) few_shot_bootstrap = BootstrapFewShot() compiled_program = few_shot_bootstrap.compile( student, teacher=teacher, t...
student_copy = student.reset_copy() def forward_pass(*args, **kwargs): knn_trainset = self.KNN(**kwargs) few_shot_bootstrap = BootstrapFewShot() compiled_program = few_shot_bootstrap.compile( student, teacher=teacher, t...
28
89
156
245
import types from typing import List import dsp from dspy.teleprompt import BootstrapFewShot from .teleprompt import Teleprompter class KNNFewShot(Teleprompter): def __init__(self, KNN, k: int, trainset: List[dsp.Example]): self.KNN = KNN(k, trainset) def compile(self, student, *, teacher=None, tra...
import types from typing import List import dsp from dspy.teleprompt import BootstrapFewShot from .teleprompt import Teleprompter class KNNFewShot(Teleprompter): def __init__(self, KNN, k: int, trainset: List[dsp.Example]): self.KNN = KNN(k, trainset) def compile(self, student, *, teacher=None, tra...
24,831
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/signature_opt_bayesian.py
67,82
38,94
compile
BayesianSignatureOptimizer
82,94
82,94
class BayesianSignatureOptimizer(MIPRO): def __init__( self, prompt_model=None, task_model=None, teacher_settings={}, n=10, metric=None, init_temperature=1.0, verbose=False, track_stats=True, view_data_batch_size=10, ): prin...
class BayesianSignatureOptimizer(MIPRO): def __init__( self, prompt_model=None, task_model=None, teacher_settings={}, n=10, metric=None, init_temperature=1.0, verbose=False, track_stats=True, view_data_batch_size=10, ): prin...
return super().compile( student, trainset=devset, max_bootstrapped_demos=max_bootstrapped_demos, max_labeled_demos=max_labeled_demos, eval_kwargs=eval_kwargs, seed=seed, view_data=view_data, view_examples=view_exampl...
return super().compile( student, trainset=devset, max_bootstrapped_demos=max_bootstrapped_demos, max_labeled_demos=max_labeled_demos, eval_kwargs=eval_kwargs, seed=seed, view_data=view_data, view_examples=view_exampl...
13
391
143
534
from dspy.teleprompt.mipro_optimizer import MIPRO """ =============================================================== DEPRECATED!!! PLEASE USE MIPRO INSTEAD. =============================================================== USAGE SUGGESTIONS: The following code can be used to compile a optimized signature teleprompter...
from dspy.teleprompt.mipro_optimizer import MIPRO """ =============================================================== DEPRECATED!!! PLEASE USE MIPRO INSTEAD. =============================================================== USAGE SUGGESTIONS: The following code can be used to compile a optimized signature teleprompter...
24,833
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/signature_opt_typed.py
121,124
104,128
check_signature_not_attempted
GenerateSignature
124,128
124,128
class GenerateSignature(dspy.Signature, Generic[T]): __doc__ = textwrap.dedent("""\ You are an instruction optimizer for large language models. I will give some task instructions I've tried, along with their corresponding validation scores. - The instructions are arranged in order b...
class GenerateSignature(dspy.Signature, Generic[T]): __doc__ = textwrap.dedent("""\ You are an instruction optimizer for large language models. I will give some task instructions I've tried, along with their corresponding validation scores. - The instructions are arranged in order b...
if s in signatures_to_avoid: raise ValueError("Never propose a signature already in the list above.") return s
if s in signatures_to_avoid: raise ValueError("Never propose a signature already in the list above.") return s
16
287
37
324
import textwrap from dataclasses import dataclass from typing import Generic, Literal, TypeVar import pydantic import dspy from dspy import BaseModel from dspy.functional.functional import TypedChainOfThought, TypedPredictor from dspy.signatures import Signature from dspy.signatures.field import InputField, OutputFie...
import textwrap from dataclasses import dataclass from typing import Generic, Literal, TypeVar import pydantic import dspy from dspy import BaseModel from dspy.functional.functional import TypedChainOfThought, TypedPredictor from dspy.signatures import Signature from dspy.signatures.field import InputField, OutputFie...
24,834
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/teleprompt_optuna.py
39,40
9,80
objective
BootstrapFewShotWithOptuna
40,59
40,59
class BootstrapFewShotWithOptuna(Teleprompter): def __init__( self, metric, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, num_candidate_programs=16, num_threads=6, ): self.metric = metric self.te...
class BootstrapFewShotWithOptuna(Teleprompter): def __init__( self, metric, teacher_settings={}, max_bootstrapped_demos=4, max_labeled_demos=16, max_rounds=1, num_candidate_programs=16, num_threads=6, ): self.metric = metric self.te...
program2 = self.student.reset_copy() for (name, compiled_predictor), (_, program2_predictor) in zip( self.compiled_teleprompter.named_predictors(), program2.named_predictors(), ): all_demos = compiled_predictor.demos demo_index = trial.suggest_int(f"demo_index...
program2 = self.student.reset_copy() for (name, compiled_predictor), (_, program2_predictor) in zip( self.compiled_teleprompter.named_predictors(), program2.named_predictors(), ): all_demos = compiled_predictor.demos demo_index = trial.suggest_int(f"demo_index...
47
737
271
1,008
import optuna from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt.teleprompt import Teleprompter from .bootstrap import BootstrapFewShot class BootstrapFewShotWithOptuna(Teleprompter): def __init__( self, metric, teacher_settings={}, max_bootstrapped_demos=4, ...
import optuna from dspy.evaluate.evaluate import Evaluate from dspy.teleprompt.teleprompt import Teleprompter from .bootstrap import BootstrapFewShot class BootstrapFewShotWithOptuna(Teleprompter): def __init__( self, metric, teacher_settings={}, max_bootstrapped_demos=4, ...
24,835
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/teleprompt/vanilla.py
10,11
6,31
compile
LabeledFewShot
11,31
11,31
class LabeledFewShot(Teleprompter): def __init__(self, k=16): self.k = k def compile(self, student, *, trainset, sample=True): FILL_FUNC_BODY
class LabeledFewShot(Teleprompter): def __init__(self, k=16): self.k = k def compile(self, student, *, trainset, sample=True): FILL_FUNC_BODY
self.student = student.reset_copy() self.trainset = trainset if len(self.trainset) == 0: return self.student rng = random.Random(0) for predictor in self.student.predictors(): if sample: predictor.demos = rng.sample(self.trainset, min(se...
self.student = student.reset_copy() self.trainset = trainset if len(self.trainset) == 0: return self.student rng = random.Random(0) for predictor in self.student.predictors(): if sample: predictor.demos = rng.sample(self.trainset, min(se...
80
63
236
299
import random from .teleprompt import Teleprompter class LabeledFewShot(Teleprompter): def __init__(self, k=16): self.k = k def compile(self, student, *, trainset, sample=True): FILL_FUNC_BODY
import random from .teleprompt import Teleprompter class LabeledFewShot(Teleprompter): def __init__(self, k=16): self.k = k def compile(self, student, *, trainset, sample=True): FILL_FUNC_BODY
24,836
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/utils/logging.py
86,87
1,101
show_logging
87,99
87,99
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
logging.basicConfig( format="%(message)s", stream=sys.stdout, level=level, ) # 'backoff' is used by OpenAI, and defaults their log level to INFO. # this can clobber up dspy relevant logging for users # this silences there logs. logging.getLogger("backoff").setLevel(loggi...
logging.basicConfig( format="%(message)s", stream=sys.stdout, level=level, ) # 'backoff' is used by OpenAI, and defaults their log level to INFO. # this can clobber up dspy relevant logging for users # this silences there logs. logging.getLogger("backoff").setLevel(loggi...
34
797
115
912
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
24,837
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/dspy/utils/logging.py
44,50
11,82
set_log_output
LogSettings
50,82
50,82
class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name self._configure_structlog() def _configure_structlog(self): if self.output_type == "st...
class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name self._configure_structlog() def _configure_structlog(self): if self.output_type == "st...
if method is not None and method not in ["console", "file"]: raise ValueError("method provided can only be 'console', 'file'") if method == "file" and file_name is None: raise ValueError("file_name must be provided when method = 'file'") if method is not None: ...
if method is not None and method not in ["console", "file"]: raise ValueError("method provided can only be 'console', 'file'") if method == "file" and file_name is None: raise ValueError("file_name must be provided when method = 'file'") if method is not None: ...
107
396
320
716
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
import logging import os import sys import typing as t import structlog logger = structlog.get_logger() class LogSettings: def __init__(self, output_type: str, method: str, file_name: t.Optional[str]) -> None: self.output_type = output_type self.method = method self.file_name = file_name...
24,838
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/examples/functional/repl.py
28,29
1,30
execute_code
29,30
29,30
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
return PythonREPL().run(command, timeout, globals, locals)
return PythonREPL().run(command, timeout, globals, locals)
5
271
19
290
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
24,839
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/examples/functional/repl.py
14,15
5,28
run
PythonREPL
15,28
15,28
class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, timeout=5, globals={}, locals=None) -> Optional[str]:...
class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, timeout=5, globals={}, locals=None) -> Optional[str]:...
queue: multiprocessing.Queue = multiprocessing.Queue() p = multiprocessing.Process( target=self.worker, args=(command, globals, locals, queue), ) p.start() p.join(timeout) if p.is_alive(): p.terminate() return "TimeoutError" ret...
queue: multiprocessing.Queue = multiprocessing.Queue() p = multiprocessing.Process( target=self.worker, args=(command, globals, locals, queue), ) p.start() p.join(timeout) if p.is_alive(): p.terminate() return "TimeoutError" ret...
36
111
131
242
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
import multiprocessing from typing import Optional class PythonREPL: @classmethod def worker(cls, code: str, globals, locals, queue): try: exec(code, globals, locals) queue.put(None) except Exception as e: queue.put(repr(e)) def run(self, command: str, ...
24,840
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy
/home/hieuvd/dung_repo/raw/stars_01/stanfordnlp_dspy/dspy/examples/tweets/tweet_metric.py
27,28
1,51
metric
28,51
28,51
import dspy from dspy.datasets import HotPotQA # Load the dataset. dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=200, test_size=0, keep_details=True) # Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata. trainset = [x.without('id', 'type').with_in...
import dspy from dspy.datasets import HotPotQA # Load the dataset. dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=200, test_size=0, keep_details=True) # Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata. trainset = [x.without('id', 'type').with_in...
question, answer, tweet = gold.question, gold.answer, pred.output context = retrieve(question).passages engaging = "Does the assessed text make for a self-contained, engaging tweet?" faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context." ...
question, answer, tweet = gold.question, gold.answer, pred.output context = retrieve(question).passages engaging = "Does the assessed text make for a self-contained, engaging tweet?" faithful = "Is the assessed text grounded in the context? Say no if it includes significant facts not in the context." ...
150
381
415
796
import dspy from dspy.datasets import HotPotQA # Load the dataset. dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=200, test_size=0, keep_details=True) # Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata. trainset = [x.without('id', 'type').with_in...
import dspy from dspy.datasets import HotPotQA # Load the dataset. dataset = HotPotQA(train_seed=1, train_size=200, eval_seed=2023, dev_size=200, test_size=0, keep_details=True) # Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata. trainset = [x.without('id', 'type').with_in...
25,103
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/action/action.py
34,36
11,42
execute
Action
36,42
36,42
class Action: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: str ) -> str: env = Environment(loader=BaseLoader()) template = env....
class Action: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: str ) -> str: env = Environment(loader=BaseLoader()) template = env....
prompt = self.render(conversation) response = self.llm.inference(prompt, project_name) valid_response = self.validate_response(response) return valid_response
prompt = self.render(conversation) response = self.llm.inference(prompt, project_name) valid_response = self.validate_response(response) return valid_response
12
218
60
278
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.config import Config from src.llm import LLM PROMPT = open("src/agents/action/prompt.jinja2", "r").read().strip() class Action: def __init__(self, base_model: str): config = C...
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.config import Config from src.llm import LLM PROMPT = open("src/agents/action/prompt.jinja2", "r").read().strip() class Action: def __init__(self, base_model: str): config = C...
25,104
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/answer/answer.py
35,37
11,43
execute
Answer
37,43
37,43
class Answer: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: str, code_markdown: str ) -> str: env = Environment(loader=BaseLoader()) ...
class Answer: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: str, code_markdown: str ) -> str: env = Environment(loader=BaseLoader()) ...
prompt = self.render(conversation, code_markdown) response = self.llm.inference(prompt, project_name) valid_response = self.validate_response(response) return valid_response
prompt = self.render(conversation, code_markdown) response = self.llm.inference(prompt, project_name) valid_response = self.validate_response(response) return valid_response
13
234
65
299
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.config import Config from src.llm import LLM PROMPT = open("src/agents/answer/prompt.jinja2", "r").read().strip() class Answer: def __init__(self, base_model: str): config = C...
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.config import Config from src.llm import LLM PROMPT = open("src/agents/answer/prompt.jinja2", "r").read().strip() class Answer: def __init__(self, base_model: str): config = C...
25,105
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/coder/coder.py
34,35
16,135
validate_response
Coder
35,68
35,68
class Coder: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.logger = Logger() self.llm = LLM(model_id=base_model) def render( self, step_by_step_plan: str, user_context: str, search_results: dict ) -> str: ...
class Coder: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.logger = Logger() self.llm = LLM(model_id=base_model) def render( self, step_by_step_plan: str, user_context: str, search_results: dict ) -> str: ...
response = response.strip() self.logger.debug(f"Response from the model: {response}") if "~~~" not in response: return False response = response.split("~~~", 1)[1] response = response[:response.rfind("~~~")] response = response.strip() result = [] ...
response = response.strip() self.logger.debug(f"Response from the model: {response}") if "~~~" not in response: return False response = response.split("~~~", 1)[1] response = response[:response.rfind("~~~")] response = response.strip() result = [] ...
79
975
312
1,287
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.config import Config from src.llm import LLM from src.state import AgentState from src.logger import Logger from src.services.utils import retry_wrapper from src.socket_instance import emit_agent PROMPT = o...
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.config import Config from src.llm import LLM from src.state import AgentState from src.logger import Logger from src.services.utils import retry_wrapper from src.socket_instance import emit_agent PROMPT = o...
25,106
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/decision/decision.py
14,15
10,35
render
Decision
15,19
15,19
class Decision: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: FILL_FUNC_BODY @validate_responses def validate_response(self, response: str): for item in response: if "function" not in item or "args" not in item ...
class Decision: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: FILL_FUNC_BODY @validate_responses def validate_response(self, response: str): for item in response: if "function" not in item or "args" not in item ...
env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(prompt=prompt)
env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(prompt=prompt)
8
212
43
255
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.llm import LLM PROMPT = open("src/agents/decision/prompt.jinja2").read().strip() class Decision: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) ...
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper, validate_responses from src.llm import LLM PROMPT = open("src/agents/decision/prompt.jinja2").read().strip() class Decision: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) ...
25,107
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/feature/feature.py
80,81
16,129
get_project_path
Feature
81,84
81,84
class Feature: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: list, code_markdown: str, system_os: str ) -> str: ...
class Feature: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: list, code_markdown: str, system_os: str ) -> str: ...
project_name = project_name.lower().replace(" ", "-") return f"{self.project_dir}/{project_name}"
project_name = project_name.lower().replace(" ", "-") return f"{self.project_dir}/{project_name}"
7
1,099
38
1,137
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.config import Config from src.llm import LLM from src.state import AgentState from src.services.utils import retry_wrapper from src.socket_instance import emit_agent PROMPT = open("src/agents/feature/prompt...
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.config import Config from src.llm import LLM from src.state import AgentState from src.services.utils import retry_wrapper from src.socket_instance import emit_agent PROMPT = open("src/agents/feature/prompt...
25,108
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/formatter/formatter.py
19,20
7,23
execute
Formatter
20,23
20,23
class Formatter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, raw_text: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(raw_text=raw_text) def validate_response(se...
class Formatter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, raw_text: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(raw_text=raw_text) def validate_response(se...
raw_text = self.render(raw_text) response = self.llm.inference(raw_text, project_name) return response
raw_text = self.render(raw_text) response = self.llm.inference(raw_text, project_name) return response
9
152
40
192
from jinja2 import Environment, BaseLoader from src.llm import LLM PROMPT = open("src/agents/formatter/prompt.jinja2").read().strip() class Formatter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, raw_text: str) -> str: env = Environment(loader=Bas...
from jinja2 import Environment, BaseLoader from src.llm import LLM PROMPT = open("src/agents/formatter/prompt.jinja2").read().strip() class Formatter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, raw_text: str) -> str: env = Environment(loader=Bas...
25,109
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/internal_monologue/internal_monologue.py
28,30
10,35
execute
InternalMonologue
30,35
30,35
class InternalMonologue: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, current_prompt: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(current_prompt=current_prompt) @v...
class InternalMonologue: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, current_prompt: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(current_prompt=current_prompt) @v...
rendered_prompt = self.render(current_prompt) response = self.llm.inference(rendered_prompt, project_name) valid_response = self.validate_response(response) return valid_response
rendered_prompt = self.render(current_prompt) response = self.llm.inference(rendered_prompt, project_name) valid_response = self.validate_response(response) return valid_response
12
216
64
280
import json from jinja2 import Environment, BaseLoader from src.llm import LLM from src.services.utils import retry_wrapper, validate_responses PROMPT = open("src/agents/internal_monologue/prompt.jinja2").read().strip() class InternalMonologue: def __init__(self, base_model: str): self.llm = LLM(model_i...
import json from jinja2 import Environment, BaseLoader from src.llm import LLM from src.services.utils import retry_wrapper, validate_responses PROMPT = open("src/agents/internal_monologue/prompt.jinja2").read().strip() class InternalMonologue: def __init__(self, base_model: str): self.llm = LLM(model_i...
25,110
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/patcher/patcher.py
40,41
15,139
validate_response
Patcher
41,69
41,69
class Patcher: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: list, code_markdown: str, commands: list, error :str, ...
class Patcher: def __init__(self, base_model: str): config = Config() self.project_dir = config.get_projects_dir() self.llm = LLM(model_id=base_model) def render( self, conversation: list, code_markdown: str, commands: list, error :str, ...
response = response.strip() response = response.split("~~~", 1)[1] response = response[:response.rfind("~~~")] response = response.strip() result = [] current_file = None current_code = [] code_block = False for line in response.split("\n"): ...
response = response.strip() response = response.split("~~~", 1)[1] response = response[:response.rfind("~~~")] response = response.strip() result = [] current_file = None current_code = [] code_block = False for line in response.split("\n"): ...
67
947
272
1,219
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.socket_instance import emit_agent from src.config import Config from src.llm import LLM from src.state import AgentState from src.services.utils import retry_wrapper PROMPT = open("src/agents/patcher/prompt...
import os import time from jinja2 import Environment, BaseLoader from typing import List, Dict, Union from src.socket_instance import emit_agent from src.config import Config from src.llm import LLM from src.state import AgentState from src.services.utils import retry_wrapper PROMPT = open("src/agents/patcher/prompt...
25,111
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/planner/planner.py
68,69
7,72
execute
Planner
69,72
69,72
class Planner: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(prompt=prompt) def validate_response(self, resp...
class Planner: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render(prompt=prompt) def validate_response(self, resp...
prompt = self.render(prompt) response = self.llm.inference(prompt, project_name) return response
prompt = self.render(prompt) response = self.llm.inference(prompt, project_name) return response
9
673
37
710
from jinja2 import Environment, BaseLoader from src.llm import LLM PROMPT = open("src/agents/planner/prompt.jinja2").read().strip() class Planner: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: env = Environment(loader=BaseLoade...
from jinja2 import Environment, BaseLoader from src.llm import LLM PROMPT = open("src/agents/planner/prompt.jinja2").read().strip() class Planner: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, prompt: str) -> str: env = Environment(loader=BaseLoade...
25,112
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/reporter/reporter.py
22,23
10,43
validate_response
Reporter
23,30
23,30
class Reporter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, conversation: list, code_markdown: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render( conversation=co...
class Reporter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, conversation: list, code_markdown: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) return template.render( conversation=co...
response = response.strip().replace("```md", "```") if response.startswith("```") and response.endswith("```"): response = response[3:-3].strip() return response
response = response.strip().replace("```md", "```") if response.startswith("```") and response.endswith("```"): response = response[3:-3].strip() return response
13
240
65
305
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper from src.llm import LLM PROMPT = open("src/agents/reporter/prompt.jinja2").read().strip() class Reporter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, con...
import json from jinja2 import Environment, BaseLoader from src.services.utils import retry_wrapper from src.llm import LLM PROMPT = open("src/agents/reporter/prompt.jinja2").read().strip() class Reporter: def __init__(self, base_model: str): self.llm = LLM(model_id=base_model) def render(self, con...
25,113
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/researcher/researcher.py
26,28
13,47
validate_response
Researcher
28,37
28,37
class Researcher: def __init__(self, base_model: str): self.bing_search = BingSearch() self.llm = LLM(model_id=base_model) def render(self, step_by_step_plan: str, contextual_keywords: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) ...
class Researcher: def __init__(self, base_model: str): self.bing_search = BingSearch() self.llm = LLM(model_id=base_model) def render(self, step_by_step_plan: str, contextual_keywords: str) -> str: env = Environment(loader=BaseLoader()) template = env.from_string(PROMPT) ...
if "queries" not in response and "ask_user" not in response: return False else: return { "queries": response["queries"], "ask_user": response["ask_user"] }
if "queries" not in response and "ask_user" not in response: return False else: return { "queries": response["queries"], "ask_user": response["ask_user"] }
20
328
71
399
import json from typing import List from jinja2 import Environment, BaseLoader from src.llm import LLM from src.services.utils import retry_wrapper, validate_responses from src.browser.search import BingSearch PROMPT = open("src/agents/researcher/prompt.jinja2").read().strip() class Researcher: def __init__(se...
import json from typing import List from jinja2 import Environment, BaseLoader from src.llm import LLM from src.services.utils import retry_wrapper, validate_responses from src.browser.search import BingSearch PROMPT = open("src/agents/researcher/prompt.jinja2").read().strip() class Researcher: def __init__(se...
25,114
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/agents/runner/runner.py
69,79
18,223
run_code
Runner
79,199
79,199
class Runner: def __init__(self, base_model: str): self.base_model = base_model self.llm = LLM(model_id=base_model) def render( self, conversation: str, code_markdown: str, system_os: str ) -> str: env = Environment(loader=BaseLoader()) templa...
class Runner: def __init__(self, base_model: str): self.base_model = base_model self.llm = LLM(model_id=base_model) def render( self, conversation: str, code_markdown: str, system_os: str ) -> str: env = Environment(loader=BaseLoader()) templa...
retries = 0 for command in commands: command_set = command.split(" ") command_failed = False process = subprocess.run( command_set, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cw...
retries = 0 for command in commands: command_set = command.split(" ") command_failed = False process = subprocess.run( command_set, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cw...
235
632
1,266
1,898
import time import json import os import subprocess from jinja2 import Environment, BaseLoader from src.agents.patcher import Patcher from src.llm import LLM from src.state import AgentState from src.project import ProjectManager from src.services.utils import retry_wrapper, validate_responses PROMPT = open("src/ag...
import time import json import os import subprocess from jinja2 import Environment, BaseLoader from src.agents.patcher import Patcher from src.llm import LLM from src.state import AgentState from src.project import ProjectManager from src.services.utils import retry_wrapper, validate_responses PROMPT = open("src/ag...
25,115
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/bert/sentence.py
8,9
3,18
extract_keywords
SentenceBert
9,18
9,18
class SentenceBert: def __init__(self, sentence: str): self.sentence = sentence self.kw_model = KeyBERT() def extract_keywords(self, top_n: int = 5) -> list: FILL_FUNC_BODY
class SentenceBert: def __init__(self, sentence: str): self.sentence = sentence self.kw_model = KeyBERT() def extract_keywords(self, top_n: int = 5) -> list: FILL_FUNC_BODY
keywords = self.kw_model.extract_keywords( self.sentence, keyphrase_ngram_range=(1, 1), stop_words='english', top_n=top_n, use_mmr=True, diversity=0.7 ) return keywords
keywords = self.kw_model.extract_keywords( self.sentence, keyphrase_ngram_range=(1, 1), stop_words='english', top_n=top_n, use_mmr=True, diversity=0.7 ) return keywords
13
72
91
163
from keybert import KeyBERT class SentenceBert: def __init__(self, sentence: str): self.sentence = sentence self.kw_model = KeyBERT() def extract_keywords(self, top_n: int = 5) -> list: FILL_FUNC_BODY
from keybert import KeyBERT class SentenceBert: def __init__(self, sentence: str): self.sentence = sentence self.kw_model = KeyBERT() def extract_keywords(self, top_n: int = 5) -> list: FILL_FUNC_BODY
25,116
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/browser/browser.py
80,81
14,90
get_content
Browser
81,84
81,84
class Browser: def __init__(self): self.playwright = None self.browser = None self.page = None self.agent = AgentState() async def start(self): self.playwright = await async_playwright().start() self.browser = await self.playwright.chromium.launch(headless=True) ...
class Browser: def __init__(self): self.playwright = None self.browser = None self.page = None self.agent = AgentState() async def start(self): self.playwright = await async_playwright().start() self.browser = await self.playwright.chromium.launch(headless=True) ...
pdf_path = self.get_pdf() return self.pdf_to_text(pdf_path)
pdf_path = self.get_pdf() return self.pdf_to_text(pdf_path)
5
817
31
848
import asyncio import base64 import os from playwright.sync_api import sync_playwright, TimeoutError, Page from playwright.async_api import async_playwright, TimeoutError from markdownify import markdownify as md from pdfminer.high_level import extract_text from src.socket_instance import emit_agent from src.config im...
import asyncio import base64 import os from playwright.sync_api import sync_playwright, TimeoutError, Page from playwright.async_api import async_playwright, TimeoutError from markdownify import markdownify as md from pdfminer.high_level import extract_text from src.socket_instance import emit_agent from src.config im...
25,118
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/documenter/pdf.py
13,14
8,24
markdown_to_pdf
PDF
14,24
14,24
class PDF: def __init__(self): config = Config() self.pdf_path = config.get_pdfs_dir() def markdown_to_pdf(self, markdown_string, project_name): FILL_FUNC_BODY
class PDF: def __init__(self): config = Config() self.pdf_path = config.get_pdfs_dir() def markdown_to_pdf(self, markdown_string, project_name): FILL_FUNC_BODY
html_string = markdown(markdown_string) out_file_path = os.path.join(self.pdf_path, f"{project_name}.pdf") with open(out_file_path, "wb") as out_file: pisa_status = pisa.CreatePDF(html_string, dest=out_file) if pisa_status.err: raise Exception("Error gen...
html_string = markdown(markdown_string) out_file_path = os.path.join(self.pdf_path, f"{project_name}.pdf") with open(out_file_path, "wb") as out_file: pisa_status = pisa.CreatePDF(html_string, dest=out_file) if pisa_status.err: raise Exception("Error gen...
24
68
126
194
import os from io import BytesIO from markdown import markdown from xhtml2pdf import pisa from src.config import Config class PDF: def __init__(self): config = Config() self.pdf_path = config.get_pdfs_dir() def markdown_to_pdf(self, markdown_string, project_name): FILL_FUNC_BODY
import os from io import BytesIO from markdown import markdown from xhtml2pdf import pisa from src.config import Config class PDF: def __init__(self): config = Config() self.pdf_path = config.get_pdfs_dir() def markdown_to_pdf(self, markdown_string, project_name): FILL_FUNC_BODY
25,119
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/filesystem/read_code.py
15,16
9,36
read_directory
ReadCode
16,28
16,28
class ReadCode: def __init__(self, project_name: str): config = Config() project_path = config.get_projects_dir() self.directory_path = os.path.join(project_path, project_name.lower().replace(" ", "-")) def read_directory(self): FILL_FUNC_BODY def code_set_to_markdown(self): ...
class ReadCode: def __init__(self, project_name: str): config = Config() project_path = config.get_projects_dir() self.directory_path = os.path.join(project_path, project_name.lower().replace(" ", "-")) def read_directory(self): FILL_FUNC_BODY def code_set_to_markdown(self): ...
files_list = [] for root, _dirs, files in os.walk(self.directory_path): for file in files: try: file_path = os.path.join(root, file) with open(file_path, 'r') as file_content: files_list.append({"filename": file_...
files_list = [] for root, _dirs, files in os.walk(self.directory_path): for file in files: try: file_path = os.path.join(root, file) with open(file_path, 'r') as file_content: files_list.append({"filename": file_...
31
189
124
313
import os from src.config import Config """ TODO: Replace this with `code2prompt` - https://github.com/mufeedvh/code2prompt """ class ReadCode: def __init__(self, project_name: str): config = Config() project_path = config.get_projects_dir() self.directory_path = os.path.join(project_path...
import os from src.config import Config """ TODO: Replace this with `code2prompt` - https://github.com/mufeedvh/code2prompt """ class ReadCode: def __init__(self, project_name: str): config = Config() project_path = config.get_projects_dir() self.directory_path = os.path.join(project_path...
25,120
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/init.py
6,7
1,33
init_devika
7,33
7,33
import os from src.config import Config from src.logger import Logger def init_devika(): FILL_FUNC_BODY
import os from src.config import Config from src.logger import Logger def init_devika(): FILL_FUNC_BODY
logger = Logger() logger.info("Initializing Devika...") logger.info("checking configurations...") config = Config() sqlite_db = config.get_sqlite_db() screenshots_dir = config.get_screenshots_dir() pdfs_dir = config.get_pdfs_dir() projects_dir = config.get_projects_dir() logs_...
logger = Logger() logger.info("Initializing Devika...") logger.info("checking configurations...") config = Config() sqlite_db = config.get_sqlite_db() screenshots_dir = config.get_screenshots_dir() pdfs_dir = config.get_pdfs_dir() projects_dir = config.get_projects_dir() logs_...
61
37
344
381
import os from src.config import Config from src.logger import Logger def init_devika(): FILL_FUNC_BODY
import os from src.config import Config from src.logger import Logger def init_devika(): FILL_FUNC_BODY
25,121
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/llm/claude_client.py
13,14
5,27
inference
Claude
14,27
14,27
class Claude: def __init__(self): config = Config() api_key = config.get_claude_api_key() self.client = Anthropic( api_key=api_key, ) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
class Claude: def __init__(self): config = Config() api_key = config.get_claude_api_key() self.client = Anthropic( api_key=api_key, ) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
message = self.client.messages.create( max_tokens=4096, messages=[ { "role": "user", "content": prompt.strip(), } ], model=model_id, temperature=0 ) return message...
message = self.client.messages.create( max_tokens=4096, messages=[ { "role": "user", "content": prompt.strip(), } ], model=model_id, temperature=0 ) return message...
17
91
95
186
from anthropic import Anthropic from src.config import Config class Claude: def __init__(self): config = Config() api_key = config.get_claude_api_key() self.client = Anthropic( api_key=api_key, ) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BOD...
from anthropic import Anthropic from src.config import Config class Claude: def __init__(self): config = Config() api_key = config.get_claude_api_key() self.client = Anthropic( api_key=api_key, ) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BOD...
25,122
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/llm/gemini_client.py
12,13
6,34
inference
Gemini
13,34
13,34
class Gemini: def __init__(self): config = Config() api_key = config.get_gemini_api_key() genai.configure(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
class Gemini: def __init__(self): config = Config() api_key = config.get_gemini_api_key() genai.configure(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
config = genai.GenerationConfig(temperature=0) model = genai.GenerativeModel(model_id, generation_config=config) # Set safety settings for the request safety_settings = { HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATE...
config = genai.GenerationConfig(temperature=0) model = genai.GenerativeModel(model_id, generation_config=config) # Set safety settings for the request safety_settings = { HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATE...
111
85
342
427
import google.generativeai as genai from google.generativeai.types import HarmCategory, HarmBlockThreshold from src.config import Config class Gemini: def __init__(self): config = Config() api_key = config.get_gemini_api_key() genai.configure(api_key=api_key) def inference(self, model...
import google.generativeai as genai from google.generativeai.types import HarmCategory, HarmBlockThreshold from src.config import Config class Gemini: def __init__(self): config = Config() api_key = config.get_gemini_api_key() genai.configure(api_key=api_key) def inference(self, model...
25,123
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/llm/groq_client.py
12,13
6,25
inference
Groq
13,25
13,25
class Groq: def __init__(self): config = Config() api_key = config.get_groq_api_key() self.client = _Groq(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
class Groq: def __init__(self): config = Config() api_key = config.get_groq_api_key() self.client = _Groq(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
chat_completion = self.client.chat.completions.create( messages=[ { "role": "user", "content": prompt.strip(), } ], model=model_id, temperature=0 ) return chat_completion.choi...
chat_completion = self.client.chat.completions.create( messages=[ { "role": "user", "content": prompt.strip(), } ], model=model_id, temperature=0 ) return chat_completion.choi...
16
87
95
182
from groq import Groq as _Groq from src.config import Config class Groq: def __init__(self): config = Config() api_key = config.get_groq_api_key() self.client = _Groq(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
from groq import Groq as _Groq from src.config import Config class Groq: def __init__(self): config = Config() api_key = config.get_groq_api_key() self.client = _Groq(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
25,124
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/llm/llm.py
83,84
27,147
inference
LLM
84,147
84,147
class LLM: def __init__(self, model_id: str = None): self.model_id = model_id self.log_prompts = config.get_logging_prompts() self.timeout_inference = config.get_timeout_inference() self.models = { "CLAUDE": [ ("Claude 3 Opus", "claude-3-opus-20240229"), ...
class LLM: def __init__(self, model_id: str = None): self.model_id = model_id self.log_prompts = config.get_logging_prompts() self.timeout_inference = config.get_timeout_inference() self.models = { "CLAUDE": [ ("Claude 3 Opus", "claude-3-opus-20240229"), ...
self.update_global_token_usage(prompt, project_name) model_enum, model_name = self.model_enum(self.model_id) print(f"Model: {self.model_id}, Enum: {model_enum}") if model_enum is None: raise ValueError(f"Model {self.model_id} not supported") model_m...
self.update_global_token_usage(prompt, project_name) model_enum, model_name = self.model_enum(self.model_id) print(f"Model: {self.model_id}, Enum: {model_enum}") if model_enum is None: raise ValueError(f"Model {self.model_id} not supported") model_m...
157
811
718
1,529
import sys import tiktoken from typing import List, Tuple from src.socket_instance import emit_agent from .ollama_client import Ollama from .claude_client import Claude from .openai_client import OpenAi from .gemini_client import Gemini from .mistral_client import MistralAi from .groq_client import Groq from src.sta...
import sys import tiktoken from typing import List, Tuple from src.socket_instance import emit_agent from .ollama_client import Ollama from .claude_client import Claude from .openai_client import OpenAi from .gemini_client import Gemini from .mistral_client import MistralAi from .groq_client import Groq from src.sta...
25,125
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika
/home/hieuvd/dung_repo/raw/stars_01/stitionai_devika/devika/src/llm/mistral_client.py
13,14
7,23
inference
MistralAi
14,23
14,23
class MistralAi: def __init__(self): config = Config() api_key = config.get_mistral_api_key() self.client = MistralClient(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
class MistralAi: def __init__(self): config = Config() api_key = config.get_mistral_api_key() self.client = MistralClient(api_key=api_key) def inference(self, model_id: str, prompt: str) -> str: FILL_FUNC_BODY
print("prompt", prompt.strip()) chat_completion = self.client.chat( model=model_id, messages=[ ChatMessage(role="user", content=prompt.strip()) ], temperature=0 ) return chat_completion.choices[0].message.content
print("prompt", prompt.strip()) chat_completion = self.client.chat( model=model_id, messages=[ ChatMessage(role="user", content=prompt.strip()) ], temperature=0 ) return chat_completion.choices[0].message.content
14
90
90
180
from mistralai.client import MistralClient from mistralai.models.chat_completion import ChatMessage from src.config import Config class MistralAi: def __init__(self): config = Config() api_key = config.get_mistral_api_key() self.client = MistralClient(api_key=api_key) def inference(s...
from mistralai.client import MistralClient from mistralai.models.chat_completion import ChatMessage from src.config import Config class MistralAi: def __init__(self): config = Config() api_key = config.get_mistral_api_key() self.client = MistralClient(api_key=api_key) def inference(s...