method_name stringlengths 1 78 | method_body stringlengths 3 9.66k | full_code stringlengths 31 10.7k | docstring stringlengths 4 4.74k ⌀ |
|---|---|---|---|
test_one_namespace_w_list_of_features_no_emb | str1 = 'test1'
str2 = 'test2'
expected = [{'test_namespace': [str1, str2]}]
assert base.embed({'test_namespace': [str1, str2]}, MockEncoder()) == expected | @pytest.mark.requires('vowpal_wabbit_next')
def test_one_namespace_w_list_of_features_no_emb() ->None:
str1 = 'test1'
str2 = 'test2'
expected = [{'test_namespace': [str1, str2]}]
assert base.embed({'test_namespace': [str1, str2]}, MockEncoder()
) == expected | null |
__init__ | super().__init__()
self._lock = threading.Lock() | def __init__(self) ->None:
super().__init__()
self._lock = threading.Lock() | null |
test_myscale | """Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
config = MyScaleSettings()
config.table = 'test_myscale'
docsearch = MyScale.from_texts(texts, FakeEmbeddings(), config=config)
output = docsearch.similarity_search('foo', k=1)
assert output == [Document(page_content='foo', metadata={'_dummy':... | def test_myscale() ->None:
"""Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
config = MyScaleSettings()
config.table = 'test_myscale'
docsearch = MyScale.from_texts(texts, FakeEmbeddings(), config=config)
output = docsearch.similarity_search('foo', k=1)
assert outp... | Test end to end construction and search. |
_import_spark_sql | from langchain_community.utilities.spark_sql import SparkSQL
return SparkSQL | def _import_spark_sql() ->Any:
from langchain_community.utilities.spark_sql import SparkSQL
return SparkSQL | null |
_run | """Use the tool."""
return self.api_wrapper.run(query) | def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun]
=None) ->str:
"""Use the tool."""
return self.api_wrapper.run(query) | Use the tool. |
_format_chat_history | buffer = []
for human, ai in chat_history:
buffer.append(HumanMessage(content=human))
buffer.append(AIMessage(content=ai))
return buffer | def _format_chat_history(chat_history: List[Tuple[str, str]]):
buffer = []
for human, ai in chat_history:
buffer.append(HumanMessage(content=human))
buffer.append(AIMessage(content=ai))
return buffer | null |
random_string | return str(uuid.uuid4()) | def random_string() ->str:
return str(uuid.uuid4()) | null |
visit_Name | if isinstance(node.ctx, ast.Load):
self.loads.add(node.id)
elif isinstance(node.ctx, ast.Store):
self.stores.add(node.id) | def visit_Name(self, node: ast.Name) ->Any:
if isinstance(node.ctx, ast.Load):
self.loads.add(node.id)
elif isinstance(node.ctx, ast.Store):
self.stores.add(node.id) | null |
test_openai_modelname_to_contextsize_valid | """Test model name to context size on a valid model."""
assert OpenAI().modelname_to_contextsize('davinci') == 2049 | def test_openai_modelname_to_contextsize_valid() ->None:
"""Test model name to context size on a valid model."""
assert OpenAI().modelname_to_contextsize('davinci') == 2049 | Test model name to context size on a valid model. |
deanonymize | """Deanonymize text"""
return self._deanonymize(text_to_deanonymize, deanonymizer_matching_strategy) | def deanonymize(self, text_to_deanonymize: str,
deanonymizer_matching_strategy: Callable[[str, MappingDataType], str]=
DEFAULT_DEANONYMIZER_MATCHING_STRATEGY) ->str:
"""Deanonymize text"""
return self._deanonymize(text_to_deanonymize,
deanonymizer_matching_strategy) | Deanonymize text |
test_ip | """Test inner product distance."""
texts = ['foo', 'bar', 'baz']
docsearch = USearch.from_texts(texts, FakeEmbeddings(), metric='ip')
output = docsearch.similarity_search_with_score('far', k=2)
_, score = output[1]
assert score == -8.0 | def test_ip() ->None:
"""Test inner product distance."""
texts = ['foo', 'bar', 'baz']
docsearch = USearch.from_texts(texts, FakeEmbeddings(), metric='ip')
output = docsearch.similarity_search_with_score('far', k=2)
_, score = output[1]
assert score == -8.0 | Test inner product distance. |
_llm_params | params: Dict[str, Any] = {'temperature': self.temperature, 'n': self.n}
if self.stop:
params['stop'] = self.stop
if self.max_tokens is not None:
params['max_tokens'] = self.max_tokens
return params | @property
def _llm_params(self) ->Dict[str, Any]:
params: Dict[str, Any] = {'temperature': self.temperature, 'n': self.n}
if self.stop:
params['stop'] = self.stop
if self.max_tokens is not None:
params['max_tokens'] = self.max_tokens
return params | null |
output_keys | """Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
return _output_keys | @property
def output_keys(self) ->List[str]:
"""Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
return _output_keys | Return the output keys.
:meta private: |
_identifying_params | """Get the identifying parameters."""
return {**{'model': self.model}, **self._default_params} | @property
def _identifying_params(self) ->Dict[str, Any]:
"""Get the identifying parameters."""
return {**{'model': self.model}, **self._default_params} | Get the identifying parameters. |
test_qdrant_similarity_search_filters | """Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i, 'metadata': {'page': i + 1, 'pages': [i + 2, -1]}} for
i in range(len(texts))]
docsearch = Qdrant.from_texts(texts, ConsistentFakeEmbeddings(), metadatas=
metadatas, location=':memory:', batch_size=batch_size, ... | @pytest.mark.parametrize('batch_size', [1, 64])
@pytest.mark.parametrize('vector_name', [None, 'my-vector'])
def test_qdrant_similarity_search_filters(batch_size: int, vector_name:
Optional[str]) ->None:
"""Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i... | Test end to end construction and search. |
get_tag | return datetime.datetime.now().strftime('%Y%m%d-%H%M%S') | def get_tag(self) ->str:
return datetime.datetime.now().strftime('%Y%m%d-%H%M%S') | null |
_import_titan_takeoff | from langchain_community.llms.titan_takeoff import TitanTakeoff
return TitanTakeoff | def _import_titan_takeoff() ->Any:
from langchain_community.llms.titan_takeoff import TitanTakeoff
return TitanTakeoff | null |
test_openllm_llm_local | llm = OpenLLM(model_name='flan-t5', model_id='google/flan-t5-small')
output = llm('Say foo:')
assert isinstance(output, str) | def test_openllm_llm_local() ->None:
llm = OpenLLM(model_name='flan-t5', model_id='google/flan-t5-small')
output = llm('Say foo:')
assert isinstance(output, str) | null |
test_python_repl | """Test functionality when globals/locals are not provided."""
repl = PythonREPL()
repl.run('foo = 1')
assert repl.locals is not None
assert repl.locals['foo'] == 1
repl.run('bar = foo * 2')
assert repl.locals is not None
assert repl.locals['bar'] == 2 | def test_python_repl() ->None:
"""Test functionality when globals/locals are not provided."""
repl = PythonREPL()
repl.run('foo = 1')
assert repl.locals is not None
assert repl.locals['foo'] == 1
repl.run('bar = foo * 2')
assert repl.locals is not None
assert repl.locals['bar'] == 2 | Test functionality when globals/locals are not provided. |
_get_mock_document | return {'uri': f'{uri}', 'title': f'Title {uri}', 'content': f'Content {uri}'} | def _get_mock_document(self, uri: str) ->Dict:
return {'uri': f'{uri}', 'title': f'Title {uri}', 'content':
f'Content {uri}'} | null |
test_add_documents | documents = [Document(page_content='test_add_documents document')]
added_documents = time_weighted_retriever.add_documents(documents)
assert isinstance(added_documents, list)
assert len(added_documents) == 1
assert time_weighted_retriever.memory_stream[-1].page_content == documents[0
].page_content | def test_add_documents(time_weighted_retriever:
TimeWeightedVectorStoreRetriever) ->None:
documents = [Document(page_content='test_add_documents document')]
added_documents = time_weighted_retriever.add_documents(documents)
assert isinstance(added_documents, list)
assert len(added_documents) == 1
... | null |
validate_inputs | """Ensure we have an LLM for each step."""
llm = values.get('llm')
ideation_llm = values.get('ideation_llm')
critique_llm = values.get('critique_llm')
resolver_llm = values.get('resolver_llm')
if not llm and not ideation_llm:
raise ValueError(
'Either ideation_llm or llm needs to be given. Pass llm, if you ... | @root_validator
@classmethod
def validate_inputs(cls, values: Dict[str, Any]) ->Dict[str, Any]:
"""Ensure we have an LLM for each step."""
llm = values.get('llm')
ideation_llm = values.get('ideation_llm')
critique_llm = values.get('critique_llm')
resolver_llm = values.get('resolver_llm')
if not ... | Ensure we have an LLM for each step. |
test_load | loader = GoogleSpeechToTextLoader(project_id='test_project_id', file_path=
'./testfile.mp3')
docs = loader.load()
assert len(docs) == 1
assert docs[0].page_content == 'Test transcription text'
assert docs[0].metadata['language_code'] == 'en-US' | @pytest.mark.requires('google.api_core')
def test_load() ->None:
loader = GoogleSpeechToTextLoader(project_id='test_project_id',
file_path='./testfile.mp3')
docs = loader.load()
assert len(docs) == 1
assert docs[0].page_content == 'Test transcription text'
assert docs[0].metadata['language_c... | null |
_get_complexity_metrics | """Compute text complexity metrics using textstat.
Parameters:
text (str): The text to analyze.
Returns:
(dict): A dictionary containing the complexity metrics.
"""
resp = {}
if self.complexity_metrics:
text_complexity_metrics = _fetch_text_complexity_metrics(text)
... | def _get_complexity_metrics(self, text: str) ->dict:
"""Compute text complexity metrics using textstat.
Parameters:
text (str): The text to analyze.
Returns:
(dict): A dictionary containing the complexity metrics.
"""
resp = {}
if self.complexity_metrics:
... | Compute text complexity metrics using textstat.
Parameters:
text (str): The text to analyze.
Returns:
(dict): A dictionary containing the complexity metrics. |
test_model_no_session_id_field_error | class Base(DeclarativeBase):
pass
class Model(Base):
__tablename__ = 'test_table'
id = Column(Integer, primary_key=True)
test_field = Column(Text)
class CustomMessageConverter(DefaultMessageConverter):
def get_sql_model_class(self) ->Any:
return Model
with pytest.raises(ValueError):
SQL... | def test_model_no_session_id_field_error(con_str: str) ->None:
class Base(DeclarativeBase):
pass
class Model(Base):
__tablename__ = 'test_table'
id = Column(Integer, primary_key=True)
test_field = Column(Text)
class CustomMessageConverter(DefaultMessageConverter):
... | null |
raw_results | params = {'api_key': self.tavily_api_key, 'query': query, 'max_results':
max_results, 'search_depth': search_depth, 'include_domains':
include_domains, 'exclude_domains': exclude_domains, 'include_answer':
include_answer, 'include_raw_content': include_raw_content,
'include_images': include_images}
resp... | def raw_results(self, query: str, max_results: Optional[int]=5,
search_depth: Optional[str]='advanced', include_domains: Optional[List[
str]]=[], exclude_domains: Optional[List[str]]=[], include_answer:
Optional[bool]=False, include_raw_content: Optional[bool]=False,
include_images: Optional[bool]=False... | null |
drop | """
Helper function: Drop data
"""
self.client.command(
f'DROP TABLE IF EXISTS {self.config.database}.{self.config.table}') | def drop(self) ->None:
"""
Helper function: Drop data
"""
self.client.command(
f'DROP TABLE IF EXISTS {self.config.database}.{self.config.table}') | Helper function: Drop data |
format_memories_simple | return '; '.join([f'{mem.page_content}' for mem in relevant_memories]) | def format_memories_simple(self, relevant_memories: List[Document]) ->str:
return '; '.join([f'{mem.page_content}' for mem in relevant_memories]) | null |
test_litellm_call | """Test valid call to litellm."""
chat = ChatLiteLLM(model='test')
message = HumanMessage(content='Hello')
response = chat([message])
assert isinstance(response, AIMessage)
assert isinstance(response.content, str) | def test_litellm_call() ->None:
"""Test valid call to litellm."""
chat = ChatLiteLLM(model='test')
message = HumanMessage(content='Hello')
response = chat([message])
assert isinstance(response, AIMessage)
assert isinstance(response.content, str) | Test valid call to litellm. |
output_keys | """Expect output key.
:meta private:
"""
return [self.output_key] | @property
def output_keys(self) ->List[str]:
"""Expect output key.
:meta private:
"""
return [self.output_key] | Expect output key.
:meta private: |
_get_default_parser | """Get default mime-type based parser."""
return MimeTypeBasedParser(handlers={'application/pdf': PyMuPDFParser(),
'text/plain': TextParser(), 'application/msword': MsWordParser(),
'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
MsWordParser()}, fallback_parser=None) | def _get_default_parser() ->BaseBlobParser:
"""Get default mime-type based parser."""
return MimeTypeBasedParser(handlers={'application/pdf': PyMuPDFParser(),
'text/plain': TextParser(), 'application/msword': MsWordParser(),
'application/vnd.openxmlformats-officedocument.wordprocessingml.documen... | Get default mime-type based parser. |
iter | """Enables iteration over steps taken to reach final output."""
return AgentExecutorIterator(self, inputs, callbacks, tags=self.tags,
include_run_info=include_run_info) | def iter(self, inputs: Any, callbacks: Callbacks=None, *, include_run_info:
bool=False, async_: bool=False) ->AgentExecutorIterator:
"""Enables iteration over steps taken to reach final output."""
return AgentExecutorIterator(self, inputs, callbacks, tags=self.tags,
include_run_info=include_run_info... | Enables iteration over steps taken to reach final output. |
memory_variables | """The list of keys emitted from the load_memory_variables method."""
return [self.memory_key] | @property
def memory_variables(self) ->List[str]:
"""The list of keys emitted from the load_memory_variables method."""
return [self.memory_key] | The list of keys emitted from the load_memory_variables method. |
get_input_variables | """Get input variables."""
created_variables = set()
all_variables = set()
for k, prompt in values['pipeline_prompts']:
created_variables.add(k)
all_variables.update(prompt.input_variables)
values['input_variables'] = list(all_variables.difference(created_variables))
return values | @root_validator(pre=True)
def get_input_variables(cls, values: Dict) ->Dict:
"""Get input variables."""
created_variables = set()
all_variables = set()
for k, prompt in values['pipeline_prompts']:
created_variables.add(k)
all_variables.update(prompt.input_variables)
values['input_var... | Get input variables. |
get_openai_output_parser | """Get the appropriate function output parser given the user functions.
Args:
functions: Sequence where element is a dictionary, a pydantic.BaseModel class,
or a Python function. If a dictionary is passed in, it is assumed to
already be a valid OpenAI function.
Returns:
... | def get_openai_output_parser(functions: Sequence[Union[Dict[str, Any], Type
[BaseModel], Callable]]) ->Union[BaseOutputParser,
BaseGenerationOutputParser]:
"""Get the appropriate function output parser given the user functions.
Args:
functions: Sequence where element is a dictionary, a pydantic... | Get the appropriate function output parser given the user functions.
Args:
functions: Sequence where element is a dictionary, a pydantic.BaseModel class,
or a Python function. If a dictionary is passed in, it is assumed to
already be a valid OpenAI function.
Returns:
A PydanticOutputFunctionsP... |
load | """Load data into Document objects.""" | @abstractmethod
def load(self) ->List[Document]:
"""Load data into Document objects.""" | Load data into Document objects. |
_chain_type | return 'llm_requests_chain' | @property
def _chain_type(self) ->str:
return 'llm_requests_chain' | null |
test_format_headers_api_key | """Test that the action headers is being created correctly."""
tool = ZapierNLARunAction(action_id='test', zapier_description='test',
params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper(
zapier_nla_api_key='test'))
headers = tool.api_wrapper._format_headers()
assert headers['Content-Type'] == 'applicat... | def test_format_headers_api_key() ->None:
"""Test that the action headers is being created correctly."""
tool = ZapierNLARunAction(action_id='test', zapier_description='test',
params_schema={'test': 'test'}, api_wrapper=ZapierNLAWrapper(
zapier_nla_api_key='test'))
headers = tool.api_wrapper... | Test that the action headers is being created correctly. |
load | """Load documents."""
try:
from azure.storage.blob import BlobClient
except ImportError as exc:
raise ImportError(
'Could not import azure storage blob python package. Please install it with `pip install azure-storage-blob`.'
) from exc
client = BlobClient.from_connection_string(conn_str=self.co... | def load(self) ->List[Document]:
"""Load documents."""
try:
from azure.storage.blob import BlobClient
except ImportError as exc:
raise ImportError(
'Could not import azure storage blob python package. Please install it with `pip install azure-storage-blob`.'
) from ex... | Load documents. |
update | """Change the expander's label and expanded state"""
if new_label is None:
new_label = self._label
if new_expanded is None:
new_expanded = self._expanded
if self._label == new_label and self._expanded == new_expanded:
return
self._label = new_label
self._expanded = new_expanded
self._container = self._paren... | def update(self, *, new_label: Optional[str]=None, new_expanded: Optional[
bool]=None) ->None:
"""Change the expander's label and expanded state"""
if new_label is None:
new_label = self._label
if new_expanded is None:
new_expanded = self._expanded
if self._label == new_label and sel... | Change the expander's label and expanded state |
_default_params | """Get the default parameters for calling Baichuan API."""
normal_params = {'model': self.model, 'temperature': self.temperature,
'top_p': self.top_p, 'top_k': self.top_k, 'with_search_enhance': self.
with_search_enhance}
return {**normal_params, **self.model_kwargs} | @property
def _default_params(self) ->Dict[str, Any]:
"""Get the default parameters for calling Baichuan API."""
normal_params = {'model': self.model, 'temperature': self.temperature,
'top_p': self.top_p, 'top_k': self.top_k, 'with_search_enhance':
self.with_search_enhance}
return {**normal_... | Get the default parameters for calling Baichuan API. |
validate_environment | """Validate that api key and python package exists in environment."""
if values['n'] < 1:
raise ValueError('n must be at least 1.')
if values['streaming'] and values['n'] > 1:
raise ValueError('Cannot stream results when n > 1.')
if values['streaming'] and values['best_of'] > 1:
raise ValueError('Cannot str... | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that api key and python package exists in environment."""
if values['n'] < 1:
raise ValueError('n must be at least 1.')
if values['streaming'] and values['n'] > 1:
raise ValueError('Cannot stream results when n... | Validate that api key and python package exists in environment. |
clear | """Clear session memory from Zep. Note that Zep is long-term storage for memory
and this is not advised unless you have specific data retention requirements.
"""
try:
self.zep_client.memory.delete_memory(self.session_id)
except NotFoundError:
logger.warning(
f'Session {self.session_id} n... | def clear(self) ->None:
"""Clear session memory from Zep. Note that Zep is long-term storage for memory
and this is not advised unless you have specific data retention requirements.
"""
try:
self.zep_client.memory.delete_memory(self.session_id)
except NotFoundError:
logger.wa... | Clear session memory from Zep. Note that Zep is long-term storage for memory
and this is not advised unless you have specific data retention requirements. |
on_text | """Do nothing"""
pass | def on_text(self, text: str, **kwargs: Any) ->None:
"""Do nothing"""
pass | Do nothing |
transform_documents | """Transform a list of documents.
Args:
documents: A sequence of Documents to be transformed.
Returns:
A list of transformed Documents.
""" | @abstractmethod
def transform_documents(self, documents: Sequence[Document], **kwargs: Any
) ->Sequence[Document]:
"""Transform a list of documents.
Args:
documents: A sequence of Documents to be transformed.
Returns:
A list of transformed Documents.
""" | Transform a list of documents.
Args:
documents: A sequence of Documents to be transformed.
Returns:
A list of transformed Documents. |
mock_requests_wrapper | return _MockTextRequestsWrapper() | @pytest.fixture
def mock_requests_wrapper() ->TextRequestsWrapper:
return _MockTextRequestsWrapper() | null |
add_texts | """Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
Returns:
List of ids from adding the texts into the vectorstore.
"""
names: List[str] = []
for text in texts:
doc_name = str(uuid.uuid4(... | def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]=
None, **kwargs: Any) ->List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
Returns:
List of ids from adding... | Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
Returns:
List of ids from adding the texts into the vectorstore. |
test_fireworks_streaming_stop_words | """Test stream completion with stop words."""
generator = llm.stream("Who's the best quarterback in the NFL?", stop=[','])
assert isinstance(generator, Generator)
last_token = ''
for token in generator:
last_token = token
assert isinstance(token, str)
assert last_token[-1] == ',' | @pytest.mark.scheduled
def test_fireworks_streaming_stop_words(llm: Fireworks) ->None:
"""Test stream completion with stop words."""
generator = llm.stream("Who's the best quarterback in the NFL?", stop=[',']
)
assert isinstance(generator, Generator)
last_token = ''
for token in generator:
... | Test stream completion with stop words. |
_convert_dict_to_message | role = _dict['role']
content = _dict['content']
if role == 'user':
return HumanMessage(content=content)
elif role == 'assistant':
return AIMessage(content=content)
elif role == 'system':
return SystemMessage(content=content)
else:
return ChatMessage(content=content, role=role) | @staticmethod
def _convert_dict_to_message(_dict: Mapping[str, Any]) ->BaseMessage:
role = _dict['role']
content = _dict['content']
if role == 'user':
return HumanMessage(content=content)
elif role == 'assistant':
return AIMessage(content=content)
elif role == 'system':
retur... | null |
create_llm_result | """Create the LLMResult from the choices and prompts."""
generations = []
for i, _ in enumerate(prompts):
sub_choices = choices[i:i + 1]
generations.append([Generation(text=choice.__dict__['choices'][0].text) for
choice in sub_choices])
llm_output = {'model': self.model}
return LLMResult(generations=gen... | def create_llm_result(self, choices: Any, prompts: List[str]) ->LLMResult:
"""Create the LLMResult from the choices and prompts."""
generations = []
for i, _ in enumerate(prompts):
sub_choices = choices[i:i + 1]
generations.append([Generation(text=choice.__dict__['choices'][0].
t... | Create the LLMResult from the choices and prompts. |
__init__ | """Initializes private fields."""
texttospeech = _import_google_cloud_texttospeech()
super().__init__(**kwargs)
self._client = texttospeech.TextToSpeechClient(client_info=get_client_info(
module='text-to-speech')) | def __init__(self, **kwargs: Any) ->None:
"""Initializes private fields."""
texttospeech = _import_google_cloud_texttospeech()
super().__init__(**kwargs)
self._client = texttospeech.TextToSpeechClient(client_info=
get_client_info(module='text-to-speech')) | Initializes private fields. |
test_copy_file_errs_outside_root_dir | """Test the FileCopy tool when a root dir is specified."""
with TemporaryDirectory() as temp_dir:
tool = CopyFileTool(root_dir=temp_dir)
result = tool.run({'source_path': '../source.txt', 'destination_path':
'../destination.txt'})
assert result == INVALID_PATH_TEMPLATE.format(arg_name='source_path',... | def test_copy_file_errs_outside_root_dir() ->None:
"""Test the FileCopy tool when a root dir is specified."""
with TemporaryDirectory() as temp_dir:
tool = CopyFileTool(root_dir=temp_dir)
result = tool.run({'source_path': '../source.txt',
'destination_path': '../destination.txt'})
... | Test the FileCopy tool when a root dir is specified. |
pull | """
Pulls an object from the hub and returns it as a LangChain object.
:param owner_repo_commit: The full name of the repo to pull from in the format of
`owner/repo:commit_hash`.
:param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service
if you have an api key set,... | def pull(owner_repo_commit: str, *, api_url: Optional[str]=None, api_key:
Optional[str]=None) ->Any:
"""
Pulls an object from the hub and returns it as a LangChain object.
:param owner_repo_commit: The full name of the repo to pull from in the format of
`owner/repo:commit_hash`.
:param api_... | Pulls an object from the hub and returns it as a LangChain object.
:param owner_repo_commit: The full name of the repo to pull from in the format of
`owner/repo:commit_hash`.
:param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service
if you have an api key set, or a localhost instance... |
next_thought | """
Generate the next thought given the problem description and the thoughts
generated so far.
""" | @abstractmethod
def next_thought(self, problem_description: str, thoughts_path: Tuple[str,
...]=(), **kwargs: Any) ->str:
"""
Generate the next thought given the problem description and the thoughts
generated so far.
""" | Generate the next thought given the problem description and the thoughts
generated so far. |
validate_url_scheme | """Check that the URL scheme is valid."""
parsed_url = urlparse(url)
if parsed_url.scheme not in ('http', 'https'):
raise ValueError("URL scheme must be 'http' or 'https'")
return url | @validator('url')
def validate_url_scheme(cls, url: str) ->str:
"""Check that the URL scheme is valid."""
parsed_url = urlparse(url)
if parsed_url.scheme not in ('http', 'https'):
raise ValueError("URL scheme must be 'http' or 'https'")
return url | Check that the URL scheme is valid. |
fetch_results | self.fetch_page_result(queue)
while self.find_options.get('pageState'):
self.fetch_page_result(queue)
queue.put(None) | def fetch_results(self, queue: Queue):
self.fetch_page_result(queue)
while self.find_options.get('pageState'):
self.fetch_page_result(queue)
queue.put(None) | null |
_get_elements | from unstructured.partition.auto import partition
return partition(file=self.file, **self.unstructured_kwargs) | def _get_elements(self) ->List:
from unstructured.partition.auto import partition
return partition(file=self.file, **self.unstructured_kwargs) | null |
zep_chat | mock_zep_client: ZepClient = mocker.patch('zep_python.ZepClient', autospec=True
)
mock_zep_client.memory = mocker.patch('zep_python.memory.client.MemoryClient',
autospec=True)
zep_chat: ZepChatMessageHistory = ZepChatMessageHistory('test_session',
'http://localhost:8000')
zep_chat.zep_client = mock_zep_clie... | @pytest.fixture
@pytest.mark.requires('zep_python')
def zep_chat(mocker: MockerFixture) ->ZepChatMessageHistory:
mock_zep_client: ZepClient = mocker.patch('zep_python.ZepClient',
autospec=True)
mock_zep_client.memory = mocker.patch(
'zep_python.memory.client.MemoryClient', autospec=True)
zep... | null |
test_search | zep_chat.search('test query')
zep_chat.zep_client.memory.search_memory.assert_called_once_with('test_session'
, mocker.ANY, limit=None) | @pytest.mark.requires('zep_python')
def test_search(mocker: MockerFixture, zep_chat: ZepChatMessageHistory) ->None:
zep_chat.search('test query')
zep_chat.zep_client.memory.search_memory.assert_called_once_with(
'test_session', mocker.ANY, limit=None) | null |
__init__ | self.host = host
self.aiosession = aiosession
if self.host is None or len(self.host) < 3:
raise ValueError(' param `host` must be set to a valid url')
self._batch_size = 128 | def __init__(self, host: str='http://localhost:7797/v1', aiosession:
Optional[aiohttp.ClientSession]=None) ->None:
self.host = host
self.aiosession = aiosession
if self.host is None or len(self.host) < 3:
raise ValueError(' param `host` must be set to a valid url')
self._batch_size = 128 | null |
_value_serializer | """Serialize a value."""
return json.dumps(value).encode() | def _value_serializer(value: Sequence[float]) ->bytes:
"""Serialize a value."""
return json.dumps(value).encode() | Serialize a value. |
_get_elements | """Get elements."""
from unstructured.partition.auto import partition
try:
import boto3
except ImportError:
raise ImportError(
'Could not import `boto3` python package. Please install it with `pip install boto3`.'
)
s3 = boto3.client('s3', region_name=self.region_name, api_version=self.
api_... | def _get_elements(self) ->List:
"""Get elements."""
from unstructured.partition.auto import partition
try:
import boto3
except ImportError:
raise ImportError(
'Could not import `boto3` python package. Please install it with `pip install boto3`.'
)
s3 = boto3.c... | Get elements. |
_import_typesense | from langchain_community.vectorstores.typesense import Typesense
return Typesense | def _import_typesense() ->Any:
from langchain_community.vectorstores.typesense import Typesense
return Typesense | null |
_openai_v1_installed | try:
return is_openai_v1()
except Exception as _:
return False | def _openai_v1_installed() ->bool:
try:
return is_openai_v1()
except Exception as _:
return False | null |
__init__ | self.fail_starts_with = fail_starts_with | def __init__(self, fail_starts_with: str) ->None:
self.fail_starts_with = fail_starts_with | null |
test_include_types | """Test include types from schema."""
url = os.environ.get('NEO4J_URI')
username = os.environ.get('NEO4J_USERNAME')
password = os.environ.get('NEO4J_PASSWORD')
assert url is not None
assert username is not None
assert password is not None
graph = Neo4jGraph(url=url, username=username, password=password)
graph.query('MA... | def test_include_types() ->None:
"""Test include types from schema."""
url = os.environ.get('NEO4J_URI')
username = os.environ.get('NEO4J_USERNAME')
password = os.environ.get('NEO4J_PASSWORD')
assert url is not None
assert username is not None
assert password is not None
graph = Neo4jGra... | Test include types from schema. |
_get_default_output_parser | return ReActOutputParser() | @classmethod
def _get_default_output_parser(cls, **kwargs: Any) ->AgentOutputParser:
return ReActOutputParser() | null |
embed_documents | """Compute document embeddings using an OctoAI instruct model."""
texts = list(map(lambda x: x.replace('\n', ' '), texts))
return self._compute_embeddings(texts, self.embed_instruction) | def embed_documents(self, texts: List[str]) ->List[List[float]]:
"""Compute document embeddings using an OctoAI instruct model."""
texts = list(map(lambda x: x.replace('\n', ' '), texts))
return self._compute_embeddings(texts, self.embed_instruction) | Compute document embeddings using an OctoAI instruct model. |
_import_vectara | from langchain_community.vectorstores.vectara import Vectara
return Vectara | def _import_vectara() ->Any:
from langchain_community.vectorstores.vectara import Vectara
return Vectara | null |
parser | """Parse LLM output into a pydantic object."""
if cls.pydantic_model is None:
raise NotImplementedError(
f'pydantic_model not implemented for {cls.__name__}')
return PydanticOutputParser(pydantic_object=cls.pydantic_model) | @classmethod
def parser(cls) ->PydanticOutputParser:
"""Parse LLM output into a pydantic object."""
if cls.pydantic_model is None:
raise NotImplementedError(
f'pydantic_model not implemented for {cls.__name__}')
return PydanticOutputParser(pydantic_object=cls.pydantic_model) | Parse LLM output into a pydantic object. |
convert_python_function_to_ernie_function | """Convert a Python function to an Ernie function-calling API compatible dict.
Assumes the Python function has type hints and a docstring with a description. If
the docstring has Google Python style argument descriptions, these will be
included as well.
"""
description, arg_descriptions = _pars... | def convert_python_function_to_ernie_function(function: Callable) ->Dict[
str, Any]:
"""Convert a Python function to an Ernie function-calling API compatible dict.
Assumes the Python function has type hints and a docstring with a description. If
the docstring has Google Python style argument descri... | Convert a Python function to an Ernie function-calling API compatible dict.
Assumes the Python function has type hints and a docstring with a description. If
the docstring has Google Python style argument descriptions, these will be
included as well. |
visit_structured_query | if structured_query.filter is None:
kwargs = {}
else:
kwargs = {'filter': structured_query.filter.accept(self)}
return structured_query.query, kwargs | def visit_structured_query(self, structured_query: StructuredQuery) ->Tuple[
str, dict]:
if structured_query.filter is None:
kwargs = {}
else:
kwargs = {'filter': structured_query.filter.accept(self)}
return structured_query.query, kwargs | null |
_get_default_document_prompt | return PromptTemplate(input_variables=['page_content'], template=
'{page_content}') | def _get_default_document_prompt() ->PromptTemplate:
return PromptTemplate(input_variables=['page_content'], template=
'{page_content}') | null |
int | return int(item) | def int(self, item: Any) ->int:
return int(item) | null |
add_texts | """Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids:
Optional list of ids to associate with the texts. Ids have t... | def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]=
None, ids: Optional[Sequence[str]]=None, batch_size: int=64, **kwargs: Any
) ->List[str]:
"""Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vector... | Run more texts through the embeddings and add to the vectorstore.
Args:
texts: Iterable of strings to add to the vectorstore.
metadatas: Optional list of metadatas associated with the texts.
ids:
Optional list of ids to associate with the texts. Ids have to be
uuid-like strings.
batch_s... |
_generate_reaction | """React to a given observation or dialogue act."""
prompt = PromptTemplate.from_template('{agent_summary_description}' +
"""
It is {current_time}.""" +
"""
{agent_name}'s status: {agent_status}""" +
"""
Summary of relevant context from {agent_name}'s memory:""" +
"""
{relevant_memories}""" +
"""
Mo... | def _generate_reaction(self, observation: str, suffix: str, now: Optional[
datetime]=None) ->str:
"""React to a given observation or dialogue act."""
prompt = PromptTemplate.from_template('{agent_summary_description}' +
"""
It is {current_time}.""" +
"""
{agent_name}'s status: {agent_status}... | React to a given observation or dialogue act. |
_identifying_params | """Get the identifying parameters."""
return {'model_name': self.model, 'aviary_url': self.aviary_url} | @property
def _identifying_params(self) ->Mapping[str, Any]:
"""Get the identifying parameters."""
return {'model_name': self.model, 'aviary_url': self.aviary_url} | Get the identifying parameters. |
_get_doc_cls | """Get docarray Document class describing the schema of DocIndex."""
from docarray import BaseDoc
from docarray.typing import NdArray
class DocArrayDoc(BaseDoc):
text: Optional[str]
embedding: Optional[NdArray] = Field(**embeddings_params)
metadata: Optional[dict]
return DocArrayDoc | @staticmethod
def _get_doc_cls(**embeddings_params: Any) ->Type['BaseDoc']:
"""Get docarray Document class describing the schema of DocIndex."""
from docarray import BaseDoc
from docarray.typing import NdArray
class DocArrayDoc(BaseDoc):
text: Optional[str]
embedding: Optional[NdArray]... | Get docarray Document class describing the schema of DocIndex. |
on_llm_new_token | """Do nothing when a new token is generated."""
pass | def on_llm_new_token(self, token: str, **kwargs: Any) ->None:
"""Do nothing when a new token is generated."""
pass | Do nothing when a new token is generated. |
test_visit_comparison_in | comp = Comparison(comparator=Comparator.IN, attribute='name', value='foo')
expected = {'name': {'$in': ['foo']}}
actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
assert expected == actual | def test_visit_comparison_in() ->None:
comp = Comparison(comparator=Comparator.IN, attribute='name', value='foo')
expected = {'name': {'$in': ['foo']}}
actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
assert expected == actual | null |
foo | """Docstring
Args:
bar: int
baz: str
"""
raise NotImplementedError() | def foo(bar: int, baz: str) ->str:
"""Docstring
Args:
bar: int
baz: str
"""
raise NotImplementedError() | Docstring
Args:
bar: int
baz: str |
_generate | raise NotImplementedError | def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]=
None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any
) ->ChatResult:
raise NotImplementedError | null |
_parse_filename_from_url | """Parse the filename from an url.
Args:
url: Url to parse the filename from.
Returns:
The filename.
Raises:
ValueError: If the filename could not be parsed.
"""
filename_matches = re.search('filename%2A%3DUTF-8%27%27(.+)', url)
if filename_matches:... | def _parse_filename_from_url(self, url: str) ->str:
"""Parse the filename from an url.
Args:
url: Url to parse the filename from.
Returns:
The filename.
Raises:
ValueError: If the filename could not be parsed.
"""
filename_matches = re.searc... | Parse the filename from an url.
Args:
url: Url to parse the filename from.
Returns:
The filename.
Raises:
ValueError: If the filename could not be parsed. |
__init__ | self.connection_string = connection_string
self.engine = create_engine(connection_string, echo=False)
self.session_id_field_name = session_id_field_name
self.converter = custom_message_converter or DefaultMessageConverter(table_name
)
self.sql_model_class = self.converter.get_sql_model_class()
if not hasattr(self.s... | def __init__(self, session_id: str, connection_string: str, table_name: str
='message_store', session_id_field_name: str='session_id',
custom_message_converter: Optional[BaseMessageConverter]=None):
self.connection_string = connection_string
self.engine = create_engine(connection_string, echo=False)
... | null |
get_noop_manager | """Return a manager that doesn't perform any operations.
Returns:
BaseRunManager: The noop manager.
"""
return cls(run_id=uuid.uuid4(), handlers=[], inheritable_handlers=[], tags=
[], inheritable_tags=[], metadata={}, inheritable_metadata={}) | @classmethod
def get_noop_manager(cls: Type[BRM]) ->BRM:
"""Return a manager that doesn't perform any operations.
Returns:
BaseRunManager: The noop manager.
"""
return cls(run_id=uuid.uuid4(), handlers=[], inheritable_handlers=[],
tags=[], inheritable_tags=[], metadata={}, i... | Return a manager that doesn't perform any operations.
Returns:
BaseRunManager: The noop manager. |
test_batch_size | llm = FakeListLLM(responses=['foo'] * 3)
with collect_runs() as cb:
llm.batch(['foo', 'bar', 'foo'], {'callbacks': [cb]})
assert all([((r.extra or {}).get('batch_size') == 3) for r in cb.
traced_runs])
assert len(cb.traced_runs) == 3
llm = FakeListLLM(responses=['foo'])
with collect_runs() as cb:
... | def test_batch_size() ->None:
llm = FakeListLLM(responses=['foo'] * 3)
with collect_runs() as cb:
llm.batch(['foo', 'bar', 'foo'], {'callbacks': [cb]})
assert all([((r.extra or {}).get('batch_size') == 3) for r in cb.
traced_runs])
assert len(cb.traced_runs) == 3
llm = Fa... | null |
validate_environment | """Validate that api key and python package exists in environment."""
values['openai_api_key'] = get_from_dict_or_env(values, 'openai_api_key',
'OPENAI_API_KEY')
values['openai_api_base'] = get_from_dict_or_env(values, 'openai_api_base',
'OPENAI_API_BASE', default='')
values['openai_proxy'] = get_from_dict_or_e... | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that api key and python package exists in environment."""
values['openai_api_key'] = get_from_dict_or_env(values,
'openai_api_key', 'OPENAI_API_KEY')
values['openai_api_base'] = get_from_dict_or_env(values,
'op... | Validate that api key and python package exists in environment. |
_generate_inputs | """Create the input for the triton inference server."""
query = np.array(prompt).astype(object)
request_output_len = np.array([tokens]).astype(np.uint32).reshape((1, -1))
runtime_top_k = np.array([top_k]).astype(np.uint32).reshape((1, -1))
runtime_top_p = np.array([top_p]).astype(np.float32).reshape((1, -1))
temperatur... | def _generate_inputs(self, prompt: Sequence[Sequence[str]], tokens: int=300,
temperature: float=1.0, top_k: float=1, top_p: float=0, beam_width: int
=1, repetition_penalty: float=1, length_penalty: float=1.0, stream:
bool=True) ->List[grpcclient.InferRequestedOutput]:
"""Create the input for the triton ... | Create the input for the triton inference server. |
__iter__ | yield from self._children | def __iter__(self) ->Iterator[AsyncIterator[T]]:
yield from self._children | null |
update | """Update cache based on prompt and llm_string."""
for gen in return_val:
if not isinstance(gen, Generation):
raise ValueError(
f'UpstashRedisCache supports caching of normal LLM generations, got {type(gen)}'
)
if isinstance(gen, ChatGeneration):
warnings.warn(
... | def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE
) ->None:
"""Update cache based on prompt and llm_string."""
for gen in return_val:
if not isinstance(gen, Generation):
raise ValueError(
f'UpstashRedisCache supports caching of normal LLM generati... | Update cache based on prompt and llm_string. |
__call__ | results: List[Dict[str, Any]] = []
for fields in fields_collection:
results.append(self.generator({'fields': fields, 'preferences': self.
sentence_preferences}))
return results | def __call__(self, fields_collection: List[List[Any]]) ->List[Dict[str, Any]]:
results: List[Dict[str, Any]] = []
for fields in fields_collection:
results.append(self.generator({'fields': fields, 'preferences':
self.sentence_preferences}))
return results | null |
transform_output | """Transforms the output from the model to string that
the LLM class expects.
""" | @abstractmethod
def transform_output(self, output: bytes) ->OUTPUT_TYPE:
"""Transforms the output from the model to string that
the LLM class expects.
""" | Transforms the output from the model to string that
the LLM class expects. |
_import_databricks_chat | from langchain_community.chat_models.databricks import ChatDatabricks
return ChatDatabricks | def _import_databricks_chat() ->Any:
from langchain_community.chat_models.databricks import ChatDatabricks
return ChatDatabricks | null |
validate_environment | """Validate that api key and endpoint exists in environment."""
azure_cogs_key = get_from_dict_or_env(values, 'azure_cogs_key',
'AZURE_COGS_KEY')
azure_cogs_endpoint = get_from_dict_or_env(values, 'azure_cogs_endpoint',
'AZURE_COGS_ENDPOINT')
try:
import azure.ai.textanalytics as sdk
from azure.core.cre... | @root_validator(pre=True)
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that api key and endpoint exists in environment."""
azure_cogs_key = get_from_dict_or_env(values, 'azure_cogs_key',
'AZURE_COGS_KEY')
azure_cogs_endpoint = get_from_dict_or_env(values,
'azure_cogs_endpo... | Validate that api key and endpoint exists in environment. |
get_relative_path | """Get the path of the file as a relative path to the package directory."""
if isinstance(file, str):
file = Path(file)
return str(file.relative_to(relative_to)) | def get_relative_path(file: Union[Path, str], *, relative_to: Path=PACKAGE_DIR
) ->str:
"""Get the path of the file as a relative path to the package directory."""
if isinstance(file, str):
file = Path(file)
return str(file.relative_to(relative_to)) | Get the path of the file as a relative path to the package directory. |
from_text | """Create graph index from text."""
if self.llm is None:
raise ValueError('llm should not be None')
graph = self.graph_type()
chain = LLMChain(llm=self.llm, prompt=prompt)
output = chain.predict(text=text)
knowledge = parse_triples(output)
for triple in knowledge:
graph.add_triple(triple)
return graph | def from_text(self, text: str, prompt: BasePromptTemplate=
KNOWLEDGE_TRIPLE_EXTRACTION_PROMPT) ->NetworkxEntityGraph:
"""Create graph index from text."""
if self.llm is None:
raise ValueError('llm should not be None')
graph = self.graph_type()
chain = LLMChain(llm=self.llm, prompt=prompt)
... | Create graph index from text. |
test_sentence_transformer_db_query | """Test sentence_transformer similarity search."""
embedding = SentenceTransformerEmbeddings()
texts = ["we will foo your bar until you can't foo any more",
'the quick brown fox jumped over the lazy dog']
query = 'what the foo is a bar?'
query_vector = embedding.embed_query(query)
assert len(query_vector) == 384
db... | def test_sentence_transformer_db_query() ->None:
"""Test sentence_transformer similarity search."""
embedding = SentenceTransformerEmbeddings()
texts = ["we will foo your bar until you can't foo any more",
'the quick brown fox jumped over the lazy dog']
query = 'what the foo is a bar?'
query... | Test sentence_transformer similarity search. |
_load_prompt_from_file | """Load prompt from file."""
if isinstance(file, str):
file_path = Path(file)
else:
file_path = file
if file_path.suffix == '.json':
with open(file_path) as f:
config = json.load(f)
elif file_path.suffix == '.yaml':
with open(file_path, 'r') as f:
config = yaml.safe_load(f)
else:
rai... | def _load_prompt_from_file(file: Union[str, Path]) ->BasePromptTemplate:
"""Load prompt from file."""
if isinstance(file, str):
file_path = Path(file)
else:
file_path = file
if file_path.suffix == '.json':
with open(file_path) as f:
config = json.load(f)
elif file... | Load prompt from file. |
_run | return f'{arg1} {arg2} {arg3}' | def _run(self, arg1: int, arg2: bool, arg3: Optional[dict]=None) ->str:
return f'{arg1} {arg2} {arg3}' | null |
librarian_rag | return get_docs_message(x['message']) | def librarian_rag(x):
return get_docs_message(x['message']) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.