method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
__init__
try: import streamlit as st except ImportError as e: raise ImportError( 'Unable to import streamlit, please run `pip install streamlit`.' ) from e if key not in st.session_state: st.session_state[key] = [] self._messages = st.session_state[key]
def __init__(self, key: str='langchain_messages'): try: import streamlit as st except ImportError as e: raise ImportError( 'Unable to import streamlit, please run `pip install streamlit`.' ) from e if key not in st.session_state: st.session_state[key] = [] ...
null
test_metadata_without_frontmatter
"""Verify docs without frontmatter, still have basic metadata.""" doc = next(doc for doc in docs if doc.metadata['source'] == 'no_metadata.md') assert set(doc.metadata) == STANDARD_METADATA_FIELDS
def test_metadata_without_frontmatter() ->None: """Verify docs without frontmatter, still have basic metadata.""" doc = next(doc for doc in docs if doc.metadata['source'] == 'no_metadata.md') assert set(doc.metadata) == STANDARD_METADATA_FIELDS
Verify docs without frontmatter, still have basic metadata.
_get_local_name
if '#' in iri: local_name = iri.split('#')[-1] elif '/' in iri: local_name = iri.split('/')[-1] else: raise ValueError(f"Unexpected IRI '{iri}', contains neither '#' nor '/'.") return local_name
@staticmethod def _get_local_name(iri: str) ->str: if '#' in iri: local_name = iri.split('#')[-1] elif '/' in iri: local_name = iri.split('/')[-1] else: raise ValueError( f"Unexpected IRI '{iri}', contains neither '#' nor '/'.") return local_name
null
test_get_session_pool
mock_session_pool.return_value = MagicMock() nebula_graph = NebulaGraph(self.space, self.username, self.password, self. address, self.port, self.session_pool_size) session_pool = nebula_graph._get_session_pool() self.assertIsInstance(session_pool, MagicMock)
@patch('nebula3.gclient.net.SessionPool.SessionPool') def test_get_session_pool(self, mock_session_pool: Any) ->None: mock_session_pool.return_value = MagicMock() nebula_graph = NebulaGraph(self.space, self.username, self.password, self.address, self.port, self.session_pool_size) session_pool = nebu...
null
test_openai_streaming_n_error
"""Test validation for streaming fails if n is not 1.""" with pytest.raises(ValueError): OpenAI(n=2, streaming=True)
def test_openai_streaming_n_error() ->None: """Test validation for streaming fails if n is not 1.""" with pytest.raises(ValueError): OpenAI(n=2, streaming=True)
Test validation for streaming fails if n is not 1.
mget
"""Get the values associated with the given keys.""" keys = [self._get_prefixed_key(key) for key in keys] return cast(List[Optional[str]], self.client.mget(*keys))
def mget(self, keys: Sequence[str]) ->List[Optional[str]]: """Get the values associated with the given keys.""" keys = [self._get_prefixed_key(key) for key in keys] return cast(List[Optional[str]], self.client.mget(*keys))
Get the values associated with the given keys.
_type
return 'json_functions'
@property def _type(self) ->str: return 'json_functions'
null
lookup
"""Look up based on prompt and llm_string.""" item = self.kv_cache.get(llm_string=_hash(llm_string), prompt=_hash(prompt)) if item is not None: generations = _loads_generations(item['body_blob']) if generations is not None: return generations else: return None else: return None
def lookup(self, prompt: str, llm_string: str) ->Optional[RETURN_VAL_TYPE]: """Look up based on prompt and llm_string.""" item = self.kv_cache.get(llm_string=_hash(llm_string), prompt=_hash(prompt) ) if item is not None: generations = _loads_generations(item['body_blob']) if generati...
Look up based on prompt and llm_string.
similarity_search
"""Return docs most similar to query. Args: query: The string that will be used to search for similar documents. k: The amount of neighbors that will be retrieved. filter: Optional. A list of Namespaces for filtering the matching results. For example: ...
def similarity_search(self, query: str, k: int=4, filter: Optional[List[ Namespace]]=None, **kwargs: Any) ->List[Document]: """Return docs most similar to query. Args: query: The string that will be used to search for similar documents. k: The amount of neighbors that will be re...
Return docs most similar to query. Args: query: The string that will be used to search for similar documents. k: The amount of neighbors that will be retrieved. filter: Optional. A list of Namespaces for filtering the matching results. For example: [Namespace("color", ["red"], []), Namespac...
__init__
"""Initialize the OBSFileLoader with the specified settings. Args: bucket (str): The name of the OBS bucket to be used. key (str): The name of the object in the OBS bucket. client (ObsClient, optional): An instance of the ObsClient to connect to OBS. endpoint (st...
def __init__(self, bucket: str, key: str, client: Any=None, endpoint: str= '', config: Optional[dict]=None) ->None: """Initialize the OBSFileLoader with the specified settings. Args: bucket (str): The name of the OBS bucket to be used. key (str): The name of the object in the OB...
Initialize the OBSFileLoader with the specified settings. Args: bucket (str): The name of the OBS bucket to be used. key (str): The name of the object in the OBS bucket. client (ObsClient, optional): An instance of the ObsClient to connect to OBS. endpoint (str, optional): The endpoint URL of your OBS ...
get_sql_model_class
return Model
def get_sql_model_class(self) ->Any: return Model
null
_import_wolfram_alpha
from langchain_community.utilities.wolfram_alpha import WolframAlphaAPIWrapper return WolframAlphaAPIWrapper
def _import_wolfram_alpha() ->Any: from langchain_community.utilities.wolfram_alpha import WolframAlphaAPIWrapper return WolframAlphaAPIWrapper
null
_raise_functions_not_supported
raise ValueError( 'Function messages are not supported by the MLflow AI Gateway. Please create a feature request at https://github.com/mlflow/mlflow/issues.' )
@staticmethod def _raise_functions_not_supported() ->None: raise ValueError( 'Function messages are not supported by the MLflow AI Gateway. Please create a feature request at https://github.com/mlflow/mlflow/issues.' )
null
predict
if stop is None: _stop = None else: _stop = list(stop) result = self([HumanMessage(content=text)], stop=_stop, **kwargs) if isinstance(result.content, str): return result.content else: raise ValueError('Cannot use predict when output is not a string.')
def predict(self, text: str, *, stop: Optional[Sequence[str]]=None, ** kwargs: Any) ->str: if stop is None: _stop = None else: _stop = list(stop) result = self([HumanMessage(content=text)], stop=_stop, **kwargs) if isinstance(result.content, str): return result.content el...
null
_import_human
from langchain_community.llms.human import HumanInputLLM return HumanInputLLM
def _import_human() ->Any: from langchain_community.llms.human import HumanInputLLM return HumanInputLLM
null
completion_with_retry
"""Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator def _completion_with_retry(**kwargs: Any) ->Any: return llm.client.generate(**kwargs) return _completion_with_retry(**kwargs)
def completion_with_retry(llm: Cohere, **kwargs: Any) ->Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_retry_decorator(llm) @retry_decorator def _completion_with_retry(**kwargs: Any) ->Any: return llm.client.generate(**kwargs) return _completion_with_retry(*...
Use tenacity to retry the completion call.
_llm_type
"""Return type of llm.""" return 'forefrontai'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'forefrontai'
Return type of llm.
lc_secrets
return {'cohere_api_key': 'COHERE_API_KEY'}
@property def lc_secrets(self) ->Dict[str, str]: return {'cohere_api_key': 'COHERE_API_KEY'}
null
test_shell_tool_run_str
placeholder = PlaceholderProcess(output='hello') shell_tool = ShellTool(process=placeholder) result = shell_tool._run(commands="echo 'Hello, World!'") assert result.strip() == 'hello'
def test_shell_tool_run_str() ->None: placeholder = PlaceholderProcess(output='hello') shell_tool = ShellTool(process=placeholder) result = shell_tool._run(commands="echo 'Hello, World!'") assert result.strip() == 'hello'
null
on_tool_start
"""Run when tool starts running."""
def on_tool_start(self, serialized: Dict[str, Any], input_str: str, ** kwargs: Any) ->None: """Run when tool starts running."""
Run when tool starts running.
_import_office365_create_draft_message
from langchain_community.tools.office365.create_draft_message import O365CreateDraftMessage return O365CreateDraftMessage
def _import_office365_create_draft_message() ->Any: from langchain_community.tools.office365.create_draft_message import O365CreateDraftMessage return O365CreateDraftMessage
null
from_texts
"""Return VectorStore initialized from texts and embeddings.""" vs_obj = BigQueryVectorSearch(embedding=embedding, **kwargs) vs_obj.add_texts(texts, metadatas) return vs_obj
@classmethod def from_texts(cls: Type['BigQueryVectorSearch'], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, **kwargs: Any ) ->'BigQueryVectorSearch': """Return VectorStore initialized from texts and embeddings.""" vs_obj = BigQueryVectorSearch(embedding=embedding, **kwa...
Return VectorStore initialized from texts and embeddings.
test_huggingface_pipeline_device_map
"""Test pipelines specifying the device map parameter.""" llm = HuggingFacePipeline.from_model_id(model_id='gpt2', task= 'text-generation', device_map='auto', pipeline_kwargs={'max_new_tokens': 10}) output = llm('Say foo:') assert isinstance(output, str)
def test_huggingface_pipeline_device_map() ->None: """Test pipelines specifying the device map parameter.""" llm = HuggingFacePipeline.from_model_id(model_id='gpt2', task= 'text-generation', device_map='auto', pipeline_kwargs={ 'max_new_tokens': 10}) output = llm('Say foo:') assert isins...
Test pipelines specifying the device map parameter.
visit_comparison
field = f'metadata.{comparison.attribute}' is_range_comparator = comparison.comparator in [Comparator.GT, Comparator. GTE, Comparator.LT, Comparator.LTE] if is_range_comparator: return {'range': {field: {self._format_func(comparison.comparator): comparison.value}}} if comparison.comparator == Comparator...
def visit_comparison(self, comparison: Comparison) ->Dict: field = f'metadata.{comparison.attribute}' is_range_comparator = comparison.comparator in [Comparator.GT, Comparator.GTE, Comparator.LT, Comparator.LTE] if is_range_comparator: return {'range': {field: {self._format_func(comparison.c...
null
_get_last_completed_thought
"""Return our most recent completed LLMThought, or None if we don't have one.""" if len(self._completed_thoughts) > 0: return self._completed_thoughts[len(self._completed_thoughts) - 1] return None
def _get_last_completed_thought(self) ->Optional[LLMThought]: """Return our most recent completed LLMThought, or None if we don't have one.""" if len(self._completed_thoughts) > 0: return self._completed_thoughts[len(self._completed_thoughts) - 1] return None
Return our most recent completed LLMThought, or None if we don't have one.
client
import meilisearch return meilisearch.Client(TEST_MEILI_HTTP_ADDR, TEST_MEILI_MASTER_KEY)
def client(self) ->'meilisearch.Client': import meilisearch return meilisearch.Client(TEST_MEILI_HTTP_ADDR, TEST_MEILI_MASTER_KEY)
null
on_tool_end
"""Run when tool ends running."""
def on_tool_end(self, output: str, **kwargs: Any) ->None: """Run when tool ends running."""
Run when tool ends running.
_is_vision_model
return 'vision' in model
def _is_vision_model(model: str) ->bool: return 'vision' in model
null
_prompt_type
"""Name of prompt type.""" return 'chat'
@property def _prompt_type(self) ->str: """Name of prompt type.""" return 'chat'
Name of prompt type.
add_documents
"""Adds documents to the docstore and vectorstores. Args: documents: List of documents to add ids: Optional list of ids for documents. If provided should be the same length as the list of documents. Can provided if parent documents are already in the docu...
def add_documents(self, documents: List[Document], ids: Optional[List[str]] =None, add_to_docstore: bool=True) ->None: """Adds documents to the docstore and vectorstores. Args: documents: List of documents to add ids: Optional list of ids for documents. If provided should be the...
Adds documents to the docstore and vectorstores. Args: documents: List of documents to add ids: Optional list of ids for documents. If provided should be the same length as the list of documents. Can provided if parent documents are already in the document store and you don't want to re-add ...
_select_relevance_score_fn
""" The 'correct' relevance function may differ depending on a few things, including: - the distance / similarity metric used by the VectorStore - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) - embedding dimensionality - etc. """ i...
def _select_relevance_score_fn(self) ->Callable[[float], float]: """ The 'correct' relevance function may differ depending on a few things, including: - the distance / similarity metric used by the VectorStore - the scale of your embeddings (OpenAI's are unit normed. Many others are ...
The 'correct' relevance function may differ depending on a few things, including: - the distance / similarity metric used by the VectorStore - the scale of your embeddings (OpenAI's are unit normed. Many others are not!) - embedding dimensionality - etc.
__init__
"""Initialize with parameters.""" if not integration_token: raise ValueError('integration_token must be provided') if not database_id: raise ValueError('database_id must be provided') self.token = integration_token self.database_id = database_id self.headers = {'Authorization': 'Bearer ' + self.token, 'Content-...
def __init__(self, integration_token: str, database_id: str, request_timeout_sec: Optional[int]=10) ->None: """Initialize with parameters.""" if not integration_token: raise ValueError('integration_token must be provided') if not database_id: raise ValueError('database_id must be provide...
Initialize with parameters.
_validate_tools
validate_tools_single_input(cls.__name__, tools) super()._validate_tools(tools) if len(tools) != 2: raise ValueError(f'Exactly two tools must be specified, but got {tools}') tool_names = {tool.name for tool in tools} if tool_names != {'Lookup', 'Search'}: raise ValueError( f'Tool names should be Lookup ...
@classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) ->None: validate_tools_single_input(cls.__name__, tools) super()._validate_tools(tools) if len(tools) != 2: raise ValueError( f'Exactly two tools must be specified, but got {tools}') tool_names = {tool.name for tool in ...
null
get_output_schema
runnable, config = self._prepare(config) return runnable.get_output_schema(config)
def get_output_schema(self, config: Optional[RunnableConfig]=None) ->Type[ BaseModel]: runnable, config = self._prepare(config) return runnable.get_output_schema(config)
null
configure
"""Configure the async callback manager. Args: inheritable_callbacks (Optional[Callbacks], optional): The inheritable callbacks. Defaults to None. local_callbacks (Optional[Callbacks], optional): The local callbacks. Defaults to None. verbose ...
@classmethod def configure(cls, inheritable_callbacks: Callbacks=None, local_callbacks: Callbacks=None, verbose: bool=False, inheritable_tags: Optional[List[ str]]=None, local_tags: Optional[List[str]]=None, inheritable_metadata: Optional[Dict[str, Any]]=None, local_metadata: Optional[Dict[str, Any]] =N...
Configure the async callback manager. Args: inheritable_callbacks (Optional[Callbacks], optional): The inheritable callbacks. Defaults to None. local_callbacks (Optional[Callbacks], optional): The local callbacks. Defaults to None. verbose (bool, optional): Whether to enable verbose mode. D...
_get_arn
region_name = self.client.meta.region_name service = 'comprehend' prompt_safety_endpoint = 'document-classifier-endpoint/prompt-safety' return f'arn:aws:{service}:{region_name}:aws:{prompt_safety_endpoint}'
def _get_arn(self) ->str: region_name = self.client.meta.region_name service = 'comprehend' prompt_safety_endpoint = 'document-classifier-endpoint/prompt-safety' return f'arn:aws:{service}:{region_name}:aws:{prompt_safety_endpoint}'
null
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs['question'] get_chat_history = self.get_chat_history or _get_chat_history chat_history_str = get_chat_history(inputs['chat_history']) if chat_history_str: callbacks = _run_manager.get_child() new_question = self.questi...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() question = inputs['question'] get_chat_history = self.get_chat_history or _get_chat_history chat_history_str ...
null
_similarity_search_with_relevance_scores
""" Default similarity search with relevance scores. Modify if necessary in subclass. Return docs and relevance scores in the range [0, 1]. 0 is dissimilar, 1 is most similar. Args: query: input text k: Number of Documents to return. Defaults to 4. ...
def _similarity_search_with_relevance_scores(self, query: str, k: int=4, metadata: Optional[Dict[str, Any]]=None, **kwargs: Any) ->List[Tuple[ Document, float]]: """ Default similarity search with relevance scores. Modify if necessary in subclass. Return docs and relevance scores in ...
Default similarity search with relevance scores. Modify if necessary in subclass. Return docs and relevance scores in the range [0, 1]. 0 is dissimilar, 1 is most similar. Args: query: input text k: Number of Documents to return. Defaults to 4. metadata: Optional, metadata filter **kwargs: kwargs to b...
similarity_search_by_vector_with_relevance_scores
"""Accepts a query_embedding (vector), and returns documents with similar embeddings along with their relevance scores.""" q_str = self._build_query_sql(embedding, distance_func, k, where_str) try: query_response = self._client.Queries.query(sql={'query': q_str}) except Exception as e: logger.error('Exc...
def similarity_search_by_vector_with_relevance_scores(self, embedding: List [float], k: int=4, distance_func: DistanceFunction=DistanceFunction. COSINE_SIM, where_str: Optional[str]=None, **kwargs: Any) ->List[Tuple[ Document, float]]: """Accepts a query_embedding (vector), and returns documents with ...
Accepts a query_embedding (vector), and returns documents with similar embeddings along with their relevance scores.
embeddings
return self._embedding
@property def embeddings(self) ->Embeddings: return self._embedding
null
setter
return ContextSet(_key, _value, prefix=self.prefix, **kwargs)
def setter(self, _key: Optional[str]=None, _value: Optional[SetValue]=None, /, **kwargs: SetValue) ->ContextSet: return ContextSet(_key, _value, prefix=self.prefix, **kwargs)
null
_default_api_url
return f'https://api-inference.huggingface.co/pipeline/feature-extraction/{self.model_name}'
@property def _default_api_url(self) ->str: return ( f'https://api-inference.huggingface.co/pipeline/feature-extraction/{self.model_name}' )
null
_parse_note
note_dict: Dict[str, Any] = {} resources = [] def add_prefix(element_tag: str) ->str: if prefix is None: return element_tag return f'{prefix}.{element_tag}' for elem in note: if elem.tag == 'content': note_dict[elem.tag] = EverNoteLoader._parse_content(elem.text) note_dict['content-r...
@staticmethod def _parse_note(note: List, prefix: Optional[str]=None) ->dict: note_dict: Dict[str, Any] = {} resources = [] def add_prefix(element_tag: str) ->str: if prefix is None: return element_tag return f'{prefix}.{element_tag}' for elem in note: if elem.tag ==...
null
_import_databricks
from langchain_community.llms.databricks import Databricks return Databricks
def _import_databricks() ->Any: from langchain_community.llms.databricks import Databricks return Databricks
null
parse_triples
"""Parse knowledge triples from the knowledge string.""" knowledge_str = knowledge_str.strip() if not knowledge_str or knowledge_str == 'NONE': return [] triple_strs = knowledge_str.split(KG_TRIPLE_DELIMITER) results = [] for triple_str in triple_strs: try: kg_triple = KnowledgeTriple.from_string(triple...
def parse_triples(knowledge_str: str) ->List[KnowledgeTriple]: """Parse knowledge triples from the knowledge string.""" knowledge_str = knowledge_str.strip() if not knowledge_str or knowledge_str == 'NONE': return [] triple_strs = knowledge_str.split(KG_TRIPLE_DELIMITER) results = [] for...
Parse knowledge triples from the knowledge string.
similarity_search_with_score_by_vector
"""Return docs most similar to query. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of D...
def similarity_search_with_score_by_vector(self, embedding: List[float], k: int=4, filter: Optional[Dict[str, Any]]=None, fetch_k: int=20, **kwargs: Any) ->List[Tuple[Document, float]]: """Return docs most similar to query. Args: embedding: Embedding vector to look up documents similar ...
Return docs most similar to query. Args: embedding: Embedding vector to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, Any]]): Filter by metadata. Defaults to None. fetch_k: (Optional[int]) Number of Documents to fetch before filtering. ...
init_in_memory
from docarray import BaseDoc from docarray.index import InMemoryExactNNIndex class MyDoc(BaseDoc): title: str title_embedding: NdArray[32] other_emb: NdArray[32] year: int embeddings = FakeEmbeddings(size=32) in_memory_db = InMemoryExactNNIndex[MyDoc]() in_memory_db.index([MyDoc(title=f'My document {i}'...
@pytest.fixture def init_in_memory() ->Tuple[InMemoryExactNNIndex, Dict[str, Any], FakeEmbeddings]: from docarray import BaseDoc from docarray.index import InMemoryExactNNIndex class MyDoc(BaseDoc): title: str title_embedding: NdArray[32] other_emb: NdArray[32] year: in...
null
__init__
super().__init__() warnings.warn( """`OSSContentFormatter` will be deprecated in the future. Please use `GPT2ContentFormatter` instead. """ )
def __init__(self) ->None: super().__init__() warnings.warn( """`OSSContentFormatter` will be deprecated in the future. Please use `GPT2ContentFormatter` instead. """ )
null
test_initialize_watsonxllm_cpd_bad_path_password_without_username
try: WatsonxLLM(model_id='google/flan-ul2', url= 'https://cpd-zen.apps.cpd48.cp.fyre.ibm.com', password='test_password') except ValueError as e: assert 'WATSONX_USERNAME' in e.__str__()
def test_initialize_watsonxllm_cpd_bad_path_password_without_username() ->None: try: WatsonxLLM(model_id='google/flan-ul2', url= 'https://cpd-zen.apps.cpd48.cp.fyre.ibm.com', password= 'test_password') except ValueError as e: assert 'WATSONX_USERNAME' in e.__str__()
null
test_chat_ernie_bot_with_model_name
chat = ErnieBotChat(model_name='ERNIE-Bot') message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
def test_chat_ernie_bot_with_model_name() ->None: chat = ErnieBotChat(model_name='ERNIE-Bot') message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
null
test_anthropic_streaming
"""Test streaming tokens from anthropic.""" chat = ChatAnthropic(model='test', streaming=True) message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
@pytest.mark.scheduled def test_anthropic_streaming() ->None: """Test streaming tokens from anthropic.""" chat = ChatAnthropic(model='test', streaming=True) message = HumanMessage(content='Hello') response = chat([message]) assert isinstance(response, AIMessage) assert isinstance(response.conten...
Test streaming tokens from anthropic.
get_num_tokens
return len(text.split())
def get_num_tokens(self, text: str) ->int: return len(text.split())
null
_should_continue
if self.max_iterations is not None and iterations >= self.max_iterations: return False if self.max_execution_time is not None and time_elapsed >= self.max_execution_time: return False return True
def _should_continue(self, iterations: int, time_elapsed: float) ->bool: if self.max_iterations is not None and iterations >= self.max_iterations: return False if (self.max_execution_time is not None and time_elapsed >= self. max_execution_time): return False return True
null
__init__
"""Initialize the record manager. Args: namespace (str): The namespace for the record manager. """ self.namespace = namespace
def __init__(self, namespace: str) ->None: """Initialize the record manager. Args: namespace (str): The namespace for the record manager. """ self.namespace = namespace
Initialize the record manager. Args: namespace (str): The namespace for the record manager.
test_vectara_from_files
"""Test end to end construction and search.""" urls = [ 'https://papers.nips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf' , 'https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/Final-DengYu-NOW-Book-DeepLearn2013-ForLecturesJuly2.docx' ] files_list = [] for ...
def test_vectara_from_files() ->None: """Test end to end construction and search.""" urls = [ 'https://papers.nips.cc/paper_files/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf' , 'https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/Final-DengYu-NOW-Book-DeepL...
Test end to end construction and search.
_identifying_params
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return {**{'model_kwargs': _model_kwargs}}
@property def _identifying_params(self) ->Dict[str, Any]: """Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return {**{'model_kwargs': _model_kwargs}}
Get the identifying parameters.
test_import_storage
from langchain_community.storage.upstash_redis import UpstashRedisStore
@pytest.mark.requires('upstash_redis') def test_import_storage() ->None: from langchain_community.storage.upstash_redis import UpstashRedisStore
null
convert_bytes
if isinstance(data, bytes): return data.decode('ascii') if isinstance(data, dict): return dict(map(convert_bytes, data.items())) if isinstance(data, list): return list(map(convert_bytes, data)) if isinstance(data, tuple): return map(convert_bytes, data) return data
def convert_bytes(data: Any) ->Any: if isinstance(data, bytes): return data.decode('ascii') if isinstance(data, dict): return dict(map(convert_bytes, data.items())) if isinstance(data, list): return list(map(convert_bytes, data)) if isinstance(data, tuple): return map(con...
null
_default_true
return True
def _default_true(_: Dict[str, Any]) ->bool: return True
null
_parse_input
"""Parse input of the form data["key1"][0]["key2"] into a list of keys.""" _res = re.findall('\\[.*?]', text) res = [i[1:-1].replace('"', '').replace("'", '') for i in _res] res = [(int(i) if i.isdigit() else i) for i in res] return res
def _parse_input(text: str) ->List[Union[str, int]]: """Parse input of the form data["key1"][0]["key2"] into a list of keys.""" _res = re.findall('\\[.*?]', text) res = [i[1:-1].replace('"', '').replace("'", '') for i in _res] res = [(int(i) if i.isdigit() else i) for i in res] return res
Parse input of the form data["key1"][0]["key2"] into a list of keys.
test_anthropic_model_name_param
llm = Anthropic(model_name='foo') assert llm.model == 'foo'
@pytest.mark.requires('anthropic') def test_anthropic_model_name_param() ->None: llm = Anthropic(model_name='foo') assert llm.model == 'foo'
null
lc_secrets
return {'url': 'WATSONX_URL', 'apikey': 'WATSONX_APIKEY', 'token': 'WATSONX_TOKEN', 'password': 'WATSONX_PASSWORD', 'username': 'WATSONX_USERNAME', 'instance_id': 'WATSONX_INSTANCE_ID'}
@property def lc_secrets(self) ->Dict[str, str]: return {'url': 'WATSONX_URL', 'apikey': 'WATSONX_APIKEY', 'token': 'WATSONX_TOKEN', 'password': 'WATSONX_PASSWORD', 'username': 'WATSONX_USERNAME', 'instance_id': 'WATSONX_INSTANCE_ID'}
null
test_huggingface_endpoint_summarization
"""Test valid call to HuggingFace summarization model.""" llm = HuggingFaceEndpoint(endpoint_url='', task='summarization') output = llm('Say foo:') assert isinstance(output, str)
@unittest.skip( 'This test requires an inference endpoint. Tested with Hugging Face endpoints' ) def test_huggingface_endpoint_summarization() ->None: """Test valid call to HuggingFace summarization model.""" llm = HuggingFaceEndpoint(endpoint_url='', task='summarization') output = llm('Say foo:') ...
Test valid call to HuggingFace summarization model.
get_tools
"""Get the tools in the toolkit.""" tools: List[BaseTool] = [] for vectorstore_info in self.vectorstores: description = VectorStoreQATool.get_description(vectorstore_info.name, vectorstore_info.description) qa_tool = VectorStoreQATool(name=vectorstore_info.name, description= description, vectors...
def get_tools(self) ->List[BaseTool]: """Get the tools in the toolkit.""" tools: List[BaseTool] = [] for vectorstore_info in self.vectorstores: description = VectorStoreQATool.get_description(vectorstore_info. name, vectorstore_info.description) qa_tool = VectorStoreQATool(name=v...
Get the tools in the toolkit.
_load_map_reduce_chain
_question_prompt = (question_prompt or map_reduce_prompt. QUESTION_PROMPT_SELECTOR.get_prompt(llm)) _combine_prompt = (combine_prompt or map_reduce_prompt. COMBINE_PROMPT_SELECTOR.get_prompt(llm)) map_chain = LLMChain(llm=llm, prompt=_question_prompt, verbose=verbose, callback_manager=callback_manager, call...
def _load_map_reduce_chain(llm: BaseLanguageModel, question_prompt: Optional[BasePromptTemplate]=None, combine_prompt: Optional[ BasePromptTemplate]=None, combine_document_variable_name: str= 'summaries', map_reduce_document_variable_name: str='context', collapse_prompt: Optional[BasePromptTemplate]=Non...
null
parse_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 try: func_call = copy.deepcopy(message.additional_kwargs['function_call']) except KeyError as exc: raise Outp...
def parse_result(self, result: List[Generation], *, partial: bool=False) ->Any: generation = result[0] if not isinstance(generation, ChatGeneration): raise OutputParserException( 'This output parser can only be used with a chat generation.') message = generation.message try: ...
null
add_texts
"""Embed texts and add to the vector store. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. Returns: List of ids from adding the texts into the vectorstore. """ ids: List[str] = [] ...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, **kwargs: Any) ->List[str]: """Embed texts and add to the vector store. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ...
Embed texts and add to the vector store. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. Returns: List of ids from adding the texts into the vectorstore.
_prepare_output
parsed = {'score': result['score']} if RUN_KEY in result: parsed[RUN_KEY] = result[RUN_KEY] return parsed
def _prepare_output(self, result: dict) ->dict: parsed = {'score': result['score']} if RUN_KEY in result: parsed[RUN_KEY] = result[RUN_KEY] return parsed
null
test_marqo_weighted_query
"""Test end to end construction and search.""" texts = ['Smartphone', 'Telephone'] marqo_search = Marqo.from_texts(texts=texts, index_name=INDEX_NAME, url= DEFAULT_MARQO_URL, api_key=DEFAULT_MARQO_API_KEY, verbose=False) results = marqo_search.similarity_search({'communications device': 1.0, 'Old technology': -...
def test_marqo_weighted_query(client: Marqo) ->None: """Test end to end construction and search.""" texts = ['Smartphone', 'Telephone'] marqo_search = Marqo.from_texts(texts=texts, index_name=INDEX_NAME, url =DEFAULT_MARQO_URL, api_key=DEFAULT_MARQO_API_KEY, verbose=False) results = marqo_search...
Test end to end construction and search.
test_character_text_splitter_short_words_first
"""Test splitting by character count when shorter words are first.""" text = 'a a foo bar baz' splitter = CharacterTextSplitter(separator=' ', chunk_size=3, chunk_overlap=1) output = splitter.split_text(text) expected_output = ['a a', 'foo', 'bar', 'baz'] assert output == expected_output
def test_character_text_splitter_short_words_first() ->None: """Test splitting by character count when shorter words are first.""" text = 'a a foo bar baz' splitter = CharacterTextSplitter(separator=' ', chunk_size=3, chunk_overlap=1) output = splitter.split_text(text) expected_output = ['a ...
Test splitting by character count when shorter words are first.
_Yield
self.write('(') self.write('yield') if t.value: self.write(' ') self.dispatch(t.value) self.write(')')
def _Yield(self, t): self.write('(') self.write('yield') if t.value: self.write(' ') self.dispatch(t.value) self.write(')')
null
mdelete
"""Delete the given keys.""" _keys = [self._get_prefixed_key(key) for key in keys] self.client.delete(*_keys)
def mdelete(self, keys: Sequence[str]) ->None: """Delete the given keys.""" _keys = [self._get_prefixed_key(key) for key in keys] self.client.delete(*_keys)
Delete the given keys.
get_prompt_strings
role_strings: List[Tuple[Type[BaseMessagePromptTemplate], str]] = [] role_strings.append((HumanMessagePromptTemplate, """Question: {question} Answer: Let's work this out in a step by step way to be sure we have the right answer:""" )) if stage == 'ideation': return role_strings role_strings.extend([*[(AIMes...
def get_prompt_strings(self, stage: str) ->List[Tuple[Type[ BaseMessagePromptTemplate], str]]: role_strings: List[Tuple[Type[BaseMessagePromptTemplate], str]] = [] role_strings.append((HumanMessagePromptTemplate, """Question: {question} Answer: Let's work this out in a step by step way to be sure we...
null
evaluation_name
"""Get the name of the evaluation. Returns ------- str The name of the evaluation. """ return f'score_string:{self.criterion_name}'
@property def evaluation_name(self) ->str: """Get the name of the evaluation. Returns ------- str The name of the evaluation. """ return f'score_string:{self.criterion_name}'
Get the name of the evaluation. Returns ------- str The name of the evaluation.
__iter__
"""Return self as a generator.""" return self
def __iter__(self) ->StreamingResponseGenerator: """Return self as a generator.""" return self
Return self as a generator.
_get_channel_id
request = self.youtube_client.search().list(part='id', q=channel_name, type ='channel', maxResults=1) response = request.execute() channel_id = response['items'][0]['id']['channelId'] return channel_id
def _get_channel_id(self, channel_name: str) ->str: request = self.youtube_client.search().list(part='id', q=channel_name, type='channel', maxResults=1) response = request.execute() channel_id = response['items'][0]['id']['channelId'] return channel_id
null
output_keys
""" Returns a list of output keys. This method defines the output keys that will be used to access the output values produced by the chain or function. It ensures that the specified keys are available to access the outputs. Returns: List[str]: A list of output keys....
@property def output_keys(self) ->List[str]: """ Returns a list of output keys. This method defines the output keys that will be used to access the output values produced by the chain or function. It ensures that the specified keys are available to access the outputs. Retur...
Returns a list of output keys. This method defines the output keys that will be used to access the output values produced by the chain or function. It ensures that the specified keys are available to access the outputs. Returns: List[str]: A list of output keys. Note: This method is considered private and ma...
test_single_agent_action_observation
intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log= 'Log1'), 'Observation1')] expected_result = """Log1 Observation: Observation1 Thought: """ assert format_log_to_str(intermediate_steps) == expected_result
def test_single_agent_action_observation() ->None: intermediate_steps = [(AgentAction(tool='Tool1', tool_input='input1', log='Log1'), 'Observation1')] expected_result = 'Log1\nObservation: Observation1\nThought: ' assert format_log_to_str(intermediate_steps) == expected_result
null
test_named_tool_decorator_return_direct
"""Test functionality when arguments and return direct are provided as input.""" @tool('search', return_direct=True) def search_api(query: str, *args: Any) ->str: """Search the API for the query.""" return 'API result' assert isinstance(search_api, BaseTool) assert search_api.name == 'search' assert search_api....
def test_named_tool_decorator_return_direct() ->None: """Test functionality when arguments and return direct are provided as input.""" @tool('search', return_direct=True) def search_api(query: str, *args: Any) ->str: """Search the API for the query.""" return 'API result' assert isinsta...
Test functionality when arguments and return direct are provided as input.
embed_documents
"""Return simple embeddings.""" return [([float(1.0)] * (ADA_TOKEN_COUNT - 1) + [float(i)]) for i in range( len(texts))]
def embed_documents(self, texts: List[str]) ->List[List[float]]: """Return simple embeddings.""" return [([float(1.0)] * (ADA_TOKEN_COUNT - 1) + [float(i)]) for i in range(len(texts))]
Return simple embeddings.
_create_rspace_client
"""Create a RSpace client.""" try: from rspace_client.eln import eln, field_content except ImportError: raise ImportError('You must run `pip install rspace_client`') try: eln = eln.ELNClient(self.url, self.api_key) eln.get_status() except Exception: raise Exception( f'Unable to initialize cl...
def _create_rspace_client(self) ->Any: """Create a RSpace client.""" try: from rspace_client.eln import eln, field_content except ImportError: raise ImportError('You must run `pip install rspace_client`') try: eln = eln.ELNClient(self.url, self.api_key) eln.get_status() ...
Create a RSpace client.
test_modern_treasury_loader
"""Test Modern Treasury file loader.""" modern_treasury_loader = ModernTreasuryLoader('payment_orders') documents = modern_treasury_loader.load() assert len(documents) == 1
def test_modern_treasury_loader() ->None: """Test Modern Treasury file loader.""" modern_treasury_loader = ModernTreasuryLoader('payment_orders') documents = modern_treasury_loader.load() assert len(documents) == 1
Test Modern Treasury file loader.
test_check_package_version_pass
check_package_version('PyYAML', gte_version='5.4.1')
def test_check_package_version_pass() ->None: check_package_version('PyYAML', gte_version='5.4.1')
null
test_wrong_temperature_1
chat = ErnieBotChat() message = HumanMessage(content='Hello') with pytest.raises(ValueError) as e: chat([message], temperature=1.2) assert 'parameter check failed, temperature range is (0, 1.0]' in str(e)
def test_wrong_temperature_1() ->None: chat = ErnieBotChat() message = HumanMessage(content='Hello') with pytest.raises(ValueError) as e: chat([message], temperature=1.2) assert 'parameter check failed, temperature range is (0, 1.0]' in str(e)
null
validate_environment
"""Validate that login and password exists in environment.""" login = get_from_dict_or_env(values, 'api_login', 'DATAFORSEO_LOGIN') password = get_from_dict_or_env(values, 'api_password', 'DATAFORSEO_PASSWORD') values['api_login'] = login values['api_password'] = password return values
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that login and password exists in environment.""" login = get_from_dict_or_env(values, 'api_login', 'DATAFORSEO_LOGIN') password = get_from_dict_or_env(values, 'api_password', 'DATAFORSEO_PASSWORD') values['api_log...
Validate that login and password exists in environment.
_generate
should_stream = stream if stream is not None else False if should_stream: stream_iter = self._stream(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 ...
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, stream: Optional[bool]=None, **kwargs: Any) ->ChatResult: should_stream = stream if stream is not None else False if should_stream: stream_iter = self._stream(m...
null
load
"""Load all documents.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load all documents.""" return list(self.lazy_load())
Load all documents.
lazy_load
""" Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator - created_at - last_upda...
def lazy_load(self) ->Iterator[Document]: """ Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator ...
Get issues of a GitHub repository. Returns: A list of Documents with attributes: - page_content - metadata - url - title - creator - created_at - last_update_time - closed_time - number of comments - sta...
from_api_operation
"""Create an OpenAPIEndpointChain from an operation and a spec.""" param_mapping = _ParamMapping(query_params=operation.query_params, body_params=operation.body_params, path_params=operation.path_params) requests_chain = APIRequesterChain.from_llm_and_typescript(llm, typescript_definition=operation.to_typescrip...
@classmethod def from_api_operation(cls, operation: APIOperation, llm: BaseLanguageModel, requests: Optional[Requests]=None, verbose: bool=False, return_intermediate_steps: bool=False, raw_response: bool=False, callbacks: Callbacks=None, **kwargs: Any) ->'OpenAPIEndpointChain': """Create an OpenAPIEndpo...
Create an OpenAPIEndpointChain from an operation and a spec.
connection_string_from_db_params
"""Return connection string from database parameters.""" return f'postgresql+{driver}://{user}:{password}@{host}:{port}/{database}'
@classmethod def connection_string_from_db_params(cls, driver: str, host: str, port: int, database: str, user: str, password: str) ->str: """Return connection string from database parameters.""" return f'postgresql+{driver}://{user}:{password}@{host}:{port}/{database}'
Return connection string from database parameters.
find_all_links
"""Extract all links from a raw html string. Args: raw_html: original html. pattern: Regex to use for extracting links from raw html. Returns: List[str]: all links """ pattern = pattern or DEFAULT_LINK_REGEX return list(set(re.findall(pattern, raw_html)))
def find_all_links(raw_html: str, *, pattern: Union[str, re.Pattern, None]=None ) ->List[str]: """Extract all links from a raw html string. Args: raw_html: original html. pattern: Regex to use for extracting links from raw html. Returns: List[str]: all links """ pattern...
Extract all links from a raw html string. Args: raw_html: original html. pattern: Regex to use for extracting links from raw html. Returns: List[str]: all links
mock_unstructured_local
with patch( 'langchain_community.document_loaders.lakefs.UnstructuredLakeFSLoader' ) as mock_unstructured_lakefs: mock_unstructured_lakefs.return_value.load.return_value = [( 'text content', 'pdf content')] yield mock_unstructured_lakefs.return_value
@pytest.fixture def mock_unstructured_local() ->Any: with patch( 'langchain_community.document_loaders.lakefs.UnstructuredLakeFSLoader' ) as mock_unstructured_lakefs: mock_unstructured_lakefs.return_value.load.return_value = [( 'text content', 'pdf content')] yield mock_u...
null
load_guide
"""Load a guide Args: url_override: A URL to override the default URL. Returns: List[Document] """ if url_override is None: url = IFIXIT_BASE_URL + '/guides/' + self.id else: url = url_override res = requests.get(url) if res.status_code != 200: raise ValueError('Could ...
def load_guide(self, url_override: Optional[str]=None) ->List[Document]: """Load a guide Args: url_override: A URL to override the default URL. Returns: List[Document] """ if url_override is None: url = IFIXIT_BASE_URL + '/guides/' + self.id else: url =...
Load a guide Args: url_override: A URL to override the default URL. Returns: List[Document]
output_keys
"""Expect input key. :meta private: """ _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = _output_keys + ['intermediate_steps'] return _output_keys
@property def output_keys(self) ->List[str]: """Expect input key. :meta private: """ _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = _output_keys + ['intermediate_steps'] return _output_keys
Expect input key. :meta private:
_split_text
"""Split incoming text and return chunks.""" final_chunks = [] separator = separators[-1] new_separators = [] for i, _s in enumerate(separators): _separator = _s if self._is_separator_regex else re.escape(_s) if _s == '': separator = _s break if re.search(_separator, text): separator...
def _split_text(self, text: str, separators: List[str]) ->List[str]: """Split incoming text and return chunks.""" final_chunks = [] separator = separators[-1] new_separators = [] for i, _s in enumerate(separators): _separator = _s if self._is_separator_regex else re.escape(_s) if _s ...
Split incoming text and return chunks.
_configure
"""Configure the callback manager. Args: callback_manager_cls (Type[T]): The callback manager class. inheritable_callbacks (Optional[Callbacks], optional): The inheritable callbacks. Defaults to None. local_callbacks (Optional[Callbacks], optional): The local callbacks. ...
def _configure(callback_manager_cls: Type[T], inheritable_callbacks: Callbacks=None, local_callbacks: Callbacks=None, verbose: bool=False, inheritable_tags: Optional[List[str]]=None, local_tags: Optional[List[ str]]=None, inheritable_metadata: Optional[Dict[str, Any]]=None, local_metadata: Optional[Dict...
Configure the callback manager. Args: callback_manager_cls (Type[T]): The callback manager class. inheritable_callbacks (Optional[Callbacks], optional): The inheritable callbacks. Defaults to None. local_callbacks (Optional[Callbacks], optional): The local callbacks. Defaults to None. v...
check_if_not_null
"""Check if the values are not None or empty string""" for prop, value in zip(props, values): if not value: raise ValueError(f'Parameter `{prop}` must not be None or empty string' )
def check_if_not_null(props: List[str], values: List[Any]) ->None: """Check if the values are not None or empty string""" for prop, value in zip(props, values): if not value: raise ValueError( f'Parameter `{prop}` must not be None or empty string')
Check if the values are not None or empty string
collection
return prepare_collection()
@pytest.fixture() def collection() ->Any: return prepare_collection()
null
test_all_imports
"""Simple test to make sure all things can be imported.""" for cls in vectorstores.__all__: if cls not in ['AlibabaCloudOpenSearchSettings', 'ClickhouseSettings', 'MyScaleSettings']: assert issubclass(getattr(vectorstores, cls), VectorStore)
def test_all_imports() ->None: """Simple test to make sure all things can be imported.""" for cls in vectorstores.__all__: if cls not in ['AlibabaCloudOpenSearchSettings', 'ClickhouseSettings', 'MyScaleSettings']: assert issubclass(getattr(vectorstores, cls), VectorStore)
Simple test to make sure all things can be imported.
_call
return prompt
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: return prompt
null