method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
test_max_chunks
documents = [f'text-{i}' for i in range(20)] embedding = ErnieEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 20
def test_max_chunks() ->None: documents = [f'text-{i}' for i in range(20)] embedding = ErnieEmbeddings() output = embedding.embed_documents(documents) assert len(output) == 20
null
login
""" login to jaguardb server with a jaguar_api_key or let self._jag find a key Args: pod (str): name of a Pod store (str): name of a vector store optional jaguar_api_key (str): API key of user to jaguardb server Returns: True if successful; False...
def login(self, jaguar_api_key: Optional[str]='') ->bool: """ login to jaguardb server with a jaguar_api_key or let self._jag find a key Args: pod (str): name of a Pod store (str): name of a vector store optional jaguar_api_key (str): API key of user to jaguardb...
login to jaguardb server with a jaguar_api_key or let self._jag find a key Args: pod (str): name of a Pod store (str): name of a vector store optional jaguar_api_key (str): API key of user to jaguardb server Returns: True if successful; False if not successful
lazy_load
"""Lazy load the chat sessions."""
@abstractmethod def lazy_load(self) ->Iterator[ChatSession]: """Lazy load the chat sessions."""
Lazy load the chat sessions.
test_extract_html
html2text_transformer = Html2TextTransformer() paragraphs_html = ( '<html>Begin of html tag<h1>Header</h1><p>First paragraph.</p>Middle of html tag<p>Second paragraph.</p>End of html tag</html>' ) documents = [Document(page_content=paragraphs_html)] docs_transformed = html2text_transformer.transform_documents(d...
@pytest.mark.requires('html2text') def test_extract_html() ->None: html2text_transformer = Html2TextTransformer() paragraphs_html = ( '<html>Begin of html tag<h1>Header</h1><p>First paragraph.</p>Middle of html tag<p>Second paragraph.</p>End of html tag</html>' ) documents = [Document(page_c...
null
test_api_key_is_string
llm = ChatFireworks(fireworks_api_key='secret-api-key') assert isinstance(llm.fireworks_api_key, SecretStr)
@pytest.mark.requires('fireworks') def test_api_key_is_string() ->None: llm = ChatFireworks(fireworks_api_key='secret-api-key') assert isinstance(llm.fireworks_api_key, SecretStr)
null
_import_anyscale
from langchain_community.llms.anyscale import Anyscale return Anyscale
def _import_anyscale() ->Any: from langchain_community.llms.anyscale import Anyscale return Anyscale
null
_scopes
"""Return required scopes.""" return ['Notes.Read']
@property def _scopes(self) ->List[str]: """Return required scopes.""" return ['Notes.Read']
Return required scopes.
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: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. ...
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, filter: Optional[dict]=None, namespace: Optional[str]=None, **kwargs: Any) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass ...
_get_functions_from_llm_run
""" Extract functions from a LangSmith LLM run if they exist. :param llm_run: The LLM run object. :return: Functions from the run or None. """ if llm_run.run_type != 'llm': raise ValueError(f'Expected run of type llm. Got: {llm_run.run_type}') return (llm_run.extra or {}).get('invoc...
@staticmethod def _get_functions_from_llm_run(llm_run: 'Run') ->Optional[List[Dict]]: """ Extract functions from a LangSmith LLM run if they exist. :param llm_run: The LLM run object. :return: Functions from the run or None. """ if llm_run.run_type != 'llm': raise ValueE...
Extract functions from a LangSmith LLM run if they exist. :param llm_run: The LLM run object. :return: Functions from the run or None.
delete_texts
"""Delete a list of docs from the Rockset collection""" try: from rockset.models import DeleteDocumentsRequestData except ImportError: raise ImportError( 'Could not import rockset client python package. Please install it with `pip install rockset`.' ) self._client.Documents.delete_documents(coll...
def delete_texts(self, ids: List[str]) ->None: """Delete a list of docs from the Rockset collection""" try: from rockset.models import DeleteDocumentsRequestData except ImportError: raise ImportError( 'Could not import rockset client python package. Please install it with `pip in...
Delete a list of docs from the Rockset collection
_llm_type
"""Return type of chat model.""" return 'mlflow-chat'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'mlflow-chat'
Return type of chat model.
validate_environment
"""Ensure that the API key and python package exist in environment.""" values['octoai_api_token'] = get_from_dict_or_env(values, 'octoai_api_token', 'OCTOAI_API_TOKEN') values['endpoint_url'] = get_from_dict_or_env(values, 'endpoint_url', 'ENDPOINT_URL') return values
@root_validator(allow_reuse=True) def validate_environment(cls, values: Dict) ->Dict: """Ensure that the API key and python package exist in environment.""" values['octoai_api_token'] = get_from_dict_or_env(values, 'octoai_api_token', 'OCTOAI_API_TOKEN') values['endpoint_url'] = get_from_dict_or_env...
Ensure that the API key and python package exist in environment.
embed_query
"""Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ return self.embed_documents([text])[0]
def embed_query(self, text: str) ->List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ return self.embed_documents([text])[0]
Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text.
_get_elements
from unstructured.partition.xml import partition_xml return partition_xml(filename=self.file_path, **self.unstructured_kwargs)
def _get_elements(self) ->List: from unstructured.partition.xml import partition_xml return partition_xml(filename=self.file_path, **self.unstructured_kwargs)
null
semantic_hybrid_search_with_score
""" Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most simi...
def semantic_hybrid_search_with_score(self, query: str, k: int=4, **kwargs: Any ) ->List[Tuple[Document, float]]: """ Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number ...
Returns the most similar indexed documents to the query text. Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text.
messages
"""Retrieve the messages from Redis""" _items = self.redis_client.lrange(self.key, 0, -1) items = [json.loads(m.decode('utf-8')) for m in _items[::-1]] messages = messages_from_dict(items) return messages
@property def messages(self) ->List[BaseMessage]: """Retrieve the messages from Redis""" _items = self.redis_client.lrange(self.key, 0, -1) items = [json.loads(m.decode('utf-8')) for m in _items[::-1]] messages = messages_from_dict(items) return messages
Retrieve the messages from Redis
test_json_distance_evaluator_evaluate_strings_list_diff
prediction = '[{"a": 1, "b": 2}, {"a": 2, "b": 3}]' reference = '[{"a": 1, "b": 2}, {"a": 2, "b": 4}]' result = json_distance_evaluator._evaluate_strings(prediction=prediction, reference=reference) pytest.approx(1 / len(reference.replace(' ', '')), result['score'])
@pytest.mark.requires('rapidfuzz') def test_json_distance_evaluator_evaluate_strings_list_diff( json_distance_evaluator: JsonEditDistanceEvaluator) ->None: prediction = '[{"a": 1, "b": 2}, {"a": 2, "b": 3}]' reference = '[{"a": 1, "b": 2}, {"a": 2, "b": 4}]' result = json_distance_evaluator._evaluate_st...
null
generate
"""Generate text from Arcee DALM. Args: prompt: Prompt to generate text from. size: The max number of context results to retrieve. Defaults to 3. (Can be less if filters are provided). filters: Filters to apply to the context dataset. """ response = sel...
def generate(self, prompt: str, **kwargs: Any) ->str: """Generate text from Arcee DALM. Args: prompt: Prompt to generate text from. size: The max number of context results to retrieve. Defaults to 3. (Can be less if filters are provided). filters: Filters t...
Generate text from Arcee DALM. Args: prompt: Prompt to generate text from. size: The max number of context results to retrieve. Defaults to 3. (Can be less if filters are provided). filters: Filters to apply to the context dataset.
similarity_search_by_vector
"""Perform retrieval directly using vectors. Args: embedding: vectors. k: top n. search_filter: Additional filtering conditions. Returns: document_list: List of documents. """ return self.create_results(self.inner_embedding_query(embedding=embeddin...
def similarity_search_by_vector(self, embedding: List[float], k: int=4, search_filter: Optional[dict]=None, **kwargs: Any) ->List[Document]: """Perform retrieval directly using vectors. Args: embedding: vectors. k: top n. search_filter: Additional filtering conditions...
Perform retrieval directly using vectors. Args: embedding: vectors. k: top n. search_filter: Additional filtering conditions. Returns: document_list: List of documents.
_import_zilliz
from langchain_community.vectorstores.zilliz import Zilliz return Zilliz
def _import_zilliz() ->Any: from langchain_community.vectorstores.zilliz import Zilliz return Zilliz
null
load
"""Load docs.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load docs.""" return list(self.lazy_load())
Load docs.
__radd__
chunk = AddableDict(other) for key in self: if key not in chunk or chunk[key] is None: chunk[key] = self[key] elif self[key] is not None: try: added = chunk[key] + self[key] except TypeError: added = self[key] chunk[key] = added return chunk
def __radd__(self, other: AddableDict) ->AddableDict: chunk = AddableDict(other) for key in self: if key not in chunk or chunk[key] is None: chunk[key] = self[key] elif self[key] is not None: try: added = chunk[key] + self[key] except TypeError...
null
__init__
if atransform is not None: self._atransform = atransform func_for_name: Callable = atransform if inspect.isasyncgenfunction(transform): self._atransform = transform func_for_name = transform elif inspect.isgeneratorfunction(transform): self._transform = transform func_for_name = transform else: ...
def __init__(self, transform: Union[Callable[[Iterator[Input]], Iterator[ Output]], Callable[[AsyncIterator[Input]], AsyncIterator[Output]]], atransform: Optional[Callable[[AsyncIterator[Input]], AsyncIterator[ Output]]]=None) ->None: if atransform is not None: self._atransform = atransform ...
null
teardown
bigquery.Client(location='US').delete_dataset(TestBigQueryVectorStore. dataset_name, delete_contents=True, not_found_ok=True)
def teardown() ->None: bigquery.Client(location='US').delete_dataset(TestBigQueryVectorStore. dataset_name, delete_contents=True, not_found_ok=True)
null
check_libcublas
if not is_libcublas_available(): pytest.skip(reason='libcublas.so is not available') yield
@pytest.fixture(scope='module', autouse=True) def check_libcublas() ->Iterator[None]: if not is_libcublas_available(): pytest.skip(reason='libcublas.so is not available') yield
null
config_specs
return self.mapper.config_specs
@property def config_specs(self) ->List[ConfigurableFieldSpec]: return self.mapper.config_specs
null
_default_params
"""Get the default parameters for calling Hunyuan API.""" normal_params = {'app_id': self.hunyuan_app_id, 'secret_id': self. hunyuan_secret_id, 'temperature': self.temperature, 'top_p': self.top_p} if self.query_id is not None: normal_params['query_id'] = self.query_id return {**normal_params, **self.model_kwar...
@property def _default_params(self) ->Dict[str, Any]: """Get the default parameters for calling Hunyuan API.""" normal_params = {'app_id': self.hunyuan_app_id, 'secret_id': self. hunyuan_secret_id, 'temperature': self.temperature, 'top_p': self.top_p } if self.query_id is not None: n...
Get the default parameters for calling Hunyuan API.
test_max_marginal_relevance_search_by_vector
"""Test end to end construction and MRR search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = Weaviate.from_texts(texts, embedding_openai, metadatas= metadatas, weaviate_url=weaviate_url) foo_embedding = embedding_openai.embed_query('foo') standard_ranki...
@pytest.mark.vcr(ignore_localhost=True) def test_max_marginal_relevance_search_by_vector(self, weaviate_url: str, embedding_openai: OpenAIEmbeddings) ->None: """Test end to end construction and MRR search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] ...
Test end to end construction and MRR search by vector.
add_texts
"""Add text to the Vectara vectorstore. Args: texts (List[str]): The text metadatas (List[dict]): Metadata dicts, must line up with existing store """ self.vectorstore.add_texts(texts, metadatas, doc_metadata or {})
def add_texts(self, texts: List[str], metadatas: Optional[List[dict]]=None, doc_metadata: Optional[dict]=None) ->None: """Add text to the Vectara vectorstore. Args: texts (List[str]): The text metadatas (List[dict]): Metadata dicts, must line up with existing store """ ...
Add text to the Vectara vectorstore. Args: texts (List[str]): The text metadatas (List[dict]): Metadata dicts, must line up with existing store
load
"""Load documents.""" paths = list(Path(self.file_path).glob('**/*.md')) docs = [] for path in paths: with open(path, encoding=self.encoding) as f: text = f.read() front_matter = self._parse_front_matter(text) tags = self._parse_document_tags(text) dataview_fields = self._parse_dataview_fields(t...
def load(self) ->List[Document]: """Load documents.""" paths = list(Path(self.file_path).glob('**/*.md')) docs = [] for path in paths: with open(path, encoding=self.encoding) as f: text = f.read() front_matter = self._parse_front_matter(text) tags = self._parse_docume...
Load documents.
test_redis_semantic_cache_hit
set_llm_cache(RedisSemanticCache(embedding=embedding, redis_url=REDIS_TEST_URL) ) llm = FakeLLM() params = llm.dict() params['stop'] = None llm_string = str(sorted([(k, v) for k, v in params.items()])) llm_generations = [[Generation(text=generation, generation_info=params) for generation in prompt_i_generations...
@pytest.mark.parametrize('embedding', [ConsistentFakeEmbeddings()]) @pytest.mark.parametrize('prompts, generations', [([random_string()], [[ random_string()]]), ([random_string()], [[random_string(), random_string()]]), ([random_string()], [[random_string(), random_string(), random_string()]]), ([random_st...
null
_prepare_chat
params = self._prepare_params(stop, **kwargs) history = _parse_chat_history(messages, convert_system_message_to_human= self.convert_system_message_to_human) message = history.pop() chat = self.client.start_chat(history=history) return params, chat, message
def _prepare_chat(self, messages: List[BaseMessage], stop: Optional[List[ str]]=None, **kwargs: Any) ->Tuple[Dict[str, Any], genai.ChatSession, genai.types.ContentDict]: params = self._prepare_params(stop, **kwargs) history = _parse_chat_history(messages, convert_system_message_to_human =self.co...
null
_results_to_docs
return [doc for doc, _ in _results_to_docs_and_scores(results)]
def _results_to_docs(results: Any) ->List[Document]: return [doc for doc, _ in _results_to_docs_and_scores(results)]
null
detect_file_src_type
"""Detect if the file is local or remote.""" if os.path.isfile(file_path): return 'local' parsed_url = urlparse(file_path) if parsed_url.scheme and parsed_url.netloc: return 'remote' return 'invalid'
def detect_file_src_type(file_path: str) ->str: """Detect if the file is local or remote.""" if os.path.isfile(file_path): return 'local' parsed_url = urlparse(file_path) if parsed_url.scheme and parsed_url.netloc: return 'remote' return 'invalid'
Detect if the file is local or remote.
build_extra
"""Build extra kwargs from additional params that were passed in.""" all_required_field_names = get_pydantic_field_names(cls) extra = values.get('model_kwargs', {}) for field_name in list(values): if field_name in extra: raise ValueError(f'Found {field_name} supplied twice.') if field_name not in all_re...
@root_validator(pre=True) def build_extra(cls, values: Dict[str, Any]) ->Dict[str, Any]: """Build extra kwargs from additional params that were passed in.""" all_required_field_names = get_pydantic_field_names(cls) extra = values.get('model_kwargs', {}) for field_name in list(values): if field_n...
Build extra kwargs from additional params that were passed in.
_create_chat_result
generations = [] for candidate in response['llm_response']['choices']: message = ChatJavelinAIGateway._convert_dict_to_message(candidate[ 'message']) message_metadata = candidate.get('metadata', {}) gen = ChatGeneration(message=message, generation_info=dict( message_metadata)) generation...
@staticmethod def _create_chat_result(response: Mapping[str, Any]) ->ChatResult: generations = [] for candidate in response['llm_response']['choices']: message = ChatJavelinAIGateway._convert_dict_to_message(candidate[ 'message']) message_metadata = candidate.get('metadata', {}) ...
null
get_query_constructor_prompt
"""Create query construction prompt. Args: document_contents: The contents of the document to be queried. attribute_info: A list of AttributeInfo objects describing the attributes of the document. examples: Optional list of examples to use for the chain. allowed_comparat...
def get_query_constructor_prompt(document_contents: str, attribute_info: Sequence[Union[AttributeInfo, dict]], *, examples: Optional[Sequence]= None, allowed_comparators: Sequence[Comparator]=tuple(Comparator), allowed_operators: Sequence[Operator]=tuple(Operator), enable_limit: bool=False, schema_promp...
Create query construction prompt. Args: document_contents: The contents of the document to be queried. attribute_info: A list of AttributeInfo objects describing the attributes of the document. examples: Optional list of examples to use for the chain. allowed_comparators: Sequence of allowed co...
setup_class
assert os.getenv('XATA_API_KEY' ), 'XATA_API_KEY environment variable is not set' assert os.getenv('XATA_DB_URL'), 'XATA_DB_URL environment variable is not set'
@classmethod def setup_class(cls) ->None: assert os.getenv('XATA_API_KEY' ), 'XATA_API_KEY environment variable is not set' assert os.getenv('XATA_DB_URL' ), 'XATA_DB_URL environment variable is not set'
null
__le__
"""Create a Numeric less than or equal to filter expression. Args: other (Union[int, float]): The value to filter on. Example: >>> from langchain_community.vectorstores.redis import RedisNum >>> filter = RedisNum("age") <= 18 """ self._set_value(other, self....
def __le__(self, other: Union[int, float]) ->'RedisFilterExpression': """Create a Numeric less than or equal to filter expression. Args: other (Union[int, float]): The value to filter on. Example: >>> from langchain_community.vectorstores.redis import RedisNum >...
Create a Numeric less than or equal to filter expression. Args: other (Union[int, float]): The value to filter on. Example: >>> from langchain_community.vectorstores.redis import RedisNum >>> filter = RedisNum("age") <= 18
test_call_no_result
"""Test that non-existent words return proper result.""" output = api_client.run('NO_RESULT_NO_RESULT_NO_RESULT') assert 'No Merriam-Webster definition was found for query' in output
def test_call_no_result(api_client: MerriamWebsterAPIWrapper) ->None: """Test that non-existent words return proper result.""" output = api_client.run('NO_RESULT_NO_RESULT_NO_RESULT') assert 'No Merriam-Webster definition was found for query' in output
Test that non-existent words return proper result.
embed_query
"""Return simple embeddings.""" return [float(1.0)] * (ADA_TOKEN_COUNT - 1) + [float(0.0)]
def embed_query(self, text: str) ->List[float]: """Return simple embeddings.""" return [float(1.0)] * (ADA_TOKEN_COUNT - 1) + [float(0.0)]
Return simple embeddings.
similarity_search
results = self.similarity_search_with_score(query, k, **kwargs) return [r[0] for r in results]
def similarity_search(self, query: str, k: int=4, **kwargs: Any) ->List[ Document]: results = self.similarity_search_with_score(query, k, **kwargs) return [r[0] for r in results]
null
on_agent_finish
"""Run on agent end.""" print_text(finish.log, color=color or self.color, end='\n')
def on_agent_finish(self, finish: AgentFinish, color: Optional[str]=None, **kwargs: Any) ->None: """Run on agent end.""" print_text(finish.log, color=color or self.color, end='\n')
Run on agent end.
with_config
return RunnableEach(bound=self.bound.with_config(config, **kwargs))
def with_config(self, config: Optional[RunnableConfig]=None, **kwargs: Any ) ->RunnableEach[Input, Output]: return RunnableEach(bound=self.bound.with_config(config, **kwargs))
null
_get_google_serper_results_json
return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
def _get_google_serper_results_json(**kwargs: Any) ->BaseTool: return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
null
test_vald_max_marginal_relevance_search_by_vector
"""Test end to end construction and MRR search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _vald_from_texts(metadatas=metadatas) time.sleep(WAIT_TIME) embedding = FakeEmbeddings().embed_query('foo') output = docsearch.max_marginal_relevance_search_by_vect...
def test_vald_max_marginal_relevance_search_by_vector() ->None: """Test end to end construction and MRR search by vector.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _vald_from_texts(metadatas=metadatas) time.sleep(WAIT_TIME) embedding = Fake...
Test end to end construction and MRR search by vector.
_llm_type
"""Return type of llm.""" return 'huggingface_hub'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'huggingface_hub'
Return type of llm.
create_csv_agent
"""Create csv agent by loading to a dataframe and using pandas agent.""" try: import pandas as pd except ImportError: raise ImportError( 'pandas package not found, please install with `pip install pandas`') _kwargs = pandas_kwargs or {} if isinstance(path, (str, IOBase)): df = pd.read_csv(path, **_k...
def create_csv_agent(llm: BaseLanguageModel, path: Union[str, IOBase, List[ Union[str, IOBase]]], pandas_kwargs: Optional[dict]=None, **kwargs: Any ) ->AgentExecutor: """Create csv agent by loading to a dataframe and using pandas agent.""" try: import pandas as pd except ImportError: ...
Create csv agent by loading to a dataframe and using pandas agent.
validate_environment
values['ernie_api_base'] = get_from_dict_or_env(values, 'ernie_api_base', 'ERNIE_API_BASE', 'https://aip.baidubce.com') values['ernie_client_id'] = get_from_dict_or_env(values, 'ernie_client_id', 'ERNIE_CLIENT_ID') values['ernie_client_secret'] = get_from_dict_or_env(values, 'ernie_client_secret', 'ERNIE_CL...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: values['ernie_api_base'] = get_from_dict_or_env(values, 'ernie_api_base', 'ERNIE_API_BASE', 'https://aip.baidubce.com') values['ernie_client_id'] = get_from_dict_or_env(values, 'ernie_client_id', 'ERNIE_CLIENT_ID') values[...
null
__getattr__
"""Get attr name.""" if name in DEPRECATED_CODE: HERE = Path(__file__).parents[1] relative_path = as_import_path(Path(__file__).parent, suffix=name, relative_to=HERE) old_path = 'langchain.' + relative_path new_path = 'langchain_experimental.' + relative_path raise ImportError( f"""{...
def __getattr__(name: str) ->Any: """Get attr name.""" if name in DEPRECATED_CODE: HERE = Path(__file__).parents[1] relative_path = as_import_path(Path(__file__).parent, suffix=name, relative_to=HERE) old_path = 'langchain.' + relative_path new_path = 'langchain_exper...
Get attr name.
get_model
"""Download model. From https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/, convert to new ggml format and return model path. """ model_url = ( 'https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/resolve/main/ggml-alpaca-7b-q4.bin' ) tokenizer_url = ( 'https://huggingface.co/decapoda-rese...
def get_model() ->str: """Download model. From https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/, convert to new ggml format and return model path. """ model_url = ( 'https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/resolve/main/ggml-alpaca-7b-q4.bin' ) tokenizer_url = ...
Download model. From https://huggingface.co/Sosaka/Alpaca-native-4bit-ggml/, convert to new ggml format and return model path.
on_chain_error
self.on_chain_error_common()
def on_chain_error(self, *args: Any, **kwargs: Any) ->Any: self.on_chain_error_common()
null
test_action_w_namespace_w_emb_w_more_than_one_item_in_first_dict
str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) encoded_str2 = base.stringify_embedding(list(encoded_keyword + str2)) encoded_str3 = base.stringify_embedding(list(encoded_keyword + str3)) expected = [{'test_namespace': encoded_str1, 'test_namespace2': s...
@pytest.mark.requires('vowpal_wabbit_next') def test_action_w_namespace_w_emb_w_more_than_one_item_in_first_dict() ->None: str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str1 = base.stringify_embedding(list(encoded_keyword + str1)) encoded_str2 = base.stringify_embedding(list(encoded_keyword +...
null
_import_google_scholar
from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper return GoogleScholarAPIWrapper
def _import_google_scholar() ->Any: from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper return GoogleScholarAPIWrapper
null
on_chain_start
"""Run when chain starts running. Args: serialized (Dict[str, Any]): The serialized chain. inputs (Union[Dict[str, Any], Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: CallbackManagerForChainRun: Th...
def on_chain_start(self, serialized: Dict[str, Any], inputs: Union[Dict[str, Any], Any], run_id: Optional[UUID]=None, **kwargs: Any ) ->CallbackManagerForChainRun: """Run when chain starts running. Args: serialized (Dict[str, Any]): The serialized chain. inputs (Union[Dict[s...
Run when chain starts running. Args: serialized (Dict[str, Any]): The serialized chain. inputs (Union[Dict[str, Any], Any]): The inputs to the chain. run_id (UUID, optional): The ID of the run. Defaults to None. Returns: CallbackManagerForChainRun: The callback manager for the chain run.
get_referenced_schema
"""Get a schema (or nested reference) or err.""" ref_name = ref.ref.split('/')[-1] schemas = self._schemas_strict if ref_name not in schemas: raise ValueError(f'No schema found for {ref_name}') return schemas[ref_name]
def get_referenced_schema(self, ref: Reference) ->Schema: """Get a schema (or nested reference) or err.""" ref_name = ref.ref.split('/')[-1] schemas = self._schemas_strict if ref_name not in schemas: raise ValueError(f'No schema found for {ref_name}') return schemas[ref_name]
Get a schema (or nested reference) or err.
query
"""Query the vectorstore.""" llm = llm or OpenAI(temperature=0) retriever_kwargs = retriever_kwargs or {} chain = RetrievalQA.from_chain_type(llm, retriever=self.vectorstore. as_retriever(**retriever_kwargs), **kwargs) return chain.run(question)
def query(self, question: str, llm: Optional[BaseLanguageModel]=None, retriever_kwargs: Optional[Dict[str, Any]]=None, **kwargs: Any) ->str: """Query the vectorstore.""" llm = llm or OpenAI(temperature=0) retriever_kwargs = retriever_kwargs or {} chain = RetrievalQA.from_chain_type(llm, retriever=se...
Query the vectorstore.
on_llm_end
"""Run when LLM ends running.""" self.step += 1 self.llm_ends += 1 self.ends += 1 metadata = self._init_resp() metadata.update({'action': 'on_llm_end'}) metadata.update(flatten_dict(response.llm_output or {})) metadata.update(self.get_custom_callback_meta()) output_complexity_metrics = [] output_custom_metrics = [] for...
def on_llm_end(self, response: LLMResult, **kwargs: Any) ->None: """Run when LLM ends running.""" self.step += 1 self.llm_ends += 1 self.ends += 1 metadata = self._init_resp() metadata.update({'action': 'on_llm_end'}) metadata.update(flatten_dict(response.llm_output or {})) metadata.upda...
Run when LLM ends running.
__init__
super().__init__(**kwargs) self._validate_uri() try: from mlflow.deployments import get_deploy_client self._client = get_deploy_client(self.target_uri) except ImportError as e: raise ImportError( 'Failed to create the client. Please run `pip install mlflow[genai]` to install required dependencies.' ...
def __init__(self, **kwargs: Any): super().__init__(**kwargs) self._validate_uri() try: from mlflow.deployments import get_deploy_client self._client = get_deploy_client(self.target_uri) except ImportError as e: raise ImportError( 'Failed to create the client. Please ...
null
__hash__
return id(self)
def __hash__(self) ->int: return id(self)
null
fn
if url.endswith('/processing/pull'): return FakePullResponse() else: raise Exception('Invalid GET URL')
def fn(url: str, **kwargs: Any) ->Any: if url.endswith('/processing/pull'): return FakePullResponse() else: raise Exception('Invalid GET URL')
null
invoke
from langchain_core.beta.runnables.context import config_with_context config = config_with_context(ensure_config(config), self.steps) callback_manager = get_callback_manager_for_config(config) run_manager = callback_manager.on_chain_start(dumpd(self), input, name= config.get('run_name') or self.get_name()) try: ...
def invoke(self, input: Input, config: Optional[RunnableConfig]=None) ->Output: from langchain_core.beta.runnables.context import config_with_context config = config_with_context(ensure_config(config), self.steps) callback_manager = get_callback_manager_for_config(config) run_manager = callback_manager....
null
add_texts
""" Add a list of texts to the Elasticsearch index. Args: texts (Iterable[str]): The texts to add to the index. metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries to associate with the texts. model_id (str, optional): The ID o...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[Dict[Any, Any]]]=None, model_id: Optional[str]=None, refresh_indices: bool=False, **kwargs: Any) ->List[str]: """ Add a list of texts to the Elasticsearch index. Args: texts (Iterable[str]): The texts to add to t...
Add a list of texts to the Elasticsearch index. Args: texts (Iterable[str]): The texts to add to the index. metadatas (List[Dict[Any, Any]], optional): A list of metadata dictionaries to associate with the texts. model_id (str, optional): The ID of the model to use for transforming the text...
set_debug
"""Set a new value for the `debug` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing debug from langchain root module is no longer supported' ) langchain.debug = value except ImportError: pas...
def set_debug(value: bool) ->None: """Set a new value for the `debug` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing debug from langchain root module is no longer supported' ...
Set a new value for the `debug` global setting.
_identifying_params
"""Get the identifying parameters.""" return {'model_id': self.model_id}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {'model_id': self.model_id}
Get the identifying parameters.
_llm_type
"""Return type of llm.""" return 'fake'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'fake'
Return type of llm.
adapt
"""Adapts an `ArceeDocument` to a langchain's `Document` object.""" return Document(page_content=arcee_document.source.document, metadata={ 'name': arcee_document.source.name, 'source_id': arcee_document.source. id, 'index': arcee_document.index, 'id': arcee_document.id, 'score': arcee_document.score})
@classmethod def adapt(cls, arcee_document: ArceeDocument) ->Document: """Adapts an `ArceeDocument` to a langchain's `Document` object.""" return Document(page_content=arcee_document.source.document, metadata={ 'name': arcee_document.source.name, 'source_id': arcee_document. source.id, 'index': ...
Adapts an `ArceeDocument` to a langchain's `Document` object.
_destrip
if isinstance(tool_input, dict): return {k: _destrip(v) for k, v in tool_input.items()} elif isinstance(tool_input, list): if isinstance(tool_input[0], str): if len(tool_input) == 1: return tool_input[0] else: raise ValueError elif isinstance(tool_input[0], dict): ...
def _destrip(tool_input: Any) ->Any: if isinstance(tool_input, dict): return {k: _destrip(v) for k, v in tool_input.items()} elif isinstance(tool_input, list): if isinstance(tool_input[0], str): if len(tool_input) == 1: return tool_input[0] else: ...
null
_import_file_management_MoveFileTool
from langchain_community.tools.file_management import MoveFileTool return MoveFileTool
def _import_file_management_MoveFileTool() ->Any: from langchain_community.tools.file_management import MoveFileTool return MoveFileTool
null
test_load_valid_string_content
file_path = '/workspaces/langchain/test.json' expected_docs = [Document(page_content='value1', metadata={'source': file_path, 'seq_num': 1}), Document(page_content='value2', metadata={ 'source': file_path, 'seq_num': 2})] mocker.patch('builtins.open', mocker.mock_open()) mocker.patch('pathlib.Path.read_text', r...
def test_load_valid_string_content(mocker: MockerFixture) ->None: file_path = '/workspaces/langchain/test.json' expected_docs = [Document(page_content='value1', metadata={'source': file_path, 'seq_num': 1}), Document(page_content='value2', metadata ={'source': file_path, 'seq_num': 2})] mock...
null
compare
"""Compare model outputs on an input text. If a prompt was provided with starting the laboratory, then this text will be fed into the prompt. If no prompt was provided, then the input text is the entire prompt. Args: text: input text to run all models on. """ print(...
def compare(self, text: str) ->None: """Compare model outputs on an input text. If a prompt was provided with starting the laboratory, then this text will be fed into the prompt. If no prompt was provided, then the input text is the entire prompt. Args: text: input text...
Compare model outputs on an input text. If a prompt was provided with starting the laboratory, then this text will be fed into the prompt. If no prompt was provided, then the input text is the entire prompt. Args: text: input text to run all models on.
get_documents
"""Search documents by their ids or metadata values. Args: ids: List of ids of documents to retrieve from the vectorstore. filter: Filter on metadata properties, e.g. { "str_property": "foo", "in...
def get_documents(self, ids: Optional[List[str]]=None, filter: Optional[ Dict[str, Any]]=None) ->List[Document]: """Search documents by their ids or metadata values. Args: ids: List of ids of documents to retrieve from the vectorstore. filter: Filter on metadata properties, e.g....
Search documents by their ids or metadata values. Args: ids: List of ids of documents to retrieve from the vectorstore. filter: Filter on metadata properties, e.g. { "str_property": "foo", "int_property": 123 } Returns: ...
create_index_if_not_exist
index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info('Index already exists') return False self.client.tvs_create_index(self.index_name, dim, distance_type, index_type, data_type, **kwargs) return True
def create_index_if_not_exist(self, dim: int, distance_type: str, index_type: str, data_type: str, **kwargs: Any) ->bool: index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info('Index already exists') return False self.client.tvs_create_index(self.index_name...
null
__init__
super().__init__(model_name=model_name, gpu=gpu, **kwargs)
def __init__(self, model_name: str='paraphrase-multilingual-mpnet-base-v2', gpu: bool=False, **kwargs: Any) ->None: super().__init__(model_name=model_name, gpu=gpu, **kwargs)
null
_llm_type
"""Return type of chat_model.""" return 'baidu-qianfan-chat'
@property def _llm_type(self) ->str: """Return type of chat_model.""" return 'baidu-qianfan-chat'
Return type of chat_model.
parse
"""Parse the output text and extract the score and reasoning. Args: text (str): The output text to parse. Returns: TrajectoryEval: A named tuple containing the normalized score and reasoning. Raises: OutputParserException: If the score is not found in the o...
def parse(self, text: str) ->TrajectoryEval: """Parse the output text and extract the score and reasoning. Args: text (str): The output text to parse. Returns: TrajectoryEval: A named tuple containing the normalized score and reasoning. Raises: OutputPa...
Parse the output text and extract the score and reasoning. Args: text (str): The output text to parse. Returns: TrajectoryEval: A named tuple containing the normalized score and reasoning. Raises: OutputParserException: If the score is not found in the output text or if the LLM's score is not a d...
__init__
self.generator = create_data_generation_chain(llm) self.sentence_preferences = sentence_preferences or {}
def __init__(self, llm: BaseLanguageModel, sentence_preferences: Optional[ Dict[str, Any]]=None): self.generator = create_data_generation_chain(llm) self.sentence_preferences = sentence_preferences or {}
null
test_update_with_delayed_score_with_auto_validator_throws
llm, PROMPT = setup() auto_val_llm = FakeListChatModel(responses=['3']) chain = pick_best_chain.PickBest.from_llm(llm=llm, prompt=PROMPT, selection_scorer=rl_chain.AutoSelectionScorer(llm=auto_val_llm), feature_embedder=pick_best_chain.PickBestFeatureEmbedder(auto_embed= False, model=MockEncoder())) actions...
@pytest.mark.requires('vowpal_wabbit_next', 'sentence_transformers') def test_update_with_delayed_score_with_auto_validator_throws() ->None: llm, PROMPT = setup() auto_val_llm = FakeListChatModel(responses=['3']) chain = pick_best_chain.PickBest.from_llm(llm=llm, prompt=PROMPT, selection_scorer=rl_c...
null
_process_response
"""Process API response""" if response.ok: data = response.json() return data['result']['response'] else: raise ValueError(f'Request failed with status {response.status_code}')
def _process_response(self, response: requests.Response) ->str: """Process API response""" if response.ok: data = response.json() return data['result']['response'] else: raise ValueError(f'Request failed with status {response.status_code}')
Process API response
parse_output
text = message.content if '</tool>' in text: tool, tool_input = text.split('</tool>') _tool = tool.split('<tool>')[1] _tool_input = tool_input.split('<tool_input>')[1] if '</tool_input>' in _tool_input: _tool_input = _tool_input.split('</tool_input>')[0] return AgentAction(tool=_tool, tool_i...
def parse_output(message): text = message.content if '</tool>' in text: tool, tool_input = text.split('</tool>') _tool = tool.split('<tool>')[1] _tool_input = tool_input.split('<tool_input>')[1] if '</tool_input>' in _tool_input: _tool_input = _tool_input.split('</too...
null
_len_check_if_sized
if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y): raise ValueError( f'{x_name} and {y_name} expected to be equal length but len({x_name})={len(x)} and len({y_name})={len(y)}' ) return
def _len_check_if_sized(x: Any, y: Any, x_name: str, y_name: str) ->None: if isinstance(x, Sized) and isinstance(y, Sized) and len(x) != len(y): raise ValueError( f'{x_name} and {y_name} expected to be equal length but len({x_name})={len(x)} and len({y_name})={len(y)}' ) return
null
_import_anyscale
from langchain_community.llms.anyscale import Anyscale return Anyscale
def _import_anyscale() ->Any: from langchain_community.llms.anyscale import Anyscale return Anyscale
null
astradb_cache
cache = AstraDBCache(collection_name='lc_integration_test_cache', token=os. environ['ASTRA_DB_APPLICATION_TOKEN'], api_endpoint=os.environ[ 'ASTRA_DB_API_ENDPOINT'], namespace=os.environ.get('ASTRA_DB_KEYSPACE')) yield cache cache.astra_db.delete_collection('lc_integration_test_cache')
@pytest.fixture(scope='module') def astradb_cache() ->Iterator[AstraDBCache]: cache = AstraDBCache(collection_name='lc_integration_test_cache', token =os.environ['ASTRA_DB_APPLICATION_TOKEN'], api_endpoint=os.environ[ 'ASTRA_DB_API_ENDPOINT'], namespace=os.environ.get('ASTRA_DB_KEYSPACE') ) ...
null
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
stream
result = self.invoke(input, config) for i_c, c in enumerate(result): if self.sleep is not None: time.sleep(self.sleep) if (self.error_on_chunk_number is not None and i_c == self. error_on_chunk_number): raise Exception('Fake error') yield c
def stream(self, input: LanguageModelInput, config: Optional[RunnableConfig ]=None, *, stop: Optional[List[str]]=None, **kwargs: Any) ->Iterator[str]: result = self.invoke(input, config) for i_c, c in enumerate(result): if self.sleep is not None: time.sleep(self.sleep) if (self.e...
null
parse
cleaned = text.strip() finished = self.finished_value in cleaned return cleaned.replace(self.finished_value, ''), finished
def parse(self, text: str) ->Tuple[str, bool]: cleaned = text.strip() finished = self.finished_value in cleaned return cleaned.replace(self.finished_value, ''), finished
null
load
"""Load documents.""" try: from azure.storage.blob import ContainerClient 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 container = ContainerClient.from_connection_string(con...
def load(self) ->List[Document]: """Load documents.""" try: from azure.storage.blob import ContainerClient except ImportError as exc: raise ImportError( 'Could not import azure storage blob python package. Please install it with `pip install azure-storage-blob`.' ) fr...
Load documents.
_import_mlflow_chat
from langchain_community.chat_models.mlflow import ChatMlflow return ChatMlflow
def _import_mlflow_chat() ->Any: from langchain_community.chat_models.mlflow import ChatMlflow return ChatMlflow
null
now
return datetime.datetime(dt_value.year, dt_value.month, dt_value.day, dt_value.hour, dt_value.minute, dt_value.second, dt_value.microsecond, dt_value.tzinfo)
@classmethod def now(cls): return datetime.datetime(dt_value.year, dt_value.month, dt_value.day, dt_value.hour, dt_value.minute, dt_value.second, dt_value. microsecond, dt_value.tzinfo)
null
_import_twilio
from langchain_community.utilities.twilio import TwilioAPIWrapper return TwilioAPIWrapper
def _import_twilio() ->Any: from langchain_community.utilities.twilio import TwilioAPIWrapper return TwilioAPIWrapper
null
_format_chat_history
buffer: List[BaseMessage] = [] 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]]) ->List[ BaseMessage]: buffer: List[BaseMessage] = [] for human, ai in chat_history: buffer.append(HumanMessage(content=human)) buffer.append(AIMessage(content=ai)) return buffer
null
__init__
"""Initialize the TomlLoader with a source file or directory.""" self.source = Path(source)
def __init__(self, source: Union[str, Path]): """Initialize the TomlLoader with a source file or directory.""" self.source = Path(source)
Initialize the TomlLoader with a source file or directory.
output_keys
"""Output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys
@property def output_keys(self) ->List[str]: """Output keys. :meta private: """ _output_keys = [self.output_key] return _output_keys
Output keys. :meta private:
test_mosaicml_extra_kwargs
llm = MosaicML(model_kwargs={'max_new_tokens': 1}) assert llm.model_kwargs == {'max_new_tokens': 1} output = llm('Say foo:') assert isinstance(output, str) assert len(output.split()) <= 1
def test_mosaicml_extra_kwargs() ->None: llm = MosaicML(model_kwargs={'max_new_tokens': 1}) assert llm.model_kwargs == {'max_new_tokens': 1} output = llm('Say foo:') assert isinstance(output, str) assert len(output.split()) <= 1
null
test_weighted_reciprocal_rank
doc1 = Document(page_content='1') doc2 = Document(page_content='2') dummy_retriever = BM25Retriever.from_texts(['1', '2']) ensemble_retriever = EnsembleRetriever(retrievers=[dummy_retriever, dummy_retriever], weights=[0.4, 0.5], c=0) result = ensemble_retriever.weighted_reciprocal_rank([[doc1, doc2], [doc2, doc...
@pytest.mark.requires('rank_bm25') def test_weighted_reciprocal_rank() ->None: doc1 = Document(page_content='1') doc2 = Document(page_content='2') dummy_retriever = BM25Retriever.from_texts(['1', '2']) ensemble_retriever = EnsembleRetriever(retrievers=[dummy_retriever, dummy_retriever], weights=...
null
visit_operation
if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1: operator = self._format_func(operation.operator) return operator + '(' + operation.arguments[0].accept(self) + ')' elif operation.operator in UNARY_OPERATORS: raise ValueError( f'"{operation.operator.value}" can have only on...
def visit_operation(self, operation: Operation) ->str: if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1: operator = self._format_func(operation.operator) return operator + '(' + operation.arguments[0].accept(self) + ')' elif operation.operator in UNARY_OPERATORS: ...
null
test_custom_template_tool_response
intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log= 'Log1'), 'Observation1')] template_tool_response = 'Response: {observation}' expected_result = [AIMessage(content='Log1'), HumanMessage(content= 'Response: Observation1')] assert format_log_to_messages(intermediate_steps, template_tool_r...
def test_custom_template_tool_response() ->None: intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log='Log1'), 'Observation1')] template_tool_response = 'Response: {observation}' expected_result = [AIMessage(content='Log1'), HumanMessage(content= 'Response: Observation1'...
null
test_infinity_emb_sync
mocker.patch('requests.post', side_effect=mocked_requests_post) embedder = InfinityEmbeddings(model=_MODEL_ID, infinity_api_url= _INFINITY_BASE_URL) assert embedder.infinity_api_url == _INFINITY_BASE_URL assert embedder.model == _MODEL_ID response = embedder.embed_documents(_DOCUMENTS) want = [[1.0, 0.0, 0.0], [1.0...
def test_infinity_emb_sync(mocker: MockerFixture) ->None: mocker.patch('requests.post', side_effect=mocked_requests_post) embedder = InfinityEmbeddings(model=_MODEL_ID, infinity_api_url= _INFINITY_BASE_URL) assert embedder.infinity_api_url == _INFINITY_BASE_URL assert embedder.model == _MODEL_ID...
null
test__convert_dict_to_message_function
message = FunctionMessage(name='foo', content='bar') with pytest.raises(ValueError) as e: _convert_message_to_dict(message) assert 'Got unknown type' in str(e)
def test__convert_dict_to_message_function() ->None: message = FunctionMessage(name='foo', content='bar') with pytest.raises(ValueError) as e: _convert_message_to_dict(message) assert 'Got unknown type' in str(e)
null
_get_default_params
return {'language': 'en', 'format': 'json'}
def _get_default_params() ->dict: return {'language': 'en', 'format': 'json'}
null