method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_get_elements
from unstructured.__version__ import __version__ as __unstructured_version__ from unstructured.partition.md import partition_md _unstructured_version = __unstructured_version__.split('-')[0] unstructured_version = tuple([int(x) for x in _unstructured_version.split('.')] ) if unstructured_version < (0, 4, 16): r...
def _get_elements(self) ->List: from unstructured.__version__ import __version__ as __unstructured_version__ from unstructured.partition.md import partition_md _unstructured_version = __unstructured_version__.split('-')[0] unstructured_version = tuple([int(x) for x in _unstructured_version. spli...
null
post
headers = {'Authorization': f'Bearer {self.api_key.get_secret_value()}'} response = requests.post(self.api_url, headers=headers, json=request) if not response.ok: raise ValueError(f'HTTP {response.status_code} error: {response.text}') if response.json()['base_resp']['status_code'] > 0: raise ValueError( ...
def post(self, request: Any) ->Any: headers = {'Authorization': f'Bearer {self.api_key.get_secret_value()}'} response = requests.post(self.api_url, headers=headers, json=request) if not response.ok: raise ValueError(f'HTTP {response.status_code} error: {response.text}') if response.json()['base_...
null
update_cache
"""Update the cache and get the LLM output.""" llm_cache = get_llm_cache() for i, result in enumerate(new_results.generations): existing_prompts[missing_prompt_idxs[i]] = result prompt = prompts[missing_prompt_idxs[i]] if llm_cache is not None: llm_cache.update(prompt, llm_string, result) llm_output...
def update_cache(existing_prompts: Dict[int, List], llm_string: str, missing_prompt_idxs: List[int], new_results: LLMResult, prompts: List[str] ) ->Optional[dict]: """Update the cache and get the LLM output.""" llm_cache = get_llm_cache() for i, result in enumerate(new_results.generations): ...
Update the cache and get the LLM output.
_llm_type
"""Return type of llm.""" return 'pai_eas_endpoint'
@property def _llm_type(self) ->str: """Return type of llm.""" return 'pai_eas_endpoint'
Return type of llm.
test_get_combined_score
document = Document(page_content='Test document', metadata={ 'last_accessed_at': datetime(2023, 4, 14, 12, 0)}) vector_salience = 0.7 expected_hours_passed = 2.5 current_time = datetime(2023, 4, 14, 14, 30) combined_score = time_weighted_retriever._get_combined_score(document, vector_salience, current_time) exp...
def test_get_combined_score(time_weighted_retriever: TimeWeightedVectorStoreRetriever) ->None: document = Document(page_content='Test document', metadata={ 'last_accessed_at': datetime(2023, 4, 14, 12, 0)}) vector_salience = 0.7 expected_hours_passed = 2.5 current_time = datetime(2023, 4, 14...
null
stream
key = input['key'] actual_input = input['input'] if key not in self.runnables: raise ValueError(f"No runnable associated with key '{key}'") runnable = self.runnables[key] yield from runnable.stream(actual_input, config)
def stream(self, input: RouterInput, config: Optional[RunnableConfig]=None, **kwargs: Optional[Any]) ->Iterator[Output]: key = input['key'] actual_input = input['input'] if key not in self.runnables: raise ValueError(f"No runnable associated with key '{key}'") runnable = self.runnables[key] ...
null
_stop
return ['Observation:']
@property def _stop(self) ->List[str]: return ['Observation:']
null
_import_outline
from langchain_community.utilities.outline import OutlineAPIWrapper return OutlineAPIWrapper
def _import_outline() ->Any: from langchain_community.utilities.outline import OutlineAPIWrapper return OutlineAPIWrapper
null
test_tongyi_call
"""Test valid call to tongyi.""" llm = Tongyi() output = llm('who are you') assert isinstance(output, str)
def test_tongyi_call() ->None: """Test valid call to tongyi.""" llm = Tongyi() output = llm('who are you') assert isinstance(output, str)
Test valid call to tongyi.
test_typeerror
assert dumps({(1, 2): 3} ) == '{"lc": 1, "type": "not_implemented", "id": ["builtins", "dict"], "repr": "{(1, 2): 3}"}'
def test_typeerror() ->None: assert dumps({(1, 2): 3} ) == '{"lc": 1, "type": "not_implemented", "id": ["builtins", "dict"], "repr": "{(1, 2): 3}"}'
null
on_tool_error
pass
def on_tool_error(self, error: BaseException, **kwargs: Any) ->None: pass
null
_file_types
"""Return supported file types."""
@property @abstractmethod def _file_types(self) ->Sequence[_FileType]: """Return supported file types."""
Return supported file types.
load
with open(self.persist_path, 'r') as fp: return json.load(fp)
def load(self) ->Any: with open(self.persist_path, 'r') as fp: return json.load(fp)
null
__init__
"""Create a new HugeGraph wrapper instance.""" try: from hugegraph.connection import PyHugeGraph except ImportError: raise ValueError( 'Please install HugeGraph Python client first: `pip3 install hugegraph-python`' ) self.username = username self.password = password self.address = address self.p...
def __init__(self, username: str='default', password: str='default', address: str='127.0.0.1', port: int=8081, graph: str='hugegraph') ->None: """Create a new HugeGraph wrapper instance.""" try: from hugegraph.connection import PyHugeGraph except ImportError: raise ValueError( ...
Create a new HugeGraph wrapper instance.
_import_mlflow_ai_gateway
from langchain_community.llms.mlflow_ai_gateway import MlflowAIGateway return MlflowAIGateway
def _import_mlflow_ai_gateway() ->Any: from langchain_community.llms.mlflow_ai_gateway import MlflowAIGateway return MlflowAIGateway
null
_load_retrieval_qa_with_sources_chain
if 'retriever' in kwargs: retriever = kwargs.pop('retriever') else: raise ValueError('`retriever` must be present.') if 'combine_documents_chain' in config: combine_documents_chain_config = config.pop('combine_documents_chain') combine_documents_chain = load_chain_from_config( combine_documents_...
def _load_retrieval_qa_with_sources_chain(config: dict, **kwargs: Any ) ->RetrievalQAWithSourcesChain: if 'retriever' in kwargs: retriever = kwargs.pop('retriever') else: raise ValueError('`retriever` must be present.') if 'combine_documents_chain' in config: combine_documents_ch...
null
max_marginal_relevance_search
"""Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: search query text. k: Number of Documents to return. Defaults to 4. fetch_k: Numbe...
def max_marginal_relevance_search(self, query: str, k: int=DEFAULT_TOP_K, fetch_k: int=DEFAULT_TOP_K * 5, lambda_mult: float=0.5, filter: Optional[Dict[str, Any]]=None, brute_force: bool=False, fraction_lists_to_search: Optional[float]=None, **kwargs: Any) ->List[ Document]: """Return docs selected ...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: search query text. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass to MMR algorithm. ...
embeddings
return None
@property def embeddings(self) ->Optional[Embeddings]: return None
null
test_pdfminer_pdf_as_html_loader
"""Test PDFMinerPDFasHTMLLoader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PDFMinerPDFasHTMLLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__).parent.parent / 'examples/layout-parser-paper.pdf' loader = PDFMinerPDFasHTMLLoader(str(file_path)) d...
def test_pdfminer_pdf_as_html_loader() ->None: """Test PDFMinerPDFasHTMLLoader.""" file_path = Path(__file__).parent.parent / 'examples/hello.pdf' loader = PDFMinerPDFasHTMLLoader(str(file_path)) docs = loader.load() assert len(docs) == 1 file_path = Path(__file__ ).parent.parent / 'exam...
Test PDFMinerPDFasHTMLLoader.
OutputType
return self.input_type or Any
@property def OutputType(self) ->Any: return self.input_type or Any
null
on_retriever_start_common
self.starts += 1 self.retriever_starts += 1
def on_retriever_start_common(self) ->None: self.starts += 1 self.retriever_starts += 1
null
load
"""Load web pages.""" return list(self.lazy_load())
def load(self) ->List[Document]: """Load web pages.""" return list(self.lazy_load())
Load web pages.
InputType
return self.input_type or Any
@property def InputType(self) ->Any: return self.input_type or Any
null
test_output_dict
runnable = RunnableLambda(lambda input: {'output': [AIMessage(content= 'you said: ' + '\n'.join([str(m.content) for m in input['history'] if isinstance(m, HumanMessage)] + [input['input']]))]}) get_session_history = _get_get_session_history() with_history = RunnableWithMessageHistory(runnable, get_session_histo...
def test_output_dict() ->None: runnable = RunnableLambda(lambda input: {'output': [AIMessage(content= 'you said: ' + '\n'.join([str(m.content) for m in input['history'] if isinstance(m, HumanMessage)] + [input['input']]))]}) get_session_history = _get_get_session_history() with_history = Run...
null
_validate_commands
"""Validate commands.""" commands = values.get('commands') if not isinstance(commands, list): values['commands'] = [commands] warnings.warn( 'The shell tool has no safeguards by default. Use at your own risk.') return values
@root_validator def _validate_commands(cls, values: dict) ->dict: """Validate commands.""" commands = values.get('commands') if not isinstance(commands, list): values['commands'] = [commands] warnings.warn( 'The shell tool has no safeguards by default. Use at your own risk.') return ...
Validate commands.
_construct_json_body
return {'prompt': prompt, **params}
def _construct_json_body(self, prompt: str, params: dict) ->dict: return {'prompt': prompt, **params}
null
prepare_inputs_for_autoembed
""" go over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed, then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status """ next_inputs = inputs.copy() for k, v in next_inputs.items(): if isinstan...
def prepare_inputs_for_autoembed(inputs: Dict[str, Any]) ->Dict[str, Any]: """ go over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed, then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status "...
go over all the inputs and if something is either wrapped in _ToSelectFrom or _BasedOn, and if their inner values are not already _Embed, then wrap them in EmbedAndKeep while retaining their _ToSelectFrom or _BasedOn status
load_evaluators
"""Load evaluators specified by a list of evaluator types. Parameters ---------- evaluators : Sequence[EvaluatorType] The list of evaluator types to load. llm : BaseLanguageModel, optional The language model to use for evaluation, if none is provided, a default ChatOpenAI gpt-4 ...
def load_evaluators(evaluators: Sequence[EvaluatorType], *, llm: Optional[ BaseLanguageModel]=None, config: Optional[dict]=None, **kwargs: Any ) ->List[Union[Chain, StringEvaluator]]: """Load evaluators specified by a list of evaluator types. Parameters ---------- evaluators : Sequence[Evaluato...
Load evaluators specified by a list of evaluator types. Parameters ---------- evaluators : Sequence[EvaluatorType] The list of evaluator types to load. llm : BaseLanguageModel, optional The language model to use for evaluation, if none is provided, a default ChatOpenAI gpt-4 model will be used. config : di...
_call
"""Call out to StochasticAI'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 ...
def _call(self, prompt: str, stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str: """Call out to StochasticAI's complete endpoint. Args: prompt: The prompt to pass into the model. stop: Optional list of stop words to use whe...
Call out to StochasticAI'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 = StochasticAI("Tell me a joke.")
ideation_prompt
return ChatPromptTemplate.from_strings(self.get_prompt_strings('ideation'))
def ideation_prompt(self) ->ChatPromptTemplate: return ChatPromptTemplate.from_strings(self.get_prompt_strings('ideation'))
null
text_to_docs
"""Convert a string or list of strings to a list of Documents with metadata.""" from langchain.text_splitter import RecursiveCharacterTextSplitter if isinstance(text, str): text = [text] page_docs = [Document(page_content=page) for page in text] for i, doc in enumerate(page_docs): doc.metadata['page'] = i + 1 d...
def text_to_docs(text: Union[str, List[str]]) ->List[Document]: """Convert a string or list of strings to a list of Documents with metadata.""" from langchain.text_splitter import RecursiveCharacterTextSplitter if isinstance(text, str): text = [text] page_docs = [Document(page_content=page) for ...
Convert a string or list of strings to a list of Documents with metadata.
test_serialize_llmchain_env
llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello') prompt = PromptTemplate.from_template('hello {name}!') chain = LLMChain(llm=llm, prompt=prompt) import os has_env = 'OPENAI_API_KEY' in os.environ if not has_env: os.environ['OPENAI_API_KEY'] = 'env_variable' llm_2 = OpenAI(model='davinci', temp...
@pytest.mark.requires('openai') def test_serialize_llmchain_env() ->None: llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello') prompt = PromptTemplate.from_template('hello {name}!') chain = LLMChain(llm=llm, prompt=prompt) import os has_env = 'OPENAI_API_KEY' in os.environ if n...
null
_client_params
"""Get the parameters used for the openai client.""" set_model_value = self.model if self.model_name is not None: set_model_value = self.model_name self.client.api_base = self.api_base self.client.organization = self.organization creds: Dict[str, Any] = {'model': set_model_value, 'force_timeout': self. request_...
@property def _client_params(self) ->Dict[str, Any]: """Get the parameters used for the openai client.""" set_model_value = self.model if self.model_name is not None: set_model_value = self.model_name self.client.api_base = self.api_base self.client.organization = self.organization creds...
Get the parameters used for the openai client.
http_paths_and_methods
"""Return a args for every method in cached OpenAPI spec in test_specs.""" http_paths_and_methods = [] for test_spec in _get_test_specs(): spec_name = test_spec.parent.name if test_spec.suffix == '.json': with test_spec.open('r') as f: spec = json.load(f) else: with test_spec.ope...
def http_paths_and_methods() ->List[Tuple[str, OpenAPISpec, str, str]]: """Return a args for every method in cached OpenAPI spec in test_specs.""" http_paths_and_methods = [] for test_spec in _get_test_specs(): spec_name = test_spec.parent.name if test_spec.suffix == '.json': wit...
Return a args for every method in cached OpenAPI spec in test_specs.
connect_to_elasticsearch
try: import elasticsearch except ImportError: raise ImportError( 'Could not import elasticsearch python package. Please install it with `pip install elasticsearch`.' ) if es_url and cloud_id: raise ValueError( 'Both es_url and cloud_id are defined. Please provide only one.') connecti...
@staticmethod def connect_to_elasticsearch(*, es_url: Optional[str]=None, cloud_id: Optional[str]=None, api_key: Optional[str]=None, username: Optional[str ]=None, password: Optional[str]=None) ->'Elasticsearch': try: import elasticsearch except ImportError: raise ImportError( ...
null
load_memory_variables
"""Return baz variable.""" return {'baz': 'foo'}
def load_memory_variables(self, inputs: Optional[Dict[str, Any]]=None) ->Dict[ str, str]: """Return baz variable.""" return {'baz': 'foo'}
Return baz variable.
test_konko_streaming_callback_test
"""Evaluate streaming's token callback functionality.""" callback_instance = FakeCallbackHandler() callback_mgr = CallbackManager([callback_instance]) chat_instance = ChatKonko(max_tokens=10, streaming=True, temperature=0, callback_manager=callback_mgr, verbose=True) msg = HumanMessage(content='Hi') chat_response =...
def test_konko_streaming_callback_test() ->None: """Evaluate streaming's token callback functionality.""" callback_instance = FakeCallbackHandler() callback_mgr = CallbackManager([callback_instance]) chat_instance = ChatKonko(max_tokens=10, streaming=True, temperature=0, callback_manager=callbac...
Evaluate streaming's token callback functionality.
from_llm
"""Initialize from llm using default template. Args: vectorstore: Vector store for storing web pages llm: llm for search question generation search: GoogleSearchAPIWrapper prompt: prompt to generating search questions num_search_results: Number of pag...
@classmethod def from_llm(cls, vectorstore: VectorStore, llm: BaseLLM, search: GoogleSearchAPIWrapper, prompt: Optional[BasePromptTemplate]=None, num_search_results: int=1, text_splitter: RecursiveCharacterTextSplitter=RecursiveCharacterTextSplitter( chunk_size=1500, chunk_overlap=150)) ->'WebResearchRe...
Initialize from llm using default template. Args: vectorstore: Vector store for storing web pages llm: llm for search question generation search: GoogleSearchAPIWrapper prompt: prompt to generating search questions num_search_results: Number of pages per Google search text_splitter: Text splitt...
test_chroma_add_documents_mixed_metadata
db = Chroma(embedding_function=FakeEmbeddings()) docs = [Document(page_content='foo'), Document(page_content='bar', metadata ={'baz': 1})] ids = ['0', '1'] actual_ids = db.add_documents(docs, ids=ids) assert actual_ids == ids search = db.similarity_search('foo bar') assert sorted(search, key=lambda d: d.page_conten...
def test_chroma_add_documents_mixed_metadata() ->None: db = Chroma(embedding_function=FakeEmbeddings()) docs = [Document(page_content='foo'), Document(page_content='bar', metadata={'baz': 1})] ids = ['0', '1'] actual_ids = db.add_documents(docs, ids=ids) assert actual_ids == ids search =...
null
delete_file
""" Deletes a file from the repo Parameters: file_path(str): Where the file is Returns: str: Success or failure message """ try: self.gitlab_repo_instance.files.delete(file_path, self.gitlab_branch, 'Delete ' + file_path) return 'Deleted file ' + ...
def delete_file(self, file_path: str) ->str: """ Deletes a file from the repo Parameters: file_path(str): Where the file is Returns: str: Success or failure message """ try: self.gitlab_repo_instance.files.delete(file_path, self. gitlab...
Deletes a file from the repo Parameters: file_path(str): Where the file is Returns: str: Success or failure message
model
"""For backwards compatibility.""" return self.llm
@property def model(self) ->BaseChatModel: """For backwards compatibility.""" return self.llm
For backwards compatibility.
is_anomalous
""" Detect if given text is anomalous from the dataset Args: query: Text to detect if it is anomaly Returns: True or False """ vcol = self._vector_index vtype = self._vector_type embeddings = self._embedding.embed_query(query) str_embeddings = [str(f) for f in emb...
def is_anomalous(self, query: str, **kwargs: Any) ->bool: """ Detect if given text is anomalous from the dataset Args: query: Text to detect if it is anomaly Returns: True or False """ vcol = self._vector_index vtype = self._vector_type embeddings ...
Detect if given text is anomalous from the dataset Args: query: Text to detect if it is anomaly Returns: True or False
setup_class
if not os.getenv('OPENAI_API_KEY'): raise ValueError('OPENAI_API_KEY environment variable is not set')
@classmethod def setup_class(cls) ->None: if not os.getenv('OPENAI_API_KEY'): raise ValueError('OPENAI_API_KEY environment variable is not set')
null
results
res = self._response_json(url) return self._filter_results(res)
def results(self, url: str) ->list: res = self._response_json(url) return self._filter_results(res)
null
is_lc_serializable
return False
@classmethod def is_lc_serializable(cls) ->bool: return False
null
refresh_schema
"""Refreshes the Kùzu graph schema information""" node_properties = [] node_table_names = self.conn._get_node_table_names() for table_name in node_table_names: current_table_schema = {'properties': [], 'label': table_name} properties = self.conn._get_node_property_names(table_name) for property_name in prop...
def refresh_schema(self) ->None: """Refreshes the Kùzu graph schema information""" node_properties = [] node_table_names = self.conn._get_node_table_names() for table_name in node_table_names: current_table_schema = {'properties': [], 'label': table_name} properties = self.conn._get_node...
Refreshes the Kùzu graph schema information
test_copy_file
"""Test the FileCopy tool.""" with TemporaryDirectory() as temp_dir: tool = CopyFileTool() source_file = Path(temp_dir) / 'source.txt' destination_file = Path(temp_dir) / 'destination.txt' source_file.write_text('Hello, world!') tool.run({'source_path': str(source_file), 'destination_path': str( ...
def test_copy_file() ->None: """Test the FileCopy tool.""" with TemporaryDirectory() as temp_dir: tool = CopyFileTool() source_file = Path(temp_dir) / 'source.txt' destination_file = Path(temp_dir) / 'destination.txt' source_file.write_text('Hello, world!') tool.run({'sou...
Test the FileCopy tool.
replace_imports
"""Replace imports in each Python code block with links to their documentation and append the import info in a comment""" all_imports = [] with open(file, 'r') as f: data = f.read() file_name = os.path.basename(file) _DOC_TITLE = _get_doc_title(data, file_name) def replacer(match): code = match.group(2) ...
def replace_imports(file): """Replace imports in each Python code block with links to their documentation and append the import info in a comment""" all_imports = [] with open(file, 'r') as f: data = f.read() file_name = os.path.basename(file) _DOC_TITLE = _get_doc_title(data, file_name)...
Replace imports in each Python code block with links to their documentation and append the import info in a comment
__init__
self.url = url self.key = key self.username = username self.timeout = timeout
def __init__(self, url: str, key: str, username: str='root', timeout: int=10): self.url = url self.key = key self.username = username self.timeout = timeout
null
_create_chat_result
generations = [] for res in response.choices: message = _convert_dict_to_message(res.message) finish_reason = res.finish_reason gen = ChatGeneration(message=message, generation_info={'finish_reason': finish_reason}) generations.append(gen) if finish_reason != 'stop': logger.warning('...
def _create_chat_result(self, response: Any) ->ChatResult: generations = [] for res in response.choices: message = _convert_dict_to_message(res.message) finish_reason = res.finish_reason gen = ChatGeneration(message=message, generation_info={ 'finish_reason': finish_reason}) ...
null
test_debug_is_settable_via_setter
from langchain_core import globals from langchain_core.callbacks.manager import _get_debug previous_value = globals._debug previous_fn_reading = _get_debug() assert previous_value == previous_fn_reading set_debug(not previous_value) new_value = globals._debug new_fn_reading = _get_debug() try: assert new_value != p...
def test_debug_is_settable_via_setter() ->None: from langchain_core import globals from langchain_core.callbacks.manager import _get_debug previous_value = globals._debug previous_fn_reading = _get_debug() assert previous_value == previous_fn_reading set_debug(not previous_value) new_value =...
null
_construct_initial_inputs
base_info = {'page_content': docs[0].page_content} base_info.update(docs[0].metadata) document_info = {k: base_info[k] for k in self.document_prompt.input_variables} base_inputs: dict = {self.document_variable_name: self.document_prompt. format(**document_info)} inputs = {**base_inputs, **kwargs} return inputs
def _construct_initial_inputs(self, docs: List[Document], **kwargs: Any ) ->Dict[str, Any]: base_info = {'page_content': docs[0].page_content} base_info.update(docs[0].metadata) document_info = {k: base_info[k] for k in self.document_prompt. input_variables} base_inputs: dict = {self.documen...
null
max_marginal_relevance_search
"""Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. ...
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, filter: Optional[dict]=None, **kwargs: Any ) ->List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diver...
Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass ...
test_agent_tool_return_direct_in_intermediate_steps
"""Test agent using tools that return directly.""" tool = 'Search' responses = [f"""FooBarBaz Action: {tool} Action Input: misalignment""", """Oh well Final Answer: curses foiled again"""] fake_llm = FakeListLLM(responses=responses) tools = [Tool(name='Search', func=lambda x: x, description= 'Useful for searchi...
def test_agent_tool_return_direct_in_intermediate_steps() ->None: """Test agent using tools that return directly.""" tool = 'Search' responses = [f'FooBarBaz\nAction: {tool}\nAction Input: misalignment', """Oh well Final Answer: curses foiled again"""] fake_llm = FakeListLLM(responses=responses)...
Test agent using tools that return directly.
_embed_with_retry
response = embeddings.client.create(**kwargs) return _check_response(response)
@retry_decorator def _embed_with_retry(**kwargs: Any) ->Any: response = embeddings.client.create(**kwargs) return _check_response(response)
null
__init__
"""Initialize with a list of image data (bytes) or file paths Args: images: Either a single image or a list of images. Accepts image data (bytes) or file paths to images. blip_processor: The name of the pre-trained BLIP processor. blip_model: The name of ...
def __init__(self, images: Union[str, bytes, List[Union[str, bytes]]], blip_processor: str='Salesforce/blip-image-captioning-base', blip_model: str='Salesforce/blip-image-captioning-base'): """Initialize with a list of image data (bytes) or file paths Args: images: Either a single image...
Initialize with a list of image data (bytes) or file paths Args: images: Either a single image or a list of images. Accepts image data (bytes) or file paths to images. blip_processor: The name of the pre-trained BLIP processor. blip_model: The name of the pre-trained BLIP model.
input_mapper
return d['some_input']
def input_mapper(d: dict) ->str: return d['some_input']
null
load
"""Load Documents from bilibili url.""" results = [] for url in self.video_urls: transcript, video_info = self._get_bilibili_subs_and_info(url) doc = Document(page_content=transcript, metadata=video_info) results.append(doc) return results
def load(self) ->List[Document]: """Load Documents from bilibili url.""" results = [] for url in self.video_urls: transcript, video_info = self._get_bilibili_subs_and_info(url) doc = Document(page_content=transcript, metadata=video_info) results.append(doc) return results
Load Documents from bilibili url.
_on_llm_end
crumbs = self.get_breadcrumbs(run) self.function_callback(f"{get_colored_text('[llm/end]', color='blue')} " + get_bolded_text( f"""[{crumbs}] [{elapsed(run)}] Exiting LLM run with output: """) + f"{try_json_stringify(run.outputs, '[response]')}")
def _on_llm_end(self, run: Run) ->None: crumbs = self.get_breadcrumbs(run) self.function_callback( f"{get_colored_text('[llm/end]', color='blue')} " + get_bolded_text (f"""[{crumbs}] [{elapsed(run)}] Exiting LLM run with output: """) + f"{try_json_stringify(run.outputs, '[response]')}")
null
similarity_search_with_score
"""Return documents from Marqo that are similar to the query as well as their scores. Args: query (str): The query to search with, either as a string or a weighted query. k (int, optional): The number of documents to return. Defaults to 4. Returns: ...
def similarity_search_with_score(self, query: Union[str, Dict[str, float]], k: int=4) ->List[Tuple[Document, float]]: """Return documents from Marqo that are similar to the query as well as their scores. Args: query (str): The query to search with, either as a string or a weighted ...
Return documents from Marqo that are similar to the query as well as their scores. Args: query (str): The query to search with, either as a string or a weighted query. k (int, optional): The number of documents to return. Defaults to 4. Returns: List[Tuple[Document, float]]: The matching documents and...
test_structured_tool_from_function
"""Test that structured tools can be created from functions.""" def foo(bar: int, baz: str) ->str: """Docstring Args: bar: int baz: str """ raise NotImplementedError() structured_tool = StructuredTool.from_function(foo) assert structured_tool.name == 'foo' assert structur...
def test_structured_tool_from_function() ->None: """Test that structured tools can be created from functions.""" def foo(bar: int, baz: str) ->str: """Docstring Args: bar: int baz: str """ raise NotImplementedError() structured_tool = StructuredTool.f...
Test that structured tools can be created from functions.
_chain_type
"""Return the chain type.""" return 'vector_db_qa'
@property def _chain_type(self) ->str: """Return the chain type.""" return 'vector_db_qa'
Return the chain type.
test_long_context_reorder
"""Test Lost in the middle reordering get_relevant_docs.""" texts = ['Basquetball is a great sport.', 'Fly me to the moon is one of my favourite songs.', 'The Celtics are my favourite team.', 'This is a document about the Boston Celtics', 'I simply love going to the movies', 'The Boston Celtics won ...
def test_long_context_reorder() ->None: """Test Lost in the middle reordering get_relevant_docs.""" texts = ['Basquetball is a great sport.', 'Fly me to the moon is one of my favourite songs.', 'The Celtics are my favourite team.', 'This is a document about the Boston Celtics', '...
Test Lost in the middle reordering get_relevant_docs.
_identifying_params
return {}
@property def _identifying_params(self) ->Dict[str, Any]: return {}
null
_deploy
"""Call to Beam.""" try: import beam if beam.__path__ == '': raise ImportError except ImportError: raise ImportError( 'Could not import beam python package. Please install it with `curl https://raw.githubusercontent.com/slai-labs/get-beam/main/get-beam.sh -sSfL | sh`.' ) self.app_cre...
def _deploy(self) ->str: """Call to Beam.""" try: import beam if beam.__path__ == '': raise ImportError except ImportError: raise ImportError( 'Could not import beam python package. Please install it with `curl https://raw.githubusercontent.com/slai-labs/get-b...
Call to Beam.
get_runtime_environment
"""Get information about the LangChain runtime environment.""" from langchain import __version__ return {'library_version': __version__, 'library': 'langchain', 'platform': platform.platform(), 'runtime': 'python', 'runtime_version': platform. python_version()}
@lru_cache(maxsize=1) def get_runtime_environment() ->dict: """Get information about the LangChain runtime environment.""" from langchain import __version__ return {'library_version': __version__, 'library': 'langchain', 'platform': platform.platform(), 'runtime': 'python', 'runtime_version'...
Get information about the LangChain runtime environment.
_get_tables_todo
"""Get the tables that still need to be queried.""" return [table for table in tables_todo if table not in self.schemas]
def _get_tables_todo(self, tables_todo: List[str]) ->List[str]: """Get the tables that still need to be queried.""" return [table for table in tables_todo if table not in self.schemas]
Get the tables that still need to be queried.
get_cleaned_operation_id
"""Get a cleaned operation id from an operation id.""" operation_id = operation.operationId if operation_id is None: path = re.sub('[^a-zA-Z0-9]', '_', path.lstrip('/')) operation_id = f'{path}_{method}' return operation_id.replace('-', '_').replace('.', '_').replace('/', '_')
@staticmethod def get_cleaned_operation_id(operation: Operation, path: str, method: str ) ->str: """Get a cleaned operation id from an operation id.""" operation_id = operation.operationId if operation_id is None: path = re.sub('[^a-zA-Z0-9]', '_', path.lstrip('/')) operation_id = f'{pat...
Get a cleaned operation id from an operation id.
test_bigquery_loader_page_content_columns
loader = BigQueryLoader('SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS a, 4 AS b' , page_content_columns=['a']) docs = loader.load() assert len(docs) == 2 assert docs[0].page_content == 'a: 1' assert docs[0].metadata == {} assert docs[1].page_content == 'a: 3' assert docs[1].metadata == {}
@pytest.mark.skipif(not bigquery_installed, reason='bigquery not installed') def test_bigquery_loader_page_content_columns() ->None: loader = BigQueryLoader( 'SELECT 1 AS a, 2 AS b UNION ALL SELECT 3 AS a, 4 AS b', page_content_columns=['a']) docs = loader.load() assert len(docs) == 2 as...
null
evaluation_name
return f'embedding_{self.distance_metric.value}_distance'
@property def evaluation_name(self) ->str: return f'embedding_{self.distance_metric.value}_distance'
null
test_singlestoredb
"""Test end to end construction and search.""" table_name = 'test_singlestoredb' drop(table_name) docsearch = SingleStoreDB.from_texts(texts, NormilizedFakeEmbeddings(), table_name=table_name, host=TEST_SINGLESTOREDB_URL) output = docsearch.similarity_search('foo', k=1) assert output == TEST_SINGLE_RESULT drop(tabl...
@pytest.mark.skipif(not singlestoredb_installed, reason= 'singlestoredb not installed') def test_singlestoredb(texts: List[str]) ->None: """Test end to end construction and search.""" table_name = 'test_singlestoredb' drop(table_name) docsearch = SingleStoreDB.from_texts(texts, NormilizedFakeEmbeddi...
Test end to end construction and search.
embed_query
"""Compute query embeddings using a TensorflowHub embedding model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace('\n', ' ') embedding = self.embed([text]).numpy()[0] return embedding.tolist()
def embed_query(self, text: str) ->List[float]: """Compute query embeddings using a TensorflowHub embedding model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace('\n', ' ') embedding = self.embed([text]).numpy()[0] ...
Compute query embeddings using a TensorflowHub embedding model. Args: text: The text to embed. Returns: Embeddings for the text.
kv_singleio_dataset_name
import pandas as pd client = Client() df = pd.DataFrame({'the wackiest input': [ "What's the capital of California?", "What's the capital of Nevada?", "What's the capital of Oregon?", "What's the capital of Washington?"], 'unthinkable output': ['Sacramento', 'Carson City', 'Salem', 'Olympia']}) uid = str(uu...
@pytest.fixture(scope='module') def kv_singleio_dataset_name() ->Iterator[str]: import pandas as pd client = Client() df = pd.DataFrame({'the wackiest input': [ "What's the capital of California?", "What's the capital of Nevada?", "What's the capital of Oregon?", "What's the capital ...
null
_transform
for chunk in input: if isinstance(chunk, BaseMessage): yield self.parse_result([ChatGeneration(message=chunk)]) else: yield self.parse_result([Generation(text=chunk)])
def _transform(self, input: Iterator[Union[str, BaseMessage]]) ->Iterator[T]: for chunk in input: if isinstance(chunk, BaseMessage): yield self.parse_result([ChatGeneration(message=chunk)]) else: yield self.parse_result([Generation(text=chunk)])
null
_init_resp
return {k: None for k in self.callback_columns}
def _init_resp(self) ->Dict: return {k: None for k in self.callback_columns}
null
test_pickbest_textembedder_missing_context_throws
feature_embedder = pick_best_chain.PickBestFeatureEmbedder(auto_embed=False, model=MockEncoder()) named_action = {'action': ['0', '1', '2']} event = pick_best_chain.PickBestEvent(inputs={}, to_select_from= named_action, based_on={}) with pytest.raises(ValueError): feature_embedder.format(event)
@pytest.mark.requires('vowpal_wabbit_next') def test_pickbest_textembedder_missing_context_throws() ->None: feature_embedder = pick_best_chain.PickBestFeatureEmbedder(auto_embed= False, model=MockEncoder()) named_action = {'action': ['0', '1', '2']} event = pick_best_chain.PickBestEvent(inputs={}, t...
null
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
similarity_search_with_score
"""Run similarity search with Chroma with distance. Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. filter (Optional[dict]): Filter by metadata. Defaults to None. Returns: List[Tuple[Document, float]]: Li...
def similarity_search_with_score(self, query: str, k: int=4, filter: Optional[dict]=None, **kwargs: Any) ->List[Tuple[Document, float]]: """Run similarity search with Chroma with distance. Args: query (str): Query text to search for. k (int): Number of results to return. Default...
Run similarity search with Chroma with distance. Args: query (str): Query text to search for. k (int): Number of results to return. Defaults to 4. filter (Optional[dict]): Filter by metadata. Defaults to None. Returns: List[Tuple[Document, float]]: List of documents most similar to the query t...
similarity_search_with_score
embedding_vector = self.embedding.embed_query(query) return self.similarity_search_with_score_by_vector(embedding_vector, k, filter=filter)
def similarity_search_with_score(self, query: str, k: int=4, filter: Optional[Dict[str, str]]=None) ->List[Tuple[Document, float]]: embedding_vector = self.embedding.embed_query(query) return self.similarity_search_with_score_by_vector(embedding_vector, k, filter=filter)
null
astream
async def input_aiter() ->AsyncIterator[Input]: yield input return self.atransform(input_aiter(), config, **kwargs)
def astream(self, input: Input, config: Optional[RunnableConfig]=None, ** kwargs: Any) ->AsyncIterator[Output]: async def input_aiter() ->AsyncIterator[Input]: yield input return self.atransform(input_aiter(), config, **kwargs)
null
add_texts
raise NotImplementedError
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, **kwargs: Any) ->List[str]: raise NotImplementedError
null
_completion_with_retry
return llm.client.create(**kwargs)
@retry_decorator def _completion_with_retry(**kwargs: Any) ->Any: return llm.client.create(**kwargs)
null
get_table_info
"""Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of sample rows will be appended to each table description. This can increase performance as ...
def get_table_info(self, table_names: Optional[List[str]]=None) ->str: """Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of sample rows will be ...
Get information about specified tables. Follows best practices as specified in: Rajkumar et al, 2022 (https://arxiv.org/abs/2204.00498) If `sample_rows_in_table_info`, the specified number of sample rows will be appended to each table description. This can increase performance as demonstrated in the paper.
load
with open(self.persist_path, 'rb') as fp: return self.bson.loads(fp.read())
def load(self) ->Any: with open(self.persist_path, 'rb') as fp: return self.bson.loads(fp.read())
null
test_document_not_found
"""Test when document is not found.""" _dict = {'foo': Document(page_content='bar')} docstore = InMemoryDocstore(_dict) output = docstore.search('bar') assert output == 'ID bar not found.'
def test_document_not_found() ->None: """Test when document is not found.""" _dict = {'foo': Document(page_content='bar')} docstore = InMemoryDocstore(_dict) output = docstore.search('bar') assert output == 'ID bar not found.'
Test when document is not found.
validate_init_args
"""Validates proper combinations of init arguments""" errors = [] if url is None: errors.append('Must provide `base_url`') if api_key and not username or username and not api_key: errors.append( 'If one of `api_key` or `username` is provided, the other must be as well.' ) non_null_creds = list(x...
@staticmethod def validate_init_args(url: Optional[str]=None, api_key: Optional[str]=None, username: Optional[str]=None, session: Optional[requests.Session]=None, oauth2: Optional[dict]=None, token: Optional[str]=None) ->Union[List, None ]: """Validates proper combinations of init arguments""" error...
Validates proper combinations of init arguments
_stream_response_to_chat_generation_chunk
"""Convert a stream response to a generation chunk.""" parsed_response = json.loads(stream_response) generation_info = parsed_response if parsed_response.get('done' ) is True else None return ChatGenerationChunk(message=AIMessageChunk(content=parsed_response. get('response', '')), generation_info=generation_inf...
@deprecated('0.0.3', alternative= '_chat_stream_response_to_chat_generation_chunk') def _stream_response_to_chat_generation_chunk(stream_response: str ) ->ChatGenerationChunk: """Convert a stream response to a generation chunk.""" parsed_response = json.loads(stream_response) generation_info = parse...
Convert a stream response to a generation chunk.
__init__
"""Initialize with a path. Args: path: Path to the directory containing the Obsidian files. encoding: Charset encoding, defaults to "UTF-8" collect_metadata: Whether to collect metadata from the front matter. Defaults to True. """ self.file_path = pat...
def __init__(self, path: str, encoding: str='UTF-8', collect_metadata: bool =True): """Initialize with a path. Args: path: Path to the directory containing the Obsidian files. encoding: Charset encoding, defaults to "UTF-8" collect_metadata: Whether to collect metada...
Initialize with a path. Args: path: Path to the directory containing the Obsidian files. encoding: Charset encoding, defaults to "UTF-8" collect_metadata: Whether to collect metadata from the front matter. Defaults to True.
test_openai_embedding_documents_multiple
"""Test openai embeddings.""" documents = ['foo bar', 'bar foo', 'foo'] embedding = OpenAIEmbeddings(chunk_size=2) embedding.embedding_ctx_length = 8191 output = embedding.embed_documents(documents) assert len(output) == 3 assert len(output[0]) == 1536 assert len(output[1]) == 1536 assert len(output[2]) == 1536
@pytest.mark.scheduled def test_openai_embedding_documents_multiple() ->None: """Test openai embeddings.""" documents = ['foo bar', 'bar foo', 'foo'] embedding = OpenAIEmbeddings(chunk_size=2) embedding.embedding_ctx_length = 8191 output = embedding.embed_documents(documents) assert len(output) ...
Test openai embeddings.
create_stuff_documents_chain
"""Create a chain for passing a list of Documents to a model. Args: llm: Language model. prompt: Prompt template. Must contain input variable "context", which will be used for passing in the formatted documents. output_parser: Output parser. Defaults to StrOutputParser. ...
def create_stuff_documents_chain(llm: LanguageModelLike, prompt: BasePromptTemplate, *, output_parser: Optional[BaseOutputParser]=None, document_prompt: Optional[BasePromptTemplate]=None, document_separator: str=DEFAULT_DOCUMENT_SEPARATOR) ->Runnable[Dict[str, Any], Any]: """Create a chain for passing a...
Create a chain for passing a list of Documents to a model. Args: llm: Language model. prompt: Prompt template. Must contain input variable "context", which will be used for passing in the formatted documents. output_parser: Output parser. Defaults to StrOutputParser. doc...
run
"""Run query through WolframAlpha and parse result.""" res = self.wolfram_client.query(query) try: assumption = next(res.pods).text answer = next(res.results).text except StopIteration: return "Wolfram Alpha wasn't able to answer it" if answer is None or answer == '': return 'No good Wolfram Alpha Resul...
def run(self, query: str) ->str: """Run query through WolframAlpha and parse result.""" res = self.wolfram_client.query(query) try: assumption = next(res.pods).text answer = next(res.results).text except StopIteration: return "Wolfram Alpha wasn't able to answer it" if answer...
Run query through WolframAlpha and parse result.
_get_folder
req_folder = urllib.request.Request(self._get_folder_url.format(id=folder_id)) with urllib.request.urlopen(req_folder) as response: json_data = json.loads(response.read().decode()) return json_data['title']
def _get_folder(self, folder_id: str) ->str: req_folder = urllib.request.Request(self._get_folder_url.format(id= folder_id)) with urllib.request.urlopen(req_folder) as response: json_data = json.loads(response.read().decode()) return json_data['title']
null
_import_vllm_openai
from langchain_community.llms.vllm import VLLMOpenAI return VLLMOpenAI
def _import_vllm_openai() ->Any: from langchain_community.llms.vllm import VLLMOpenAI return VLLMOpenAI
null
_import_nlpcloud
from langchain_community.llms.nlpcloud import NLPCloud return NLPCloud
def _import_nlpcloud() ->Any: from langchain_community.llms.nlpcloud import NLPCloud return NLPCloud
null
pytest_collection_modifyitems
"""Add implementations for handling custom markers. At the moment, this adds support for a custom `requires` marker. The `requires` marker is used to denote tests that require one or more packages to be installed to run. If the package is not installed, the test is skipped. The `requires` marker synt...
def pytest_collection_modifyitems(config: Config, items: Sequence[Function] ) ->None: """Add implementations for handling custom markers. At the moment, this adds support for a custom `requires` marker. The `requires` marker is used to denote tests that require one or more packages to be installed...
Add implementations for handling custom markers. At the moment, this adds support for a custom `requires` marker. The `requires` marker is used to denote tests that require one or more packages to be installed to run. If the package is not installed, the test is skipped. The `requires` marker syntax is: .. code-blo...
visit_operation
args = [arg.accept(self) for arg in operation.arguments] return {'bool': {self._format_func(operation.operator): args}}
def visit_operation(self, operation: Operation) ->Dict: args = [arg.accept(self) for arg in operation.arguments] return {'bool': {self._format_func(operation.operator): args}}
null
check_ruff
"""Run ruff check on a file.""" subprocess.check_output(f'ruff check {filepath}', stderr=subprocess.STDOUT, shell=True, timeout=3, text=True)
def check_ruff(filepath: str): """Run ruff check on a file.""" subprocess.check_output(f'ruff check {filepath}', stderr=subprocess. STDOUT, shell=True, timeout=3, text=True)
Run ruff check on a file.
test_all_imports
assert set(__all__) == set(EXPECTED_ALL)
def test_all_imports() ->None: assert set(__all__) == set(EXPECTED_ALL)
null
_import_yandex_gpt
from langchain_community.llms.yandex import YandexGPT return YandexGPT
def _import_yandex_gpt() ->Any: from langchain_community.llms.yandex import YandexGPT return YandexGPT
null
lazy_load
query_result = self._execute_query() if isinstance(query_result, Exception): print(f'An error occurred during the query: {query_result}') return [] page_content_columns, metadata_columns = self._get_columns(query_result) if '*' in page_content_columns: page_content_columns = list(query_result[0].keys()) for...
def lazy_load(self) ->Iterator[Document]: query_result = self._execute_query() if isinstance(query_result, Exception): print(f'An error occurred during the query: {query_result}') return [] page_content_columns, metadata_columns = self._get_columns(query_result) if '*' in page_content_co...
null