method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_get_text_from_llm_result
"""Between steps, only the LLM result text is passed, not the LLMResult object. This function extracts the text from an LLMResult.""" if len(result.generations) != 1: raise ValueError( f'In SmartLLM the LLM result in step {step} is not exactly 1 element. This should never happen' ) if len(re...
def _get_text_from_llm_result(self, result: LLMResult, step: str) ->str: """Between steps, only the LLM result text is passed, not the LLMResult object. This function extracts the text from an LLMResult.""" if len(result.generations) != 1: raise ValueError( f'In SmartLLM the LLM resu...
Between steps, only the LLM result text is passed, not the LLMResult object. This function extracts the text from an LLMResult.
print_text
"""Print text with highlighting and no end characters.""" text_to_print = get_colored_text(text, color) if color else text print(text_to_print, end=end, file=file) if file: file.flush()
def print_text(text: str, color: Optional[str]=None, end: str='', file: Optional[TextIO]=None) ->None: """Print text with highlighting and no end characters.""" text_to_print = get_colored_text(text, color) if color else text print(text_to_print, end=end, file=file) if file: file.flush()
Print text with highlighting and no end characters.
test_finish
"""Test standard parsing of agent finish.""" parser = ReActSingleInputOutputParser() _input = """Thought: agent thought here Final Answer: The temperature is 100""" output = parser.invoke(_input) expected_output = AgentFinish(return_values={'output': 'The temperature is 100'}, log=_input) assert output == expected_...
def test_finish() ->None: """Test standard parsing of agent finish.""" parser = ReActSingleInputOutputParser() _input = ( 'Thought: agent thought here\nFinal Answer: The temperature is 100') output = parser.invoke(_input) expected_output = AgentFinish(return_values={'output': 'The te...
Test standard parsing of agent finish.
similarity_search_with_score
""" Run a similarity search with BagelDB and return documents with their corresponding similarity scores. Args: query (str): The query text to search for similar documents. k (int): The number of results to return. where (Optional[Dict[str, str]]): Filter usi...
def similarity_search_with_score(self, query: str, k: int=DEFAULT_K, where: Optional[Dict[str, str]]=None, **kwargs: Any) ->List[Tuple[Document, float] ]: """ Run a similarity search with BagelDB and return documents with their corresponding similarity scores. Args: quer...
Run a similarity search with BagelDB and return documents with their corresponding similarity scores. Args: query (str): The query text to search for similar documents. k (int): The number of results to return. where (Optional[Dict[str, str]]): Filter using metadata. Returns: List[Tuple[Document, floa...
_run
"""Use the Golden tool.""" return self.api_wrapper.run(query)
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] =None) ->str: """Use the Golden tool.""" return self.api_wrapper.run(query)
Use the Golden tool.
get
"""GET the URL and return the text.""" return self.requests.get(url, **kwargs).text
def get(self, url: str, **kwargs: Any) ->str: """GET the URL and return the text.""" return self.requests.get(url, **kwargs).text
GET the URL and return the text.
__init__
"""Create a new TextSplitter. Args: chunk_size: Maximum size of chunks to return chunk_overlap: Overlap in characters between chunks length_function: Function that measures the length of given chunks keep_separator: Whether to keep the separator in the chunks ...
def __init__(self, chunk_size: int=4000, chunk_overlap: int=200, length_function: Callable[[str], int]=len, keep_separator: bool=False, add_start_index: bool=False, strip_whitespace: bool=True) ->None: """Create a new TextSplitter. Args: chunk_size: Maximum size of chunks to return ...
Create a new TextSplitter. Args: chunk_size: Maximum size of chunks to return chunk_overlap: Overlap in characters between chunks length_function: Function that measures the length of given chunks keep_separator: Whether to keep the separator in the chunks add_start_index: If `True`, includes chunk...
embed_documents
"""Compute doc embeddings using a JohnSnowLabs transformer model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ df = self.model.predict(texts, output_level='document') emb_col = None for c in df.columns: if 'embedding' ...
def embed_documents(self, texts: List[str]) ->List[List[float]]: """Compute doc embeddings using a JohnSnowLabs transformer model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ df = self.model.predict(texts, output_...
Compute doc embeddings using a JohnSnowLabs transformer model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text.
validate_limit_to_domains
"""Check that allowed domains are valid.""" if 'limit_to_domains' not in values: raise ValueError( 'You must specify a list of domains to limit access using `limit_to_domains`' ) if not values['limit_to_domains'] and values['limit_to_domains'] is not None: raise ValueError( 'Please provi...
@root_validator(pre=True) def validate_limit_to_domains(cls, values: Dict) ->Dict: """Check that allowed domains are valid.""" if 'limit_to_domains' not in values: raise ValueError( 'You must specify a list of domains to limit access using `limit_to_domains`' ) if not values[...
Check that allowed domains are valid.
lookup
"""Look up based on prompt and llm_string.""" hit_with_id = self.lookup_with_id(prompt, llm_string) if hit_with_id is not None: return hit_with_id[1] else: return None
def lookup(self, prompt: str, llm_string: str) ->Optional[RETURN_VAL_TYPE]: """Look up based on prompt and llm_string.""" hit_with_id = self.lookup_with_id(prompt, llm_string) if hit_with_id is not None: return hit_with_id[1] else: return None
Look up based on prompt and llm_string.
test_loadnotebook_eachnoteisindividualdocument
loader = EverNoteLoader(self.example_notebook_path('sample_notebook.enex'), False) documents = loader.load() assert len(documents) == 2
def test_loadnotebook_eachnoteisindividualdocument(self) ->None: loader = EverNoteLoader(self.example_notebook_path( 'sample_notebook.enex'), False) documents = loader.load() assert len(documents) == 2
null
_llm_type
"""Return type of chat model.""" return 'anyscale-chat'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'anyscale-chat'
Return type of chat model.
yield_keys
"""Get an iterator over keys that match the given prefix.""" yield from self.store.yield_keys(prefix=prefix)
def yield_keys(self, *, prefix: Optional[str]=None) ->Union[Iterator[K], Iterator[str]]: """Get an iterator over keys that match the given prefix.""" yield from self.store.yield_keys(prefix=prefix)
Get an iterator over keys that match the given prefix.
text
"""To log the input text as text file artifact.""" with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id=self. mlf_expid): self.mlflow.log_text(text, f'{filename}.txt')
def text(self, text: str, filename: str) ->None: """To log the input text as text file artifact.""" with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id= self.mlf_expid): self.mlflow.log_text(text, f'{filename}.txt')
To log the input text as text file artifact.
test_graph_cypher_qa_chain_prompt_selection_4
qa_prompt_template = 'QA Prompt' cypher_prompt_template = 'Cypher Prompt' memory = ConversationBufferMemory(memory_key='chat_history') readonlymemory = ReadOnlySharedMemory(memory=memory) qa_prompt = PromptTemplate(template=qa_prompt_template, input_variables=[]) cypher_prompt = PromptTemplate(template=cypher_prompt_te...
def test_graph_cypher_qa_chain_prompt_selection_4() ->None: qa_prompt_template = 'QA Prompt' cypher_prompt_template = 'Cypher Prompt' memory = ConversationBufferMemory(memory_key='chat_history') readonlymemory = ReadOnlySharedMemory(memory=memory) qa_prompt = PromptTemplate(template=qa_prompt_templa...
null
test_dashvector_with_text_with_metadatas
metadatas = [{'meta': i} for i in range(len(texts))] dashvector = DashVector.from_texts(texts=texts, embedding=FakeEmbeddings(), metadatas=metadatas, ids=ids) sleep(0.5) output = dashvector.similarity_search('foo', k=1) assert output == [Document(page_content='foo', metadata={'meta': 0})]
def test_dashvector_with_text_with_metadatas() ->None: metadatas = [{'meta': i} for i in range(len(texts))] dashvector = DashVector.from_texts(texts=texts, embedding= FakeEmbeddings(), metadatas=metadatas, ids=ids) sleep(0.5) output = dashvector.similarity_search('foo', k=1) assert output ==...
null
test_elasticsearch_with_internal_user_agent
"""Test to make sure the user-agent is set correctly.""" texts = ['foo'] store = ElasticsearchStore.from_texts(texts, FakeEmbeddings(), ** elasticsearch_connection, index_name=index_name) user_agent = store.client._headers['User-Agent'] pattern = '^langchain-py-vs/\\d+\\.\\d+\\.\\d+$' match = re.match(pattern, user...
def test_elasticsearch_with_internal_user_agent(self, elasticsearch_connection: Dict, index_name: str) ->None: """Test to make sure the user-agent is set correctly.""" texts = ['foo'] store = ElasticsearchStore.from_texts(texts, FakeEmbeddings(), ** elasticsearch_connection, index_name=index_nam...
Test to make sure the user-agent is set correctly.
_vectorstore_from_texts
from cassandra.cluster import Cluster keyspace = 'vector_test_keyspace' table_name = 'vector_test_table' cluster = Cluster() session = cluster.connect() session.execute( f"CREATE KEYSPACE IF NOT EXISTS {keyspace} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': 1}}" ) if drop: session.e...
def _vectorstore_from_texts(texts: List[str], metadatas: Optional[List[dict ]]=None, embedding_class: Type[Embeddings]=ConsistentFakeEmbeddings, drop: bool=True) ->Cassandra: from cassandra.cluster import Cluster keyspace = 'vector_test_keyspace' table_name = 'vector_test_table' cluster = Cluste...
null
get_output_schema
return self.combine_docs_chain.get_output_schema(config)
def get_output_schema(self, config: Optional[RunnableConfig]=None) ->Type[ BaseModel]: return self.combine_docs_chain.get_output_schema(config)
null
create_ernie_fn_runnable
"""Create a runnable sequence that uses Ernie functions. Args: functions: A sequence of either dictionaries, pydantic.BaseModels classes, or Python functions. If dictionaries are passed in, they are assumed to already be a valid Ernie functions. If only a single function...
def create_ernie_fn_runnable(functions: Sequence[Union[Dict[str, Any], Type [BaseModel], Callable]], llm: Runnable, prompt: BasePromptTemplate, *, output_parser: Optional[Union[BaseOutputParser, BaseGenerationOutputParser]]=None, **kwargs: Any) ->Runnable: """Create a runnable sequence that uses Ernie f...
Create a runnable sequence that uses Ernie functions. Args: functions: A sequence of either dictionaries, pydantic.BaseModels classes, or Python functions. If dictionaries are passed in, they are assumed to already be a valid Ernie functions. If only a single function is passed in, then it ...
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
test_multimodal_history
llm = ChatVertexAI(model_name='gemini-ultra-vision') gcs_url = ( 'gs://cloud-samples-data/generative-ai/image/320px-Felis_catus-cat_on_snow.jpg' ) image_message = {'type': 'image_url', 'image_url': {'url': gcs_url}} text_message = {'type': 'text', 'text': 'What is shown in this image?'} message1 = HumanMessage(...
def test_multimodal_history() ->None: llm = ChatVertexAI(model_name='gemini-ultra-vision') gcs_url = ( 'gs://cloud-samples-data/generative-ai/image/320px-Felis_catus-cat_on_snow.jpg' ) image_message = {'type': 'image_url', 'image_url': {'url': gcs_url}} text_message = {'type': 'text', 't...
null
_call
"""Run the logic of this chain and return the output.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() name = inputs[self.input_key].pop('name') args = inputs[self.input_key].pop('arguments') _pretty_name = get_colored_text(name, 'green') _pretty_args = get_colored_text(json.dumps(args, in...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: """Run the logic of this chain and return the output.""" _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() name = inputs[self.input_key].pop('name') args = inp...
Run the logic of this chain and return the output.
validate_dataframe
import pandas as pd if issubclass(type(val), pd.DataFrame): return val if pd.DataFrame(val).empty: raise ValueError('DataFrame cannot be empty.') raise TypeError( "Wrong type for 'dataframe', must be a subclass of Pandas DataFrame (pd.DataFrame)" )
@validator('dataframe') def validate_dataframe(cls, val: Any) ->Any: import pandas as pd if issubclass(type(val), pd.DataFrame): return val if pd.DataFrame(val).empty: raise ValueError('DataFrame cannot be empty.') raise TypeError( "Wrong type for 'dataframe', must be a subclass ...
null
_Delete
self.fill('del ') interleave(lambda : self.write(', '), self.dispatch, t.targets)
def _Delete(self, t): self.fill('del ') interleave(lambda : self.write(', '), self.dispatch, t.targets)
null
_query
try: import mlflow.gateway except ImportError as e: raise ImportError( 'Could not import `mlflow.gateway` module. Please install it with `pip install mlflow[gateway]`.' ) from e embeddings = [] for txt in _chunk(texts, 20): resp = mlflow.gateway.query(self.route, data={'text': txt}) embe...
def _query(self, texts: List[str]) ->List[List[float]]: try: import mlflow.gateway except ImportError as e: raise ImportError( 'Could not import `mlflow.gateway` module. Please install it with `pip install mlflow[gateway]`.' ) from e embeddings = [] for txt in _ch...
null
is_lc_serializable
return False
@classmethod def is_lc_serializable(cls) ->bool: return False
null
run_query
return db.run(query)
def run_query(query): return db.run(query)
null
test_pypdf_parser
"""Test PyPDF parser.""" _assert_with_parser(PyPDFParser())
@pytest.mark.requires('pypdf') def test_pypdf_parser() ->None: """Test PyPDF parser.""" _assert_with_parser(PyPDFParser())
Test PyPDF parser.
validate_environment
"""Validate that api key exists in environment.""" zapier_nla_api_key_default = None if 'zapier_nla_oauth_access_token' in values: zapier_nla_api_key_default = '' else: values['zapier_nla_oauth_access_token'] = '' zapier_nla_api_key = get_from_dict_or_env(values, 'zapier_nla_api_key', 'ZAPIER_NLA_API_KEY', ...
@root_validator(pre=True) def validate_environment(cls, values: Dict) ->Dict: """Validate that api key exists in environment.""" zapier_nla_api_key_default = None if 'zapier_nla_oauth_access_token' in values: zapier_nla_api_key_default = '' else: values['zapier_nla_oauth_access_token'] =...
Validate that api key exists in environment.
tag
return RedisTag(field)
@staticmethod def tag(field: str) ->'RedisTag': return RedisTag(field)
null
test_thoughts_rollback
a = Thought(text='a', validity=ThoughtValidity.VALID_INTERMEDIATE) b = Thought(text='b', validity=ThoughtValidity.VALID_INTERMEDIATE) c_1 = Thought(text='c_1', validity=ThoughtValidity.VALID_INTERMEDIATE) c_2 = Thought(text='c_2', validity=ThoughtValidity.VALID_INTERMEDIATE) c_3 = Thought(text='c_3', validity=ThoughtVa...
def test_thoughts_rollback(self) ->None: a = Thought(text='a', validity=ThoughtValidity.VALID_INTERMEDIATE) b = Thought(text='b', validity=ThoughtValidity.VALID_INTERMEDIATE) c_1 = Thought(text='c_1', validity=ThoughtValidity.VALID_INTERMEDIATE) c_2 = Thought(text='c_2', validity=ThoughtValidity.VALID_I...
null
model_id
return 'your_model_id'
@pytest.fixture def model_id() ->str: return 'your_model_id'
null
__init__
"""Initialize the modelscope""" super().__init__(**kwargs) try: from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks except ImportError as e: raise ImportError( 'Could not import some python packages.Please install it with `pip install modelscope`.' ) from e ...
def __init__(self, **kwargs: Any): """Initialize the modelscope""" super().__init__(**kwargs) try: from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks except ImportError as e: raise ImportError( 'Could not import some python packages....
Initialize the modelscope
_import_merriam_webster_tool
from langchain_community.tools.merriam_webster.tool import MerriamWebsterQueryRun return MerriamWebsterQueryRun
def _import_merriam_webster_tool() ->Any: from langchain_community.tools.merriam_webster.tool import MerriamWebsterQueryRun return MerriamWebsterQueryRun
null
similarity_search
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List o...
def similarity_search(self, query: str, k: int=4, search_k: int=-1, ** kwargs: Any) ->List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to sea...
Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. search_k: inspect up to search_k nodes which defaults to n_trees * n if not provided Returns: List of Documents most similar to the query.
_run
"""Use the tool.""" try: return self.api_wrapper.results(query, self.max_results) except Exception as e: return repr(e)
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] =None) ->Union[List[Dict], str]: """Use the tool.""" try: return self.api_wrapper.results(query, self.max_results) except Exception as e: return repr(e)
Use the tool.
_on_retriever_end
"""Process the Retriever Run.""" self._submit(self._update_run_single, _copy(run))
def _on_retriever_end(self, run: Run) ->None: """Process the Retriever Run.""" self._submit(self._update_run_single, _copy(run))
Process the Retriever Run.
_load_api_chain
if 'api_request_chain' in config: api_request_chain_config = config.pop('api_request_chain') api_request_chain = load_chain_from_config(api_request_chain_config) elif 'api_request_chain_path' in config: api_request_chain = load_chain(config.pop('api_request_chain_path')) else: raise ValueError( ...
def _load_api_chain(config: dict, **kwargs: Any) ->APIChain: if 'api_request_chain' in config: api_request_chain_config = config.pop('api_request_chain') api_request_chain = load_chain_from_config(api_request_chain_config) elif 'api_request_chain_path' in config: api_request_chain = load...
null
_convert_message_to_dict
message_dict: Dict[str, Any] if isinstance(message, ChatMessage): message_dict = {'role': message.role, 'content': message.content} elif isinstance(message, SystemMessage): message_dict = {'role': 'system', 'content': message.content} elif isinstance(message, HumanMessage): message_dict = {'role': 'user', '...
def _convert_message_to_dict(message: BaseMessage) ->dict: message_dict: Dict[str, Any] if isinstance(message, ChatMessage): message_dict = {'role': message.role, 'content': message.content} elif isinstance(message, SystemMessage): message_dict = {'role': 'system', 'content': message.content...
null
lower_case_name
if v is not None: raise NotImplementedError('system_setting is not implemented yet') return v
@validator('system_settings') def lower_case_name(cls, v: str) ->Union[str, None]: if v is not None: raise NotImplementedError('system_setting is not implemented yet') return v
null
test_fake_retriever_v1_with_kwargs_upgrade
callbacks = FakeCallbackHandler() assert fake_retriever_v1_with_kwargs._new_arg_supported is False assert fake_retriever_v1_with_kwargs._expects_other_args is True results: List[Document] = fake_retriever_v1_with_kwargs.get_relevant_documents( 'Foo', callbacks=[callbacks], where_filter={'foo': 'bar'}) assert result...
def test_fake_retriever_v1_with_kwargs_upgrade(fake_retriever_v1_with_kwargs: BaseRetriever) ->None: callbacks = FakeCallbackHandler() assert fake_retriever_v1_with_kwargs._new_arg_supported is False assert fake_retriever_v1_with_kwargs._expects_other_args is True results: List[Document ] = ...
null
__init__
"""Initialize the loader with an Apify dataset ID and a mapping function. Args: dataset_id (str): The ID of the dataset on the Apify platform. dataset_mapping_function (Callable): A function that takes a single dictionary (an Apify dataset item) and converts it to an ins...
def __init__(self, dataset_id: str, dataset_mapping_function: Callable[[ Dict], Document]): """Initialize the loader with an Apify dataset ID and a mapping function. Args: dataset_id (str): The ID of the dataset on the Apify platform. dataset_mapping_function (Callable): A funct...
Initialize the loader with an Apify dataset ID and a mapping function. Args: dataset_id (str): The ID of the dataset on the Apify platform. dataset_mapping_function (Callable): A function that takes a single dictionary (an Apify dataset item) and converts it to an instance of the Document class...
load
with open(self.log_file, encoding='utf8') as f: data = json.load(f)[:self.num_logs] if self.num_logs else json.load(f) documents = [] for d in data: title = d['title'] messages = d['mapping'] text = ''.join([concatenate_rows(messages[key]['message'], title) for idx, key in enumerate(messages) i...
def load(self) ->List[Document]: with open(self.log_file, encoding='utf8') as f: data = json.load(f)[:self.num_logs] if self.num_logs else json.load(f) documents = [] for d in data: title = d['title'] messages = d['mapping'] text = ''.join([concatenate_rows(messages[key]['mes...
null
check_operator_misuse
"""Decorator to check for misuse of equality operators.""" @wraps(func) def wrapper(instance: Any, *args: Any, **kwargs: Any) ->Any: other = kwargs.get('other') if 'other' in kwargs else None if not other: for arg in args: if isinstance(arg, type(instance)): other = arg ...
def check_operator_misuse(func: Callable) ->Callable: """Decorator to check for misuse of equality operators.""" @wraps(func) def wrapper(instance: Any, *args: Any, **kwargs: Any) ->Any: other = kwargs.get('other') if 'other' in kwargs else None if not other: for arg in args: ...
Decorator to check for misuse of equality operators.
_llm_type
"""Return type of llm.""" return 'google_palm'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'google_palm'
Return type of llm.
test_rwkv_inference
"""Test valid gpt4all inference.""" model_path = _download_model() llm = RWKV(model=model_path, tokens_path='20B_tokenizer.json', strategy= 'cpu fp32') output = llm('Say foo:') assert isinstance(output, str)
@pytest.mark.filterwarnings('ignore::UserWarning:') def test_rwkv_inference() ->None: """Test valid gpt4all inference.""" model_path = _download_model() llm = RWKV(model=model_path, tokens_path='20B_tokenizer.json', strategy ='cpu fp32') output = llm('Say foo:') assert isinstance(output, str...
Test valid gpt4all inference.
_stream
params = self._convert_prompt_msg_params(messages, **kwargs) for res in self.client.stream_chat(params): if res: msg = convert_dict_to_message(res) yield ChatGenerationChunk(message=AIMessageChunk(content=msg.content)) if run_manager: run_manager.on_llm_new_token(cast(str, msg.co...
def _stream(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->Iterator[ChatGenerationChunk]: params = self._convert_prompt_msg_params(messages, **kwargs) for res in self.client.stream_chat(params): if res: ...
null
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
embed_documents
"""Return simple embeddings.""" return [([float(1.0)] * (OS_TOKEN_COUNT - 1) + [float(i + 1)]) for i in range(len(embedding_texts))]
def embed_documents(self, embedding_texts: List[str]) ->List[List[float]]: """Return simple embeddings.""" return [([float(1.0)] * (OS_TOKEN_COUNT - 1) + [float(i + 1)]) for i in range(len(embedding_texts))]
Return simple embeddings.
input_keys
"""Expect input key. :meta private: """ return [self.input_key]
@property def input_keys(self) ->List[str]: """Expect input key. :meta private: """ return [self.input_key]
Expect input key. :meta private:
on_llm_error
self._container.markdown('**LLM encountered an error...**') self._container.exception(error)
def on_llm_error(self, error: BaseException, **kwargs: Any) ->None: self._container.markdown('**LLM encountered an error...**') self._container.exception(error)
null
return_stopped_response
"""Return response when agent has been stopped due to max iterations.""" if early_stopping_method == 'force': return AgentFinish({'output': 'Agent stopped due to max iterations.'}, '') else: raise ValueError( f'Got unsupported early_stopping_method `{early_stopping_method}`')
def return_stopped_response(self, early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) ->AgentFinish: """Return response when agent has been stopped due to max iterations.""" if early_stopping_method == 'force': return AgentFinish({'output': ...
Return response when agent has been stopped due to max iterations.
_import_youtube_search
from langchain_community.tools.youtube.search import YouTubeSearchTool return YouTubeSearchTool
def _import_youtube_search() ->Any: from langchain_community.tools.youtube.search import YouTubeSearchTool return YouTubeSearchTool
null
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.
test_search_filter_with_scores
texts = ['hello bagel', 'this is langchain'] metadatas = [{'source': 'notion'}, {'source': 'google'}] txt_search = Bagel.from_texts(cluster_name='testing', texts=texts, metadatas=metadatas) output = txt_search.similarity_search_with_score('hello bagel', k=1, where= {'source': 'notion'}) assert output == [(Docum...
def test_search_filter_with_scores() ->None: texts = ['hello bagel', 'this is langchain'] metadatas = [{'source': 'notion'}, {'source': 'google'}] txt_search = Bagel.from_texts(cluster_name='testing', texts=texts, metadatas=metadatas) output = txt_search.similarity_search_with_score('hello bagel...
null
_call
"""Call out to AI21's complete endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python resp...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call out to AI21's complete endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when genera...
Call out to AI21's complete endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use when generating. Returns: The string generated by the model. Example: .. code-block:: python response = ai21("Tell me a joke.")
get_action_and_input
output = output_parser.parse_folder(text) if isinstance(output, AgentAction): return output.tool, str(output.tool_input) else: return 'Final Answer', output.return_values['output']
def get_action_and_input(text: str) ->Tuple[str, str]: output = output_parser.parse_folder(text) if isinstance(output, AgentAction): return output.tool, str(output.tool_input) else: return 'Final Answer', output.return_values['output']
null
_generate
text_generations: List[str] = [] for i in range(0, len(prompts), self.batch_size): batch_prompts = prompts[i:i + self.batch_size] responses = self.pipeline(batch_prompts) for j, response in enumerate(responses): if isinstance(response, list): response = response[0] if self.pipeli...
def _generate(self, prompts: List[str], stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->LLMResult: text_generations: List[str] = [] for i in range(0, len(prompts), self.batch_size): batch_prompts = prompts[i:i + self.batch_size] res...
null
test_huggingface_tokenizer
"""Test text splitter that uses a HuggingFace tokenizer.""" from transformers import GPT2TokenizerFast tokenizer = GPT2TokenizerFast.from_pretrained('gpt2') text_splitter = CharacterTextSplitter.from_huggingface_tokenizer(tokenizer, separator=' ', chunk_size=1, chunk_overlap=0) output = text_splitter.split_text('fo...
def test_huggingface_tokenizer() ->None: """Test text splitter that uses a HuggingFace tokenizer.""" from transformers import GPT2TokenizerFast tokenizer = GPT2TokenizerFast.from_pretrained('gpt2') text_splitter = CharacterTextSplitter.from_huggingface_tokenizer(tokenizer, separator=' ', chunk_s...
Test text splitter that uses a HuggingFace tokenizer.
delete
""" Args: skip_strict_exist_check: Deprecated. This is not used basically. """ try: from vald.v1.payload import payload_pb2 from vald.v1.vald import remove_pb2_grpc except ImportError: raise ValueError( 'Could not import vald-client-python python package. Please install i...
def delete(self, ids: Optional[List[str]]=None, skip_strict_exist_check: bool=False, grpc_metadata: Optional[Any]=None, **kwargs: Any) ->Optional[ bool]: """ Args: skip_strict_exist_check: Deprecated. This is not used basically. """ try: from vald.v1.payload import pa...
Args: skip_strict_exist_check: Deprecated. This is not used basically.
_should_continue
return self.iterations < 2
def _should_continue(self) ->bool: return self.iterations < 2
null
test_delete
with mock.patch('nuclia.sdk.resource.NucliaResource.delete', new_callable= FakeDelete): ndb = NucliaDB(knowledge_box='YOUR_KB_ID', local=False, api_key= 'YOUR_API_KEY') success = ndb.delete(['123', '456']) assert success
def test_delete() ->None: with mock.patch('nuclia.sdk.resource.NucliaResource.delete', new_callable=FakeDelete): ndb = NucliaDB(knowledge_box='YOUR_KB_ID', local=False, api_key= 'YOUR_API_KEY') success = ndb.delete(['123', '456']) assert success
null
test_runnable_context_seq_key_not_found
seq: Runnable = {'bar': Context.setter('input')} | Context.getter('foo') with pytest.raises(ValueError): seq.invoke('foo')
def test_runnable_context_seq_key_not_found() ->None: seq: Runnable = {'bar': Context.setter('input')} | Context.getter('foo') with pytest.raises(ValueError): seq.invoke('foo')
null
validate_environment
"""Validate that we have all required info to access Clarifai platform and python package exists in environment.""" values['pat'] = get_from_dict_or_env(values, 'pat', 'CLARIFAI_PAT') user_id = values.get('user_id') app_id = values.get('app_id') model_id = values.get('model_id') model_url = values.get('model_ur...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that we have all required info to access Clarifai platform and python package exists in environment.""" values['pat'] = get_from_dict_or_env(values, 'pat', 'CLARIFAI_PAT') user_id = values.get('user_id') app_id = v...
Validate that we have all required info to access Clarifai platform and python package exists in environment.
_get_elements
from unstructured.partition.csv import partition_csv return partition_csv(filename=self.file_path, **self.unstructured_kwargs)
def _get_elements(self) ->List: from unstructured.partition.csv import partition_csv return partition_csv(filename=self.file_path, **self.unstructured_kwargs)
null
__init__
"""Vector store interface for testing things in memory.""" self.store: Dict[str, Document] = {} self.permit_upserts = permit_upserts
def __init__(self, permit_upserts: bool=False) ->None: """Vector store interface for testing things in memory.""" self.store: Dict[str, Document] = {} self.permit_upserts = permit_upserts
Vector store interface for testing things in memory.
_Name
self.write(t.id)
def _Name(self, t): self.write(t.id)
null
add_texts
"""Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids associated with the texts. batch_size: Opti...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, ids: Optional[List[str]]=None, batch_size: int=25, **kwargs: Any ) ->List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstor...
Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. ids: Optional list of ids associated with the texts. batch_size: Optional batch size to upsert docs. kwargs:...
_import_elasticsearch
from langchain_community.vectorstores.elasticsearch import ElasticsearchStore return ElasticsearchStore
def _import_elasticsearch() ->Any: from langchain_community.vectorstores.elasticsearch import ElasticsearchStore return ElasticsearchStore
null
_import_gooseai
from langchain_community.llms.gooseai import GooseAI return GooseAI
def _import_gooseai() ->Any: from langchain_community.llms.gooseai import GooseAI return GooseAI
null
__init__
warnings.warn( '`MlflowAIGatewayEmbeddings` is deprecated. Use `MlflowEmbeddings` or `DatabricksEmbeddings` instead.' , DeprecationWarning) try: import mlflow.gateway except ImportError as e: raise ImportError( 'Could not import `mlflow.gateway` module. Please install it with `pip install mlflow...
def __init__(self, **kwargs: Any): warnings.warn( '`MlflowAIGatewayEmbeddings` is deprecated. Use `MlflowEmbeddings` or `DatabricksEmbeddings` instead.' , DeprecationWarning) try: import mlflow.gateway except ImportError as e: raise ImportError( 'Could not import ...
null
drop
with s2.connect(TEST_SINGLESTOREDB_URL) as conn: conn.autocommit(True) with conn.cursor() as cursor: cursor.execute(f'DROP TABLE IF EXISTS {table_name};')
def drop(table_name: str) ->None: with s2.connect(TEST_SINGLESTOREDB_URL) as conn: conn.autocommit(True) with conn.cursor() as cursor: cursor.execute(f'DROP TABLE IF EXISTS {table_name};')
null
parse_output
partial_completion = outputs['partial_completion'] steps = outputs['intermediate_steps'] search_query = extract_between_tags('search_query', partial_completion + '</search_query>') if search_query is None: docs = [] str_output = '' for action, observation in steps: docs.extend(observation) ...
def parse_output(outputs): partial_completion = outputs['partial_completion'] steps = outputs['intermediate_steps'] search_query = extract_between_tags('search_query', partial_completion + '</search_query>') if search_query is None: docs = [] str_output = '' for action, o...
null
transform_input
"""Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in the format specified in the content_type request header. """
@abstractmethod def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) ->bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in the format specified in the content_type request header. """
Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in the format specified in the content_type request header.
test_include_types3
structured_schema = {'node_props': {'Movie': [{'property': 'title', 'type': 'STRING'}], 'Actor': [{'property': 'name', 'type': 'STRING'}], 'Person': [{'property': 'name', 'type': 'STRING'}]}, 'rel_props': {}, 'relationships': [{'start': 'Actor', 'end': 'Movie', 'type': 'ACTED_IN' }, {'start': 'Person', ...
def test_include_types3() ->None: structured_schema = {'node_props': {'Movie': [{'property': 'title', 'type': 'STRING'}], 'Actor': [{'property': 'name', 'type': 'STRING' }], 'Person': [{'property': 'name', 'type': 'STRING'}]}, 'rel_props': {}, 'relationships': [{'start': 'Actor', 'end': ...
null
__init__
"""Creates an empty DeepLakeVectorStore or loads an existing one. The DeepLakeVectorStore is located at the specified ``path``. Examples: >>> # Create a vector store with default tensors >>> deeplake_vectorstore = DeepLake( ... path = <path_for_storing_Data>,...
def __init__(self, dataset_path: str=_LANGCHAIN_DEFAULT_DEEPLAKE_PATH, token: Optional[str]=None, embedding: Optional[Embeddings]=None, embedding_function: Optional[Embeddings]=None, read_only: bool=False, ingestion_batch_size: int=1000, num_workers: int=0, verbose: bool=True, exec_option: Optional[str]...
Creates an empty DeepLakeVectorStore or loads an existing one. The DeepLakeVectorStore is located at the specified ``path``. Examples: >>> # Create a vector store with default tensors >>> deeplake_vectorstore = DeepLake( ... path = <path_for_storing_Data>, ... ) >>> >>> # Create a vecto...
on_chain_end
"""Print out that we finished a chain.""" print(""" > Finished chain.""")
def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) ->None: """Print out that we finished a chain.""" print('\n\x1b[1m> Finished chain.\x1b[0m')
Print out that we finished a chain.
_validate_example_inputs
"""Validate that the example inputs are valid for the model.""" if isinstance(llm_or_chain_factory, BaseLanguageModel): _validate_example_inputs_for_language_model(example, input_mapper) else: chain = llm_or_chain_factory() if isinstance(chain, Chain): _validate_example_inputs_for_chain(example, cha...
def _validate_example_inputs(example: Example, llm_or_chain_factory: MCF, input_mapper: Optional[Callable[[Dict], Any]]) ->None: """Validate that the example inputs are valid for the model.""" if isinstance(llm_or_chain_factory, BaseLanguageModel): _validate_example_inputs_for_language_model(example...
Validate that the example inputs are valid for the model.
test_mosaicml_embedding_query
"""Test MosaicML embeddings of queries.""" document = 'foo bar' embedding = MosaicMLInstructorEmbeddings() output = embedding.embed_query(document) assert len(output) == 768
def test_mosaicml_embedding_query() ->None: """Test MosaicML embeddings of queries.""" document = 'foo bar' embedding = MosaicMLInstructorEmbeddings() output = embedding.embed_query(document) assert len(output) == 768
Test MosaicML embeddings of queries.
_call
return {self.output_key: self.evaluate(**inputs)}
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, ThoughtValidity]: return {self.output_key: self.evaluate(**inputs)}
null
add_file
if target_path in self.files: raise ValueError('target_path already exists') if not Path(source_path).exists(): raise ValueError('source_path does not exist') self.files[target_path] = FileInfo(target_path=target_path, source_path= source_path, description=description)
def add_file(self, source_path: str, target_path: str, description: str ) ->None: if target_path in self.files: raise ValueError('target_path already exists') if not Path(source_path).exists(): raise ValueError('source_path does not exist') self.files[target_path] = FileInfo(target_path=...
null
_llm_type
"""Return type of chat model.""" return 'databricks-chat'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'databricks-chat'
Return type of chat model.
_create_chat_result
if not isinstance(response, dict): response = response.dict() for res in response['choices']: if res.get('finish_reason', None) == 'content_filter': raise ValueError( 'Azure has not provided the response due to a content filter being triggered' ) chat_result = super()._create_cha...
def _create_chat_result(self, response: Union[dict, BaseModel]) ->ChatResult: if not isinstance(response, dict): response = response.dict() for res in response['choices']: if res.get('finish_reason', None) == 'content_filter': raise ValueError( 'Azure has not provided...
null
finalize
"""Wrap the wrapped function using the wrapper and update the docstring. Args: wrapper: The wrapper function. new_doc: The new docstring. Returns: The wrapped function. """ wrapper = functools.wraps(wrapped)(wr...
def finalize(wrapper: Callable[..., Any], new_doc: str) ->T: """Wrap the wrapped function using the wrapper and update the docstring. Args: wrapper: The wrapper function. new_doc: The new docstring. Returns: The wrapped fu...
Wrap the wrapped function using the wrapper and update the docstring. Args: wrapper: The wrapper function. new_doc: The new docstring. Returns: The wrapped function.
_early_stop_msg
"""Try to early-terminate streaming or generation by iterating over stop list""" content = msg.get('content', '') if content and stop: for stop_str in stop: if stop_str and stop_str in content: msg['content'] = content[:content.find(stop_str) + 1] is_stopped = True return msg, is_sto...
def _early_stop_msg(self, msg: dict, is_stopped: bool, stop: Optional[ Sequence[str]]=None) ->Tuple[dict, bool]: """Try to early-terminate streaming or generation by iterating over stop list""" content = msg.get('content', '') if content and stop: for stop_str in stop: if stop_str an...
Try to early-terminate streaming or generation by iterating over stop list
_get_paths_and_methods_from_spec_dictionary
"""Return a tuple (paths, methods) for every path in spec.""" valid_methods = [verb.value for verb in HTTPVerb] for path_name, path_item in spec['paths'].items(): for method in valid_methods: if method in path_item: yield path_name, method
def _get_paths_and_methods_from_spec_dictionary(spec: dict) ->Iterable[Tuple [str, str]]: """Return a tuple (paths, methods) for every path in spec.""" valid_methods = [verb.value for verb in HTTPVerb] for path_name, path_item in spec['paths'].items(): for method in valid_methods: if...
Return a tuple (paths, methods) for every path in spec.
is_lc_serializable
return False
@classmethod def is_lc_serializable(cls) ->bool: return False
null
_extract_token_usage
if response is None: return {'generated_token_count': 0, 'input_token_count': 0} input_token_count = 0 generated_token_count = 0 def get_count_value(key: str, result: Dict[str, Any]) ->int: return result.get(key, 0) or 0 for res in response: results = res.get('results') if results: input_token_c...
@staticmethod def _extract_token_usage(response: Optional[List[Dict[str, Any]]]=None) ->Dict[ str, Any]: if response is None: return {'generated_token_count': 0, 'input_token_count': 0} input_token_count = 0 generated_token_count = 0 def get_count_value(key: str, result: Dict[str, Any]) ->i...
null
__init_subclass__
super().__init_subclass__(**kwargs) if cls.get_relevant_documents != BaseRetriever.get_relevant_documents: warnings.warn( 'Retrievers must implement abstract `_get_relevant_documents` method instead of `get_relevant_documents`' , DeprecationWarning) swap = cls.get_relevant_documents cls.get_...
def __init_subclass__(cls, **kwargs: Any) ->None: super().__init_subclass__(**kwargs) if cls.get_relevant_documents != BaseRetriever.get_relevant_documents: warnings.warn( 'Retrievers must implement abstract `_get_relevant_documents` method instead of `get_relevant_documents`' , ...
null
test_parse_examples_failes_wrong_sequence
with pytest.raises(ValueError) as exc_info: _ = _parse_examples([AIMessage(content='a')]) print(str(exc_info.value)) assert str(exc_info.value ) == 'Expect examples to have an even amount of messages, got 1.'
def test_parse_examples_failes_wrong_sequence() ->None: with pytest.raises(ValueError) as exc_info: _ = _parse_examples([AIMessage(content='a')]) print(str(exc_info.value)) assert str(exc_info.value ) == 'Expect examples to have an even amount of messages, got 1.'
null
convert_messages
history = ChatMessageHistory() for item in input: history.add_user_message(item['result']['question']) history.add_ai_message(item['result']['answer']) return history
def convert_messages(input: List[Dict[str, Any]]) ->ChatMessageHistory: history = ChatMessageHistory() for item in input: history.add_user_message(item['result']['question']) history.add_ai_message(item['result']['answer']) return history
null
__init__
"""Constructs a new RocksetChatMessageHistory. Args: - session_id: The ID of the chat session - client: The RocksetClient object to use to query - collection: The name of the collection to use to store chat messages. If a collection with the given n...
def __init__(self, session_id: str, client: Any, collection: str, workspace: str='commons', messages_key: str='messages', sync: bool=False, message_uuid_method: Callable[[], Union[str, int]]=lambda : str(uuid4()) ) ->None: """Constructs a new RocksetChatMessageHistory. Args: - sessi...
Constructs a new RocksetChatMessageHistory. Args: - session_id: The ID of the chat session - client: The RocksetClient object to use to query - collection: The name of the collection to use to store chat messages. If a collection with the given name does not exist in the...
_stream
request = get_cohere_chat_request(messages, **self._default_params, **kwargs) stream = self.client.chat(**request, stream=True) for data in stream: if data.event_type == 'text-generation': delta = data.text yield ChatGenerationChunk(message=AIMessageChunk(content=delta)) if run_manager: ...
def _stream(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->Iterator[ChatGenerationChunk]: request = get_cohere_chat_request(messages, **self._default_params, ** kwargs) stream = self.client.chat(**reques...
null
from_params
"""Convenience constructor that builds the MaxCompute API wrapper from given parameters. Args: query: SQL query to execute. endpoint: MaxCompute endpoint. project: A project is a basic organizational unit of MaxCompute, which is similar to a datab...
@classmethod def from_params(cls, query: str, endpoint: str, project: str, *, access_id: Optional[str]=None, secret_access_key: Optional[str]=None, **kwargs: Any ) ->MaxComputeLoader: """Convenience constructor that builds the MaxCompute API wrapper from given parameters. Args: ...
Convenience constructor that builds the MaxCompute API wrapper from given parameters. Args: query: SQL query to execute. endpoint: MaxCompute endpoint. project: A project is a basic organizational unit of MaxCompute, which is similar to a database. access_id: MaxCompute access ID. Should be...
test_load_success
"""Test that returns one document""" docs = api_client.load_docs('chatgpt') assert len(docs) == api_client.top_k_results == 3 assert_docs(docs)
def test_load_success(api_client: PubMedAPIWrapper) ->None: """Test that returns one document""" docs = api_client.load_docs('chatgpt') assert len(docs) == api_client.top_k_results == 3 assert_docs(docs)
Test that returns one document
is_lc_serializable
return True
@classmethod def is_lc_serializable(cls) ->bool: return True
null
from_texts
"""Create an Epsilla vectorstore from raw documents. Args: texts (List[str]): List of text data to be inserted. embeddings (Embeddings): Embedding function. client (pyepsilla.vectordb.Client): Epsilla client to connect to. metadatas (Optional[List[dict]]): Metada...
@classmethod def from_texts(cls: Type[Epsilla], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, client: Any=None, db_path: Optional[str]=_LANGCHAIN_DEFAULT_DB_PATH, db_name: Optional[str]= _LANGCHAIN_DEFAULT_DB_NAME, collection_name: Optional[str]= _LANGCHAIN_DEFAULT_TABLE...
Create an Epsilla vectorstore from raw documents. Args: texts (List[str]): List of text data to be inserted. embeddings (Embeddings): Embedding function. client (pyepsilla.vectordb.Client): Epsilla client to connect to. metadatas (Optional[List[dict]]): Metadata for each text. Defaults to N...
mock_psychic
with patch('psychicapi.Psychic') as mock_psychic: yield mock_psychic
@pytest.fixture def mock_psychic(): with patch('psychicapi.Psychic') as mock_psychic: yield mock_psychic
null
from_texts
"""Return VectorStore initialized from texts and embeddings.""" connection = cls.create_connection(db_file) vss = cls(table=table, connection=connection, db_file=db_file, embedding= embedding) vss.add_texts(texts=texts, metadatas=metadatas) return vss
@classmethod def from_texts(cls: Type[SQLiteVSS], texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]]=None, table: str= 'langchain', db_file: str='vss.db', **kwargs: Any) ->SQLiteVSS: """Return VectorStore initialized from texts and embeddings.""" connection = cls.create_connection(...
Return VectorStore initialized from texts and embeddings.