method_name stringlengths 1 78 | method_body stringlengths 3 9.66k | full_code stringlengths 31 10.7k | docstring stringlengths 4 4.74k ⌀ |
|---|---|---|---|
_create_message_dicts | params = self._client_params
if stop is not None:
if 'stop' in params:
raise ValueError('`stop` found in both the input and default params.')
params['stop'] = stop
message_dicts = [convert_message_to_dict(m) for m in messages]
return message_dicts, params | def _create_message_dicts(self, messages: List[BaseMessage], stop: Optional
[List[str]]) ->Tuple[List[Dict[str, Any]], Dict[str, Any]]:
params = self._client_params
if stop is not None:
if 'stop' in params:
raise ValueError(
'`stop` found in both the input and default par... | null |
test_structured_tool_types_parsed | """Test the non-primitive types are correctly passed to structured tools."""
class SomeEnum(Enum):
A = 'a'
B = 'b'
class SomeBaseModel(BaseModel):
foo: str
@tool
def structured_tool(some_enum: SomeEnum, some_base_model: SomeBaseModel
) ->dict:
"""Return the arguments directly."""
return {'some_e... | def test_structured_tool_types_parsed() ->None:
"""Test the non-primitive types are correctly passed to structured tools."""
class SomeEnum(Enum):
A = 'a'
B = 'b'
class SomeBaseModel(BaseModel):
foo: str
@tool
def structured_tool(some_enum: SomeEnum, some_base_model: Som... | Test the non-primitive types are correctly passed to structured tools. |
input_keys | """Input keys this chain returns."""
return self.input_variables | @property
def input_keys(self) ->List[str]:
"""Input keys this chain returns."""
return self.input_variables | Input keys this chain returns. |
_can_use_selection_scorer | """
Returns whether the chain can use the selection scorer to score responses or not.
"""
return self.selection_scorer is not None and self.selection_scorer_activated | def _can_use_selection_scorer(self) ->bool:
"""
Returns whether the chain can use the selection scorer to score responses or not.
"""
return (self.selection_scorer is not None and self.
selection_scorer_activated) | Returns whether the chain can use the selection scorer to score responses or not. |
__init__ | """Initialize the run manager.
Args:
run_id (UUID): The ID of the run.
handlers (List[BaseCallbackHandler]): The list of handlers.
inheritable_handlers (List[BaseCallbackHandler]):
The list of inheritable handlers.
parent_run_id (UUID, optional): ... | def __init__(self, *, run_id: UUID, handlers: List[BaseCallbackHandler],
inheritable_handlers: List[BaseCallbackHandler], parent_run_id:
Optional[UUID]=None, tags: Optional[List[str]]=None, inheritable_tags:
Optional[List[str]]=None, metadata: Optional[Dict[str, Any]]=None,
inheritable_metadata: Optiona... | Initialize the run manager.
Args:
run_id (UUID): The ID of the run.
handlers (List[BaseCallbackHandler]): The list of handlers.
inheritable_handlers (List[BaseCallbackHandler]):
The list of inheritable handlers.
parent_run_id (UUID, optional): The ID of the parent run.
Defaults to None.... |
test_person_with_kwargs | person = Person(secret='hello')
assert dumps(person, separators=(',', ':')) == snapshot | def test_person_with_kwargs(snapshot: Any) ->None:
person = Person(secret='hello')
assert dumps(person, separators=(',', ':')) == snapshot | null |
similarity_search | """Run similarity search using Clarifai.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query and score for each
"""
docs_and_scores = self.similarity_search_... | def similarity_search(self, query: str, k: int=4, **kwargs: Any) ->List[
Document]:
"""Run similarity search using Clarifai.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most s... | Run similarity search using Clarifai.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query and score for each |
create_table | """Create a new table."""
if self.awadb_client is None:
return False
ret = self.awadb_client.Create(table_name)
if ret:
self.using_table_name = table_name
return ret | def create_table(self, table_name: str, **kwargs: Any) ->bool:
"""Create a new table."""
if self.awadb_client is None:
return False
ret = self.awadb_client.Create(table_name)
if ret:
self.using_table_name = table_name
return ret | Create a new table. |
_import_ainetwork_owner | from langchain_community.tools.ainetwork.owner import AINOwnerOps
return AINOwnerOps | def _import_ainetwork_owner() ->Any:
from langchain_community.tools.ainetwork.owner import AINOwnerOps
return AINOwnerOps | null |
__init__ | super().__init__(pydantic_object=LineList) | def __init__(self) ->None:
super().__init__(pydantic_object=LineList) | null |
test_create_alibabacloud_opensearch | opensearch = create_alibabacloud_opensearch()
time.sleep(1)
output = opensearch.similarity_search('foo', k=10)
assert len(output) == 3 | def test_create_alibabacloud_opensearch() ->None:
opensearch = create_alibabacloud_opensearch()
time.sleep(1)
output = opensearch.similarity_search('foo', k=10)
assert len(output) == 3 | null |
test_default_regex_matching | prediction = 'Mindy is the CTO'
reference = '^Mindy.*CTO$'
result = regex_match_string_evaluator.evaluate_strings(prediction=
prediction, reference=reference)
assert result['score'] == 1.0
reference = '^Mike.*CEO$'
result = regex_match_string_evaluator.evaluate_strings(prediction=
prediction, reference=referenc... | def test_default_regex_matching(regex_match_string_evaluator:
RegexMatchStringEvaluator) ->None:
prediction = 'Mindy is the CTO'
reference = '^Mindy.*CTO$'
result = regex_match_string_evaluator.evaluate_strings(prediction=
prediction, reference=reference)
assert result['score'] == 1.0
re... | null |
_run | """Use the tool."""
from langchain.chains.retrieval_qa.base import RetrievalQA
chain = RetrievalQA.from_chain_type(self.llm, retriever=self.vectorstore.
as_retriever())
return chain.run(query, callbacks=run_manager.get_child() if run_manager else
None) | def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun]
=None) ->str:
"""Use the tool."""
from langchain.chains.retrieval_qa.base import RetrievalQA
chain = RetrievalQA.from_chain_type(self.llm, retriever=self.
vectorstore.as_retriever())
return chain.run(query, callbacks... | Use the tool. |
test_prompt | messages = [SystemMessage(content='sys-msg'), HumanMessage(content=
'usr-msg-1'), AIMessage(content='ai-msg-1'), HumanMessage(content=
'usr-msg-2')]
actual = model.predict_messages(messages).content
expected = """### System:
sys-msg
### User:
usr-msg-1
### Assistant:
ai-msg-1
### User:
usr-msg-2
"""
assert ... | def test_prompt(model: Orca) ->None:
messages = [SystemMessage(content='sys-msg'), HumanMessage(content=
'usr-msg-1'), AIMessage(content='ai-msg-1'), HumanMessage(content=
'usr-msg-2')]
actual = model.predict_messages(messages).content
expected = """### System:
sys-msg
### User:
usr-msg-1
... | null |
_arg | self.write(t.arg)
if t.annotation:
self.write(': ')
self.dispatch(t.annotation) | def _arg(self, t):
self.write(t.arg)
if t.annotation:
self.write(': ')
self.dispatch(t.annotation) | null |
invoke | if isinstance(input, BaseMessage):
return self._call_with_config(lambda inner_input: self.parse_result([
ChatGeneration(message=inner_input)]), input, config, run_type='parser'
)
else:
return self._call_with_config(lambda inner_input: self.parse_result([
Generation(text=inner_input)]), i... | def invoke(self, input: Union[str, BaseMessage], config: Optional[
RunnableConfig]=None) ->T:
if isinstance(input, BaseMessage):
return self._call_with_config(lambda inner_input: self.parse_result
([ChatGeneration(message=inner_input)]), input, config,
run_type='parser')
else... | null |
mset | """Set the values for the given keys.
Args:
key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs.
Returns:
None
"""
for key, value in key_value_pairs:
self.store[key] = value | def mset(self, key_value_pairs: Sequence[Tuple[str, V]]) ->None:
"""Set the values for the given keys.
Args:
key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs.
Returns:
None
"""
for key, value in key_value_pairs:
self.store[key] = ... | Set the values for the given keys.
Args:
key_value_pairs (Sequence[Tuple[str, V]]): A sequence of key-value pairs.
Returns:
None |
test_load_uses_page_content_column_to_create_document_text | import xorbits.pandas as pd
data = {'text': ['Hello', 'World'], 'author': ['Alice', 'Bob'], 'date': [
'2022-01-01', '2022-01-02']}
sample_data_frame = pd.DataFrame(data)
sample_data_frame = sample_data_frame.rename(columns={'text':
'dummy_test_column'})
loader = XorbitsLoader(sample_data_frame, page_content_col... | @pytest.mark.skipif(not xorbits_installed, reason='xorbits not installed')
def test_load_uses_page_content_column_to_create_document_text() ->None:
import xorbits.pandas as pd
data = {'text': ['Hello', 'World'], 'author': ['Alice', 'Bob'], 'date':
['2022-01-01', '2022-01-02']}
sample_data_frame = pd... | null |
_load_single_chat_session | """
Convert an individual LangSmith LLM run to a ChatSession.
:param llm_run: The LLM run object.
:return: A chat session representing the run's data.
"""
chat_session = LangSmithRunChatLoader._get_messages_from_llm_run(llm_run)
functions = LangSmithRunChatLoader._get_functions_from_llm... | def _load_single_chat_session(self, llm_run: 'Run') ->ChatSession:
"""
Convert an individual LangSmith LLM run to a ChatSession.
:param llm_run: The LLM run object.
:return: A chat session representing the run's data.
"""
chat_session = LangSmithRunChatLoader._get_messages_from_... | Convert an individual LangSmith LLM run to a ChatSession.
:param llm_run: The LLM run object.
:return: A chat session representing the run's data. |
test_from_documents | input_docs = [Document(page_content='I have a pen.'), Document(page_content
='Do you have a pen?'), Document(page_content='I have a bag.')]
bm25_retriever = BM25Retriever.from_documents(documents=input_docs)
assert len(bm25_retriever.docs) == 3
assert bm25_retriever.vectorizer.doc_len == [4, 5, 4] | @pytest.mark.requires('rank_bm25')
def test_from_documents() ->None:
input_docs = [Document(page_content='I have a pen.'), Document(
page_content='Do you have a pen?'), Document(page_content=
'I have a bag.')]
bm25_retriever = BM25Retriever.from_documents(documents=input_docs)
assert len(bm2... | null |
on_text | """Do nothing"""
pass | def on_text(self, text: str, **kwargs: Any) ->None:
"""Do nothing"""
pass | Do nothing |
test_usearch_from_documents | """Test from_documents constructor."""
texts = ['foo', 'bar', 'baz']
docs = [Document(page_content=t, metadata={'a': 'b'}) for t in texts]
docsearch = USearch.from_documents(docs, FakeEmbeddings())
output = docsearch.similarity_search('foo', k=1)
assert output == [Document(page_content='foo', metadata={'a': 'b'})] | def test_usearch_from_documents() ->None:
"""Test from_documents constructor."""
texts = ['foo', 'bar', 'baz']
docs = [Document(page_content=t, metadata={'a': 'b'}) for t in texts]
docsearch = USearch.from_documents(docs, FakeEmbeddings())
output = docsearch.similarity_search('foo', k=1)
assert ... | Test from_documents constructor. |
test_yellowbrick_with_score | """Test end to end construction and search with scores and IDs."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i} for i in range(len(texts))]
docsearch = _yellowbrick_vector_from_texts(metadatas=metadatas)
output = docsearch.similarity_search_with_score('foo', k=3)
docs = [o[0] for o in output]
distances = [o[1... | @pytest.mark.requires('yb-vss')
def test_yellowbrick_with_score() ->None:
"""Test end to end construction and search with scores and IDs."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i} for i in range(len(texts))]
docsearch = _yellowbrick_vector_from_texts(metadatas=metadatas)
output = doc... | Test end to end construction and search with scores and IDs. |
with_config | """
Bind config to a Runnable, returning a new Runnable.
"""
return RunnableBinding(bound=self, config=cast(RunnableConfig, {**config or
{}, **kwargs}), kwargs={}) | def with_config(self, config: Optional[RunnableConfig]=None, **kwargs: Any
) ->Runnable[Input, Output]:
"""
Bind config to a Runnable, returning a new Runnable.
"""
return RunnableBinding(bound=self, config=cast(RunnableConfig, {**
config or {}, **kwargs}), kwargs={}) | Bind config to a Runnable, returning a new Runnable. |
_call | """Call out to NLPCloud's create endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Not supported by this interface (pass in init method)
Returns:
The string generated by the model.
Example:
.. code-block:: python
... | def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager:
Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str:
"""Call out to NLPCloud's create endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Not supported by this interface (pass in ini... | Call out to NLPCloud's create endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Not supported by this interface (pass in init method)
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = nlpcloud("Tell me a joke.") |
validate_environment | """Validate that access token exists in environment."""
values['access_token'] = get_from_dict_or_env(values, 'access_token',
'GITHUB_PERSONAL_ACCESS_TOKEN')
return values | @root_validator(pre=True)
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that access token exists in environment."""
values['access_token'] = get_from_dict_or_env(values, 'access_token',
'GITHUB_PERSONAL_ACCESS_TOKEN')
return values | Validate that access token exists in environment. |
_call | """Simpler interface.""" | @abstractmethod
def _call(self, messages: List[BaseMessage], stop: Optional[List[str]]=None,
run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str:
"""Simpler interface.""" | Simpler interface. |
_generate | if self.streaming:
stream_iter = self._stream(messages=messages, stop=stop, run_manager=
run_manager, **kwargs)
return generate_from_stream(stream_iter)
message_dicts, params = self._create_message_dicts(messages, stop)
params = {**params, **kwargs}
response = self.completion_with_retry(messages=message... | def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]=
None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any
) ->ChatResult:
if self.streaming:
stream_iter = self._stream(messages=messages, stop=stop,
run_manager=run_manager, **kwargs)
ret... | null |
load | """Load data into Document objects.
Returns:
List of Documents.
"""
if self.load_all_recursively:
soup_info = self.scrape()
self.folder_path = self._get_folder_path(soup_info)
relative_paths = self._get_paths(soup_info)
documents = []
for path in relative_paths:
... | def load(self) ->List[Document]:
"""Load data into Document objects.
Returns:
List of Documents.
"""
if self.load_all_recursively:
soup_info = self.scrape()
self.folder_path = self._get_folder_path(soup_info)
relative_paths = self._get_paths(soup_info)
... | Load data into Document objects.
Returns:
List of Documents. |
test_unstructured_org_mode_loader | """Test unstructured loader."""
file_path = os.path.join(EXAMPLE_DIRECTORY, 'README.org')
loader = UnstructuredOrgModeLoader(str(file_path))
docs = loader.load()
assert len(docs) == 1 | def test_unstructured_org_mode_loader() ->None:
"""Test unstructured loader."""
file_path = os.path.join(EXAMPLE_DIRECTORY, 'README.org')
loader = UnstructuredOrgModeLoader(str(file_path))
docs = loader.load()
assert len(docs) == 1 | Test unstructured loader. |
embed_documents | """Call out to Jina's embedding endpoint.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
return self._embed(texts) | def embed_documents(self, texts: List[str]) ->List[List[float]]:
"""Call out to Jina's embedding endpoint.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
return self._embed(texts) | Call out to Jina's embedding endpoint.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text. |
default_databricks_vector_search | return DatabricksVectorSearch(index, embedding=DEFAULT_EMBEDDING_MODEL,
text_column=DEFAULT_TEXT_COLUMN) | def default_databricks_vector_search(index: MagicMock
) ->DatabricksVectorSearch:
return DatabricksVectorSearch(index, embedding=DEFAULT_EMBEDDING_MODEL,
text_column=DEFAULT_TEXT_COLUMN) | null |
refresh_schema | """Refreshes the graph schema information."""
pass | def refresh_schema(self) ->None:
"""Refreshes the graph schema information."""
pass | Refreshes the graph schema information. |
format_response_payload | """Formats response"""
return json.loads(output)['output'] | def format_response_payload(self, output: bytes) ->str:
"""Formats response"""
return json.loads(output)['output'] | Formats response |
_search | search_url = self._build_search_url(query)
response = requests.get(search_url, headers=self._headers)
if response.status_code != 200:
raise Exception(f'Error in search request: {response}')
return json.loads(response.text)['value'] | def _search(self, query: str) ->List[dict]:
search_url = self._build_search_url(query)
response = requests.get(search_url, headers=self._headers)
if response.status_code != 200:
raise Exception(f'Error in search request: {response}')
return json.loads(response.text)['value'] | null |
_create_connection_alias | """Create the connection to the Milvus server."""
from pymilvus import MilvusException, connections
host: str = connection_args.get('host', None)
port: Union[str, int] = connection_args.get('port', None)
address: str = connection_args.get('address', None)
uri: str = connection_args.get('uri', None)
user = connection_ar... | def _create_connection_alias(self, connection_args: dict) ->str:
"""Create the connection to the Milvus server."""
from pymilvus import MilvusException, connections
host: str = connection_args.get('host', None)
port: Union[str, int] = connection_args.get('port', None)
address: str = connection_args.... | Create the connection to the Milvus server. |
__ror__ | if isinstance(other, RunnableSequence):
return RunnableSequence(other.first, *other.middle, other.last, self.
first, *self.middle, self.last, name=other.name or self.name)
else:
return RunnableSequence(coerce_to_runnable(other), self.first, *self.
middle, self.last, name=self.name) | def __ror__(self, other: Union[Runnable[Other, Any], Callable[[Other], Any],
Callable[[Iterator[Other]], Iterator[Any]], Mapping[str, Union[Runnable
[Other, Any], Callable[[Other], Any], Any]]]) ->RunnableSerializable[
Other, Output]:
if isinstance(other, RunnableSequence):
return RunnableSequen... | null |
embed_with_retry | """Use tenacity to retry the embedding call."""
retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) ->Any:
response = requests.post(**kwargs)
return _check_response(response.json())
return _embed_with_retry(**kwargs) | def embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) ->Any:
"""Use tenacity to retry the embedding call."""
retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) ->Any:
response = requests.post(**kwargs)
return _check_re... | Use tenacity to retry the embedding call. |
test_self_hosted_huggingface_pipeline_summarization | """Test valid call to self-hosted HuggingFace summarization model."""
gpu = get_remote_instance()
llm = SelfHostedHuggingFaceLLM(model_id='facebook/bart-large-cnn', task=
'summarization', hardware=gpu, model_reqs=model_reqs)
output = llm('Say foo:')
assert isinstance(output, str) | def test_self_hosted_huggingface_pipeline_summarization() ->None:
"""Test valid call to self-hosted HuggingFace summarization model."""
gpu = get_remote_instance()
llm = SelfHostedHuggingFaceLLM(model_id='facebook/bart-large-cnn', task
='summarization', hardware=gpu, model_reqs=model_reqs)
outpu... | Test valid call to self-hosted HuggingFace summarization model. |
_invoke | for attempt in self._sync_retrying(reraise=True):
with attempt:
result = super().invoke(input, self._patch_config(config,
run_manager, attempt.retry_state), **kwargs)
if attempt.retry_state.outcome and not attempt.retry_state.outcome.failed:
attempt.retry_state.set_result(result)
ret... | def _invoke(self, input: Input, run_manager: 'CallbackManagerForChainRun',
config: RunnableConfig, **kwargs: Any) ->Output:
for attempt in self._sync_retrying(reraise=True):
with attempt:
result = super().invoke(input, self._patch_config(config,
run_manager, attempt.retry_sta... | null |
_import_awadb | from langchain_community.vectorstores.awadb import AwaDB
return AwaDB | def _import_awadb() ->Any:
from langchain_community.vectorstores.awadb import AwaDB
return AwaDB | null |
get_tools | docs = retriever.get_relevant_documents(query)
return [ALL_TOOLS[d.metadata['index']] for d in docs] | def get_tools(query: str) ->List[Tool]:
docs = retriever.get_relevant_documents(query)
return [ALL_TOOLS[d.metadata['index']] for d in docs] | null |
test_chat_google_genai_system_message | model = ChatGoogleGenerativeAI(model=_MODEL,
convert_system_message_to_human=True)
text_question1, text_answer1 = 'How much is 2+2?', '4'
text_question2 = 'How much is 3+3?'
system_message = SystemMessage(content=
"You're supposed to answer math questions.")
message1 = HumanMessage(content=text_question1)
messa... | def test_chat_google_genai_system_message() ->None:
model = ChatGoogleGenerativeAI(model=_MODEL,
convert_system_message_to_human=True)
text_question1, text_answer1 = 'How much is 2+2?', '4'
text_question2 = 'How much is 3+3?'
system_message = SystemMessage(content=
"You're supposed to an... | null |
_sanitize_title | sanitized_title = re.sub('\\s', ' ', title)
sanitized_title = re.sub('(?u)[^- \\w.]', '', sanitized_title)
if len(sanitized_title) > _MAXIMUM_TITLE_LENGTH:
sanitized_title = sanitized_title[:_MAXIMUM_TITLE_LENGTH]
return sanitized_title | @staticmethod
def _sanitize_title(title: str) ->str:
sanitized_title = re.sub('\\s', ' ', title)
sanitized_title = re.sub('(?u)[^- \\w.]', '', sanitized_title)
if len(sanitized_title) > _MAXIMUM_TITLE_LENGTH:
sanitized_title = sanitized_title[:_MAXIMUM_TITLE_LENGTH]
return sanitized_title | null |
embed_documents | """Call out to Clarifai's embedding models.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
try:
from clarifai.client.input import Inputs
from clarifai.client.model import Model
except ImportError:
raise ImportErr... | def embed_documents(self, texts: List[str]) ->List[List[float]]:
"""Call out to Clarifai's embedding models.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
try:
from clarifai.client.input import Inputs
... | Call out to Clarifai's embedding models.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text. |
save | """Save the chain.
Expects `Chain._chain_type` property to be implemented and for memory to be
null.
Args:
file_path: Path to file to save the chain to.
Example:
.. code-block:: python
chain.save(file_path="path/chain.yaml")
"""
if ... | def save(self, file_path: Union[Path, str]) ->None:
"""Save the chain.
Expects `Chain._chain_type` property to be implemented and for memory to be
null.
Args:
file_path: Path to file to save the chain to.
Example:
.. code-block:: python
... | Save the chain.
Expects `Chain._chain_type` property to be implemented and for memory to be
null.
Args:
file_path: Path to file to save the chain to.
Example:
.. code-block:: python
chain.save(file_path="path/chain.yaml") |
on_agent_finish | """Run when agent ends running."""
aim = import_aim()
self.step += 1
self.agent_ends += 1
self.ends += 1
resp = {'action': 'on_agent_finish'}
resp.update(self.get_custom_callback_meta())
finish_res = deepcopy(finish)
text = """OUTPUT:
{}
LOG:
{}""".format(finish_res.return_values['output'],
finish_res.log)
self._r... | def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) ->None:
"""Run when agent ends running."""
aim = import_aim()
self.step += 1
self.agent_ends += 1
self.ends += 1
resp = {'action': 'on_agent_finish'}
resp.update(self.get_custom_callback_meta())
finish_res = deepcopy(finish)
... | Run when agent ends running. |
max_marginal_relevance_search | """Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query (str): Text to look up documents similar to.
k (int): Number of Documents to return. Defaul... | def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int=
20, lambda_mult: float=0.5, fields: Optional[List[str]]=None, **kwargs: Any
) ->List[Document]:
"""Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND ... | Return docs selected using the maximal marginal relevance.
Maximal marginal relevance optimizes for similarity to query AND diversity
among selected documents.
Args:
query (str): Text to look up documents similar to.
k (int): Number of Documents to return. Defaults to 4.
fetch_k (int): Number of Docum... |
test_loading_few_shot_prompt_when_examples_in_config | """Test loading few shot prompt when the examples are in the config."""
with change_directory(EXAMPLE_DIR):
prompt = load_prompt('few_shot_prompt_examples_in.json')
expected_prompt = FewShotPromptTemplate(input_variables=['adjective'],
prefix='Write antonyms for the following words.', example_prompt=
... | def test_loading_few_shot_prompt_when_examples_in_config() ->None:
"""Test loading few shot prompt when the examples are in the config."""
with change_directory(EXAMPLE_DIR):
prompt = load_prompt('few_shot_prompt_examples_in.json')
expected_prompt = FewShotPromptTemplate(input_variables=[
... | Test loading few shot prompt when the examples are in the config. |
_get_twilio | return Tool(name='Text-Message', description=
'Useful for when you need to send a text message to a provided phone number.'
, func=TwilioAPIWrapper(**kwargs).run) | def _get_twilio(**kwargs: Any) ->BaseTool:
return Tool(name='Text-Message', description=
'Useful for when you need to send a text message to a provided phone number.'
, func=TwilioAPIWrapper(**kwargs).run) | null |
_google_search_results | cse = self.search_engine.cse()
if self.siterestrict:
cse = cse.siterestrict()
res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute()
return res.get('items', []) | def _google_search_results(self, search_term: str, **kwargs: Any) ->List[dict]:
cse = self.search_engine.cse()
if self.siterestrict:
cse = cse.siterestrict()
res = cse.list(q=search_term, cx=self.google_cse_id, **kwargs).execute()
return res.get('items', []) | null |
get | """Gets the collection.
Args:
ids: The ids of the embeddings to get. Optional.
where: A Where type dict used to filter results by.
E.g. `{"color" : "red", "price": 4.20}`. Optional.
limit: The number of documents to return. Optional.
offset: Th... | def get(self, ids: Optional[OneOrMany[ID]]=None, where: Optional[Where]=
None, limit: Optional[int]=None, offset: Optional[int]=None,
where_document: Optional[WhereDocument]=None, include: Optional[List[
str]]=None) ->Dict[str, Any]:
"""Gets the collection.
Args:
ids: The ids of the... | Gets the collection.
Args:
ids: The ids of the embeddings to get. Optional.
where: A Where type dict used to filter results by.
E.g. `{"color" : "red", "price": 4.20}`. Optional.
limit: The number of documents to return. Optional.
offset: The offset to start returning results from.
... |
get_num_tokens | """Return number of tokens."""
return len(text.split()) | def get_num_tokens(self, text: str) ->int:
"""Return number of tokens."""
return len(text.split()) | Return number of tokens. |
clear | """Clear session memory from Neo4j"""
query = (
f'MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT]-() WITH p, length(p) AS length ORDER BY length DESC LIMIT 1 UNWIND nodes(p) as node DETACH DELETE node;'
)
self._driver.execute_query(query, {... | def clear(self) ->None:
"""Clear session memory from Neo4j"""
query = (
f'MATCH (s:`{self._node_label}`)-[:LAST_MESSAGE]->(last_message) WHERE s.id = $session_id MATCH p=(last_message)<-[:NEXT]-() WITH p, length(p) AS length ORDER BY length DESC LIMIT 1 UNWIND nodes(p) as node DETACH DELETE node;'
... | Clear session memory from Neo4j |
__init__ | super().__init__()
self.operator = operator or eq | def __init__(self, operator: Optional[Callable]=None, **kwargs: Any) ->None:
super().__init__()
self.operator = operator or eq | null |
clear | """Empty the collection of all its stored entries."""
self._drop_collection()
self._provision_collection()
return None | def clear(self) ->None:
"""Empty the collection of all its stored entries."""
self._drop_collection()
self._provision_collection()
return None | Empty the collection of all its stored entries. |
create_data_generation_chain | """Creates a chain that generates synthetic sentences with
provided fields.
Args:
llm: The language model to use.
prompt: Prompt to feed the language model with.
If not provided, the default one will be used.
"""
prompt = prompt or SENTENCE_PROMPT
return LLMChain(llm=llm, prompt=pr... | def create_data_generation_chain(llm: BaseLanguageModel, prompt: Optional[
PromptTemplate]=None) ->Chain:
"""Creates a chain that generates synthetic sentences with
provided fields.
Args:
llm: The language model to use.
prompt: Prompt to feed the language model with.
If not pro... | Creates a chain that generates synthetic sentences with
provided fields.
Args:
llm: The language model to use.
prompt: Prompt to feed the language model with.
If not provided, the default one will be used. |
run | """Search Reddit and return posts as a single string."""
results: List[Dict] = self.results(query=query, sort=sort, time_filter=
time_filter, subreddit=subreddit, limit=limit)
if len(results) > 0:
output: List[str] = [f'Searching r/{subreddit} found {len(results)} posts:'
]
for r in results:
... | def run(self, query: str, sort: str, time_filter: str, subreddit: str,
limit: int) ->str:
"""Search Reddit and return posts as a single string."""
results: List[Dict] = self.results(query=query, sort=sort, time_filter=
time_filter, subreddit=subreddit, limit=limit)
if len(results) > 0:
o... | Search Reddit and return posts as a single string. |
_llm_type | """Return type of llm."""
return 'fake_list' | @property
def _llm_type(self) ->str:
"""Return type of llm."""
return 'fake_list' | Return type of llm. |
test_confluence_loader_load_data_by_space_id | mock_confluence.get_all_pages_from_space.return_value = [self.
_get_mock_page('123'), self._get_mock_page('456')]
mock_confluence.get_all_restrictions_for_content.side_effect = [self.
_get_mock_page_restrictions('123'), self._get_mock_page_restrictions('456')
]
confluence_loader = self._get_mock_confluence_... | def test_confluence_loader_load_data_by_space_id(self, mock_confluence:
MagicMock) ->None:
mock_confluence.get_all_pages_from_space.return_value = [self.
_get_mock_page('123'), self._get_mock_page('456')]
mock_confluence.get_all_restrictions_for_content.side_effect = [self.
_get_mock_page_re... | null |
append | """Append message to the end of the chat template.
Args:
message: representation of a message to append.
"""
self.messages.append(_convert_to_message(message)) | def append(self, message: MessageLikeRepresentation) ->None:
"""Append message to the end of the chat template.
Args:
message: representation of a message to append.
"""
self.messages.append(_convert_to_message(message)) | Append message to the end of the chat template.
Args:
message: representation of a message to append. |
_import_eleven_labs_text2speech | from langchain_community.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool
return ElevenLabsText2SpeechTool | def _import_eleven_labs_text2speech() ->Any:
from langchain_community.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool
return ElevenLabsText2SpeechTool | null |
similarity_search_with_score | """Perform a search on a query string and return results with score."""
embedding = self.embedding_func.embed_query(query)
res = self.similarity_search_with_score_by_vector(embedding=embedding, k=k,
param=param, expr=expr, timeout=timeout, **kwargs)
return res | def similarity_search_with_score(self, query: str, k: int=4, param:
Optional[dict]=None, expr: Optional[str]=None, timeout: Optional[int]=
None, **kwargs: Any) ->List[Tuple[Document, float]]:
"""Perform a search on a query string and return results with score."""
embedding = self.embedding_func.embed_qu... | Perform a search on a query string and return results with score. |
get_lc_namespace | """Get the namespace of the langchain object."""
return ['langchain', 'prompts', 'pipeline'] | @classmethod
def get_lc_namespace(cls) ->List[str]:
"""Get the namespace of the langchain object."""
return ['langchain', 'prompts', 'pipeline'] | Get the namespace of the langchain object. |
_get_tools_requests_patch | return RequestsPatchTool(requests_wrapper=TextRequestsWrapper()) | def _get_tools_requests_patch() ->BaseTool:
return RequestsPatchTool(requests_wrapper=TextRequestsWrapper()) | null |
test_delete_dataset_by_ids | """Test delete dataset."""
id = deeplake_datastore.vectorstore.dataset.id.data()['value'][0]
deeplake_datastore.delete(ids=[id])
assert deeplake_datastore.similarity_search('foo', k=1, filter={'metadata':
{'page': '0'}}) == []
assert len(deeplake_datastore.vectorstore) == 2
deeplake_datastore.delete_dataset() | def test_delete_dataset_by_ids(deeplake_datastore: DeepLake) ->None:
"""Test delete dataset."""
id = deeplake_datastore.vectorstore.dataset.id.data()['value'][0]
deeplake_datastore.delete(ids=[id])
assert deeplake_datastore.similarity_search('foo', k=1, filter={
'metadata': {'page': '0'}}) == []... | Test delete dataset. |
requires_reference | return False | @property
def requires_reference(self) ->bool:
return False | null |
get_model_list | """Get a list of models loaded in the triton server."""
res = self.client.get_model_repository_index(as_json=True)
return [model['name'] for model in res['models']] | def get_model_list(self) ->List[str]:
"""Get a list of models loaded in the triton server."""
res = self.client.get_model_repository_index(as_json=True)
return [model['name'] for model in res['models']] | Get a list of models loaded in the triton server. |
truncate_word | """
Truncate a string to a certain number of words, based on the max string
length.
"""
if not isinstance(content, str) or length <= 0:
return content
if len(content) <= length:
return content
return content[:length - len(suffix)].rsplit(' ', 1)[0] + suffix | def truncate_word(content: Any, *, length: int, suffix: str='...') ->str:
"""
Truncate a string to a certain number of words, based on the max string
length.
"""
if not isinstance(content, str) or length <= 0:
return content
if len(content) <= length:
return content
return co... | Truncate a string to a certain number of words, based on the max string
length. |
clear | """Clear cache."""
from gptcache import Cache
for gptcache_instance in self.gptcache_dict.values():
gptcache_instance = cast(Cache, gptcache_instance)
gptcache_instance.flush()
self.gptcache_dict.clear() | def clear(self, **kwargs: Any) ->None:
"""Clear cache."""
from gptcache import Cache
for gptcache_instance in self.gptcache_dict.values():
gptcache_instance = cast(Cache, gptcache_instance)
gptcache_instance.flush()
self.gptcache_dict.clear() | Clear cache. |
input_keys | """Expect input key.
:meta private:
"""
return [self.question_key] | @property
def input_keys(self) ->List[str]:
"""Expect input key.
:meta private:
"""
return [self.question_key] | Expect input key.
:meta private: |
parse_result | if len(result) != 1:
raise OutputParserException(
f'Expected exactly one result, but got {len(result)}')
generation = result[0]
if not isinstance(generation, ChatGeneration):
raise OutputParserException(
'This output parser can only be used with a chat generation.')
message = generation.message
... | def parse_result(self, result: List[Generation], *, partial: bool=False) ->Any:
if len(result) != 1:
raise OutputParserException(
f'Expected exactly one result, but got {len(result)}')
generation = result[0]
if not isinstance(generation, ChatGeneration):
raise OutputParserExcepti... | null |
_import_lancedb | from langchain_community.vectorstores.lancedb import LanceDB
return LanceDB | def _import_lancedb() ->Any:
from langchain_community.vectorstores.lancedb import LanceDB
return LanceDB | null |
predict | ... | @abstractmethod
def predict(self, event: TEvent) ->Any:
... | null |
test_xml_output_parser | """Test XMLOutputParser."""
xml_parser = XMLOutputParser()
xml_result = xml_parser.parse_folder(result)
assert DEF_RESULT_EXPECTED == xml_result
assert list(xml_parser.transform(iter(result))) == [{'foo': [{'bar': [{
'baz': None}]}]}, {'foo': [{'bar': [{'baz': 'slim.shady'}]}]}, {'foo':
[{'baz': 'tag'}]}] | @pytest.mark.parametrize('result', [DEF_RESULT_ENCODING,
DEF_RESULT_ENCODING[DEF_RESULT_ENCODING.find('\n'):],
f"""
```xml
{DEF_RESULT_ENCODING}
```
""",
f"""
Some random text
```xml
{DEF_RESULT_ENCODING}
```
More random text
"""
])
def test_xml_output_parser(result: str) ->None:
"""Test XMLOutputPa... | Test XMLOutputParser. |
test_api_key_masked_when_passed_via_constructor | llm = Predibase(predibase_api_key='secret-api-key')
print(llm.predibase_api_key, end='')
captured = capsys.readouterr()
assert captured.out == '**********' | def test_api_key_masked_when_passed_via_constructor(capsys: CaptureFixture
) ->None:
llm = Predibase(predibase_api_key='secret-api-key')
print(llm.predibase_api_key, end='')
captured = capsys.readouterr()
assert captured.out == '**********' | null |
test_multiple_messages | """Tests multiple messages works."""
chat = ChatZhipuAI()
message = HumanMessage(content='Hi, how are you.')
response = chat.generate([[message], [message]])
assert isinstance(response, LLMResult)
assert len(response.generations) == 2
for generations in response.generations:
assert len(generations) == 1
for gen... | def test_multiple_messages() ->None:
"""Tests multiple messages works."""
chat = ChatZhipuAI()
message = HumanMessage(content='Hi, how are you.')
response = chat.generate([[message], [message]])
assert isinstance(response, LLMResult)
assert len(response.generations) == 2
for generations in r... | Tests multiple messages works. |
_get_human_tool | return HumanInputRun(**kwargs) | def _get_human_tool(**kwargs: Any) ->BaseTool:
return HumanInputRun(**kwargs) | 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. |
test_clear_messages | file_chat_message_history.add_user_message('Hello!')
file_chat_message_history.add_ai_message('Hi there!')
file_chat_message_history.clear()
messages = file_chat_message_history.messages
assert len(messages) == 0 | def test_clear_messages(file_chat_message_history: FileChatMessageHistory
) ->None:
file_chat_message_history.add_user_message('Hello!')
file_chat_message_history.add_ai_message('Hi there!')
file_chat_message_history.clear()
messages = file_chat_message_history.messages
assert len(messages) == 0 | null |
invoke | key = input['key']
actual_input = input['input']
if key not in self.runnables:
raise ValueError(f"No runnable associated with key '{key}'")
runnable = self.runnables[key]
return runnable.invoke(actual_input, config) | def invoke(self, input: RouterInput, config: Optional[RunnableConfig]=None
) ->Output:
key = input['key']
actual_input = input['input']
if key not in self.runnables:
raise ValueError(f"No runnable associated with key '{key}'")
runnable = self.runnables[key]
return runnable.invoke(actual_... | null |
is_lc_serializable | """Return whether this class is serializable."""
return True | @classmethod
def is_lc_serializable(cls) ->bool:
"""Return whether this class is serializable."""
return True | Return whether this class is serializable. |
_import_render | from langchain_community.tools.convert_to_openai import format_tool_to_openai_function
return format_tool_to_openai_function | def _import_render() ->Any:
from langchain_community.tools.convert_to_openai import format_tool_to_openai_function
return format_tool_to_openai_function | null |
similarity_search_with_score | """Perform a similarity search with Yellowbrick
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
NOTE: Please do not let end-user fill this and always be aware
of SQL injection.
Returns:
Li... | def similarity_search_with_score(self, query: str, k: int=4, **kwargs: Any
) ->List[Tuple[Document, float]]:
"""Perform a similarity search with Yellowbrick
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
NOTE: Please d... | Perform a similarity search with Yellowbrick
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
NOTE: Please do not let end-user fill this and always be aware
of SQL injection.
Returns:
List[Document]: List of (Document, similarity) |
__init__ | """Initialize with bucket and key name.
:param bucket: The name of the S3 bucket.
:param key: The key of the S3 object.
:param region_name: The name of the region associated with the client.
A client is associated with a single region.
:param api_version: The API version t... | def __init__(self, bucket: str, key: str, *, region_name: Optional[str]=
None, api_version: Optional[str]=None, use_ssl: Optional[bool]=True,
verify: Union[str, bool, None]=None, endpoint_url: Optional[str]=None,
aws_access_key_id: Optional[str]=None, aws_secret_access_key: Optional[
str]=None, aws_sess... | Initialize with bucket and key name.
:param bucket: The name of the S3 bucket.
:param key: The key of the S3 object.
:param region_name: The name of the region associated with the client.
A client is associated with a single region.
:param api_version: The API version to use. By default, botocore will
use t... |
load_prompt | """Unified method for loading a prompt from LangChainHub or local fs."""
if (hub_result := try_load_from_hub(path, _load_prompt_from_file, 'prompts',
{'py', 'json', 'yaml'})):
return hub_result
else:
return _load_prompt_from_file(path) | def load_prompt(path: Union[str, Path]) ->BasePromptTemplate:
"""Unified method for loading a prompt from LangChainHub or local fs."""
if (hub_result := try_load_from_hub(path, _load_prompt_from_file,
'prompts', {'py', 'json', 'yaml'})):
return hub_result
else:
return _load_prompt_fr... | Unified method for loading a prompt from LangChainHub or local fs. |
structured_tool_input | """Return the arguments directly."""
return f'{arg1}, {arg2}, {opt_arg}' | @tool(infer_schema=False)
def structured_tool_input(arg1: int, arg2: Union[float, datetime], opt_arg:
Optional[dict]=None) ->str:
"""Return the arguments directly."""
return f'{arg1}, {arg2}, {opt_arg}' | Return the arguments directly. |
on_agent_action | if self.__has_valid_config is False:
return
try:
name = action.tool
input = _parse_input(action.tool_input)
self.__track_event('tool', 'start', run_id=str(run_id), parent_run_id=
str(parent_run_id) if parent_run_id else None, name=name, input=
input, app_id=self.__app_id)
except Exceptio... | def on_agent_action(self, action: AgentAction, *, run_id: UUID,
parent_run_id: Union[UUID, None]=None, **kwargs: Any) ->Any:
if self.__has_valid_config is False:
return
try:
name = action.tool
input = _parse_input(action.tool_input)
self.__track_event('tool', 'start', run_id=... | null |
test_visit_operation | op = Operation(operator=Operator.AND, arguments=[Comparison(comparator=
Comparator.LT, attribute='foo', value=2), Comparison(comparator=
Comparator.EQ, attribute='bar', value='baz')])
expected = {'$and': [{'foo': {'$lt': 2}}, {'bar': {'$eq': 'baz'}}]}
actual = DEFAULT_TRANSLATOR.visit_operation(op)
assert expec... | def test_visit_operation() ->None:
op = Operation(operator=Operator.AND, arguments=[Comparison(comparator=
Comparator.LT, attribute='foo', value=2), Comparison(comparator=
Comparator.EQ, attribute='bar', value='baz')])
expected = {'$and': [{'foo': {'$lt': 2}}, {'bar': {'$eq': 'baz'}}]}
actua... | null |
_parse_string_eval_output | """Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Any: The parsed output.
"""
reasoning = text.strip()
parsed_scores = _get_score(reasoning)
if parsed_scores is None:
value, score = None, None
else:
value, score = parsed_scores
return {'reasoning': reas... | def _parse_string_eval_output(text: str) ->dict:
"""Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Any: The parsed output.
"""
reasoning = text.strip()
parsed_scores = _get_score(reasoning)
if parsed_scores is None:
value, score = None, ... | Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Any: The parsed output. |
_create_chat_result | generations = []
for res in response['choices']:
message = convert_dict_to_message(res['message'])
gen = ChatGeneration(message=message, generation_info=dict(
finish_reason=res.get('finish_reason')))
generations.append(gen)
token_usage = response.get('usage', {})
llm_output = {'token_usage': token_u... | def _create_chat_result(self, response: Mapping[str, Any]) ->ChatResult:
generations = []
for res in response['choices']:
message = convert_dict_to_message(res['message'])
gen = ChatGeneration(message=message, generation_info=dict(
finish_reason=res.get('finish_reason')))
gen... | null |
sync_call_fallback | """
Decorator to call the synchronous method of the class if the async method is not
implemented. This decorator might be only used for the methods that are defined
as async in the class.
"""
@functools.wraps(method)
async def wrapper(self: Any, *args: Any, **kwargs: Any) ->Any:
try:
return ... | def sync_call_fallback(method: Callable) ->Callable:
"""
Decorator to call the synchronous method of the class if the async method is not
implemented. This decorator might be only used for the methods that are defined
as async in the class.
"""
@functools.wraps(method)
async def wrapper(sel... | Decorator to call the synchronous method of the class if the async method is not
implemented. This decorator might be only used for the methods that are defined
as async in the class. |
from_embeddings | """Construct FAISS wrapper from raw documents.
This is a user friendly interface that:
1. Embeds documents.
2. Creates an in memory docstore
3. Initializes the FAISS database
This is intended to be a quick way to get started.
Example:
.. code-bl... | @classmethod
def from_embeddings(cls, text_embeddings: Iterable[Tuple[str, List[float]]],
embedding: Embeddings, metadatas: Optional[Iterable[dict]]=None, ids:
Optional[List[str]]=None, **kwargs: Any) ->FAISS:
"""Construct FAISS wrapper from raw documents.
This is a user friendly interface that:
... | Construct FAISS wrapper from raw documents.
This is a user friendly interface that:
1. Embeds documents.
2. Creates an in memory docstore
3. Initializes the FAISS database
This is intended to be a quick way to get started.
Example:
.. code-block:: python
from langchain_community.vectorstores... |
validate_variable_names | """Validate variable names do not include restricted names."""
if 'stop' in values['input_variables']:
raise ValueError(
"Cannot have an input variable named 'stop', as it is used internally, please rename."
)
if 'stop' in values['partial_variables']:
raise ValueError(
"Cannot have an pa... | @root_validator()
def validate_variable_names(cls, values: Dict) ->Dict:
"""Validate variable names do not include restricted names."""
if 'stop' in values['input_variables']:
raise ValueError(
"Cannot have an input variable named 'stop', as it is used internally, please rename."
... | Validate variable names do not include restricted names. |
test_hologres_with_filter_match | """Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': str(i)} for i in range(len(texts))]
docsearch = Hologres.from_texts(texts=texts, table_name='test_table_filter',
embedding=FakeEmbeddingsWithAdaDimension(), metadatas=metadatas,
connection_string=CONNECTION_STRING... | def test_hologres_with_filter_match() ->None:
"""Test end to end construction and search."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': str(i)} for i in range(len(texts))]
docsearch = Hologres.from_texts(texts=texts, table_name=
'test_table_filter', embedding=FakeEmbeddingsWithAdaDimens... | Test end to end construction and search. |
create_index | """
Create an index of embeddings for a list of contexts.
Args:
contexts: List of contexts to embed.
embeddings: Embeddings model to use.
Returns:
Index of embeddings.
"""
with concurrent.futures.ThreadPoolExecutor() as executor:
return np.array(list(executor.map(embeddings... | def create_index(contexts: List[str], embeddings: Embeddings) ->np.ndarray:
"""
Create an index of embeddings for a list of contexts.
Args:
contexts: List of contexts to embed.
embeddings: Embeddings model to use.
Returns:
Index of embeddings.
"""
with concurrent.future... | Create an index of embeddings for a list of contexts.
Args:
contexts: List of contexts to embed.
embeddings: Embeddings model to use.
Returns:
Index of embeddings. |
on_retriever_end | self.on_retriever_end_common() | def on_retriever_end(self, *args: Any, **kwargs: Any) ->Any:
self.on_retriever_end_common() | null |
test_singlestoredb_filter_metadata_5 | """Test complex metadata path"""
table_name = 'test_singlestoredb_filter_metadata_5'
drop(table_name)
docs = [Document(page_content=t, metadata={'index': i, 'category': 'budget',
'subfield': {'subfield': {'idx': i, 'other_idx': i + 1}}}) for i, t in
enumerate(texts)]
docsearch = SingleStoreDB.from_documents(doc... | @pytest.mark.skipif(not singlestoredb_installed, reason=
'singlestoredb not installed')
def test_singlestoredb_filter_metadata_5(texts: List[str]) ->None:
"""Test complex metadata path"""
table_name = 'test_singlestoredb_filter_metadata_5'
drop(table_name)
docs = [Document(page_content=t, metadata={... | Test complex metadata path |
_make_session | """Create a session and close it after use."""
if isinstance(self.session_factory, async_sessionmaker):
raise AssertionError('This method is not supported for async engines.')
session = self.session_factory()
try:
yield session
finally:
session.close() | @contextlib.contextmanager
def _make_session(self) ->Generator[Session, None, None]:
"""Create a session and close it after use."""
if isinstance(self.session_factory, async_sessionmaker):
raise AssertionError('This method is not supported for async engines.')
session = self.session_factory()
tr... | Create a session and close it after use. |
main | """Generate the api_reference.rst file for each package."""
for dir in os.listdir(ROOT_DIR / 'libs'):
if dir in ('cli', 'partners'):
continue
else:
_build_rst_file(package_name=dir)
for dir in os.listdir(ROOT_DIR / 'libs' / 'partners'):
_build_rst_file(package_name=dir) | def main() ->None:
"""Generate the api_reference.rst file for each package."""
for dir in os.listdir(ROOT_DIR / 'libs'):
if dir in ('cli', 'partners'):
continue
else:
_build_rst_file(package_name=dir)
for dir in os.listdir(ROOT_DIR / 'libs' / 'partners'):
_bui... | Generate the api_reference.rst file for each package. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.