method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
evaluate
"""Evaluate question answering examples and predictions.""" inputs = [{'query': example[question_key], 'answer': example[answer_key], 'result': predictions[i][prediction_key]} for i, example in enumerate( examples)] return self.apply(inputs, callbacks=callbacks)
def evaluate(self, examples: Sequence[dict], predictions: Sequence[dict], question_key: str='query', answer_key: str='answer', prediction_key: str='result', *, callbacks: Callbacks=None) ->List[dict]: """Evaluate question answering examples and predictions.""" inputs = [{'query': example[question_key], ...
Evaluate question answering examples and predictions.
test_streamlit_callback_agent
import streamlit as st from langchain.agents import AgentType, initialize_agent, load_tools streamlit_callback = StreamlitCallbackHandler(st.container()) llm = OpenAI(temperature=0) tools = load_tools(['serpapi', 'llm-math'], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType. ZERO_SHOT_REACT_DESCRIPTION...
@pytest.mark.requires('streamlit') def test_streamlit_callback_agent() ->None: import streamlit as st from langchain.agents import AgentType, initialize_agent, load_tools streamlit_callback = StreamlitCallbackHandler(st.container()) llm = OpenAI(temperature=0) tools = load_tools(['serpapi', 'llm-mat...
null
yield_keys
"""Get an iterator over keys that match the given prefix. Args: prefix (str, optional): The prefix to match. Defaults to None. Returns: Iterator[str]: An iterator over keys that match the given prefix. """ if prefix is None: yield from self.store.keys() else: fo...
def yield_keys(self, prefix: Optional[str]=None) ->Iterator[str]: """Get an iterator over keys that match the given prefix. Args: prefix (str, optional): The prefix to match. Defaults to None. Returns: Iterator[str]: An iterator over keys that match the given prefix. ...
Get an iterator over keys that match the given prefix. Args: prefix (str, optional): The prefix to match. Defaults to None. Returns: Iterator[str]: An iterator over keys that match the given prefix.
test_stream
"""Test that stream works.""" chat = ChatZhipuAI(streaming=True) callback_handler = FakeCallbackHandler() callback_manager = CallbackManager([callback_handler]) response = chat(messages=[HumanMessage(content='Hello.'), AIMessage(content ='Hello!'), HumanMessage(content='Who are you?')], stream=True, callbacks=c...
def test_stream() ->None: """Test that stream works.""" chat = ChatZhipuAI(streaming=True) callback_handler = FakeCallbackHandler() callback_manager = CallbackManager([callback_handler]) response = chat(messages=[HumanMessage(content='Hello.'), AIMessage( content='Hello!'), HumanMessage(cont...
Test that stream works.
sitemap_metadata_one
return {**meta, 'mykey': 'Super Important Metadata'}
def sitemap_metadata_one(meta: dict, _content: None) ->dict: return {**meta, 'mykey': 'Super Important Metadata'}
null
validate_environment
google_api_key = get_from_dict_or_env(values, 'google_api_key', 'GOOGLE_API_KEY') if isinstance(google_api_key, SecretStr): google_api_key = google_api_key.get_secret_value() genai.configure(api_key=google_api_key) if values.get('temperature') is not None and not 0 <= values['temperature' ] <= 1: raise ...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: google_api_key = get_from_dict_or_env(values, 'google_api_key', 'GOOGLE_API_KEY') if isinstance(google_api_key, SecretStr): google_api_key = google_api_key.get_secret_value() genai.configure(api_key=google_api_key) if ...
null
test_run_error
responses.add(responses.POST, api_client.outline_instance_url + api_client. outline_search_endpoint, json=OUTLINE_ERROR_RESPONSE, status=401) try: api_client.run('Testing') except Exception as e: assert 'Outline API returned an error:' in str(e)
@responses.activate def test_run_error(api_client: OutlineAPIWrapper) ->None: responses.add(responses.POST, api_client.outline_instance_url + api_client.outline_search_endpoint, json=OUTLINE_ERROR_RESPONSE, status=401) try: api_client.run('Testing') except Exception as e: ass...
null
validate_environment
"""Validates the environment.""" try: from google.cloud import discoveryengine_v1beta except ImportError as exc: raise ImportError( 'google.cloud.discoveryengine is not installed.Please install it with pip install google-cloud-discoveryengine>=0.11.0' ) from exc try: from google.api_core.exc...
@root_validator(pre=True) def validate_environment(cls, values: Dict) ->Dict: """Validates the environment.""" try: from google.cloud import discoveryengine_v1beta except ImportError as exc: raise ImportError( 'google.cloud.discoveryengine is not installed.Please install it with ...
Validates the environment.
test_invoke_stream_passthrough_assign_trace
def idchain_sync(__input: dict) ->bool: return False chain = RunnablePassthrough.assign(urls=idchain_sync) tracer = FakeTracer() chain.invoke({'example': [1, 2, 3]}, dict(callbacks=[tracer])) assert tracer.runs[0].name == 'RunnableAssign<urls>' assert tracer.runs[0].child_runs[0].name == 'RunnableParallel<urls>' tr...
def test_invoke_stream_passthrough_assign_trace() ->None: def idchain_sync(__input: dict) ->bool: return False chain = RunnablePassthrough.assign(urls=idchain_sync) tracer = FakeTracer() chain.invoke({'example': [1, 2, 3]}, dict(callbacks=[tracer])) assert tracer.runs[0].name == 'RunnableAs...
null
raise_value_error
"""Raise a value error.""" raise ValueError(f'x is {x}')
def raise_value_error(x: str) ->Any: """Raise a value error.""" raise ValueError(f'x is {x}')
Raise a value error.
__init__
if inspect.iscoroutinefunction(func): afunc = func func = None super().__init__(func=func, afunc=afunc, input_type=input_type, **kwargs)
def __init__(self, func: Optional[Union[Union[Callable[[Other], None], Callable[[Other, RunnableConfig], None]], Union[Callable[[Other], Awaitable[None]], Callable[[Other, RunnableConfig], Awaitable[None]]]]] =None, afunc: Optional[Union[Callable[[Other], Awaitable[None]], Callable[[Other, RunnableConfi...
null
get_resized_images
""" Resize images from base64-encoded strings. :param docs: A list of base64-encoded image to be resized. :return: Dict containing a list of resized base64-encoded strings. """ b64_images = [] for doc in docs: if isinstance(doc, Document): doc = doc.page_content b64_images.append(doc) r...
def get_resized_images(docs): """ Resize images from base64-encoded strings. :param docs: A list of base64-encoded image to be resized. :return: Dict containing a list of resized base64-encoded strings. """ b64_images = [] for doc in docs: if isinstance(doc, Document): d...
Resize images from base64-encoded strings. :param docs: A list of base64-encoded image to be resized. :return: Dict containing a list of resized base64-encoded strings.
load
"""Load documents.""" try: import pandas as pd except ImportError: raise ImportError( 'pandas is needed for Notebook Loader, please install with `pip install pandas`' ) p = Path(self.file_path) with open(p, encoding='utf8') as f: d = json.load(f) data = pd.json_normalize(d['cells']) filtered...
def load(self) ->List[Document]: """Load documents.""" try: import pandas as pd except ImportError: raise ImportError( 'pandas is needed for Notebook Loader, please install with `pip install pandas`' ) p = Path(self.file_path) with open(p, encoding='utf8') as ...
Load documents.
_add_child_run
"""Add child run to a chain run or tool run.""" parent_run.child_runs.append(child_run)
@staticmethod def _add_child_run(parent_run: Run, child_run: Run) ->None: """Add child run to a chain run or tool run.""" parent_run.child_runs.append(child_run)
Add child run to a chain run or tool run.
_run
"""Use the tool.""" return str(self.api_wrapper.run(query))
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] =None) ->str: """Use the tool.""" return str(self.api_wrapper.run(query))
Use the tool.
load
"""Load file""" data = self._get_figma_file() text = stringify_dict(data) metadata = {'source': self._construct_figma_api_url()} return [Document(page_content=text, metadata=metadata)]
def load(self) ->List[Document]: """Load file""" data = self._get_figma_file() text = stringify_dict(data) metadata = {'source': self._construct_figma_api_url()} return [Document(page_content=text, metadata=metadata)]
Load file
_llm_type
"""Return type of chat model.""" return 'everlyai-chat'
@property def _llm_type(self) ->str: """Return type of chat model.""" return 'everlyai-chat'
Return type of chat model.
_transform_chat
return response['choices'][0]['message']['content']
def _transform_chat(response: Dict[str, Any]) ->str: return response['choices'][0]['message']['content']
null
embed_documents
embeddings: List[List[float]] = [] for text in texts: embeddings.append([len(text), len(text) + 1]) return embeddings
def embed_documents(self, texts: List[str]) ->List[List[float]]: embeddings: List[List[float]] = [] for text in texts: embeddings.append([len(text), len(text) + 1]) return embeddings
null
test_anthropic_model_param
llm = Anthropic(model='foo') assert llm.model == 'foo'
@pytest.mark.requires('anthropic') def test_anthropic_model_param() ->None: llm = Anthropic(model='foo') assert llm.model == 'foo'
null
get_context_and_action_embeddings
context_emb = base.embed(event.based_on, self.model ) if event.based_on else None to_select_from_var_name, to_select_from = next(iter(event.to_select_from. items()), (None, None)) action_embs = (base.embed(to_select_from, self.model, to_select_from_var_name) if event.to_select_from else None ) if to_sel...
def get_context_and_action_embeddings(self, event: PickBestEvent) ->tuple: context_emb = base.embed(event.based_on, self.model ) if event.based_on else None to_select_from_var_name, to_select_from = next(iter(event. to_select_from.items()), (None, None)) action_embs = (base.embed(to_select_f...
null
_import_elevenlabs
try: import elevenlabs except ImportError as e: raise ImportError( 'Cannot import elevenlabs, please install `pip install elevenlabs`.' ) from e return elevenlabs
def _import_elevenlabs() ->Any: try: import elevenlabs except ImportError as e: raise ImportError( 'Cannot import elevenlabs, please install `pip install elevenlabs`.' ) from e return elevenlabs
null
_invocation_params
params = self._default_params if self.stop is not None and stop is not None: raise ValueError('`stop` found in both the input and default params.') elif self.stop is not None: params['stop_sequences'] = self.stop else: params['stop_sequences'] = stop return {**params, **kwargs}
def _invocation_params(self, stop: Optional[List[str]], **kwargs: Any) ->dict: params = self._default_params if self.stop is not None and stop is not None: raise ValueError('`stop` found in both the input and default params.') elif self.stop is not None: params['stop_sequences'] = self.stop ...
null
get_runtime_environment
"""Get information about the LangChain runtime environment.""" from langchain_core import __version__ return {'library_version': __version__, 'library': 'langchain-core', '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_core import __version__ return {'library_version': __version__, 'library': 'langchain-core', 'platform': platform.platform(), 'runtime': 'python', 'runtim...
Get information about the LangChain runtime environment.
test_sklearn
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] docsearch = SKLearnVectorStore.from_texts(texts, FakeEmbeddings()) output = docsearch.similarity_search('foo', k=1) assert len(output) == 1 assert output[0].page_content == 'foo'
@pytest.mark.requires('numpy', 'sklearn') def test_sklearn() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] docsearch = SKLearnVectorStore.from_texts(texts, FakeEmbeddings()) output = docsearch.similarity_search('foo', k=1) assert len(output) == 1 assert out...
Test end to end construction and search.
test_faiss_similarity_search_with_relevance_scores
"""Test the similarity search with normalized similarities.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings(), relevance_score_fn=lambda score: 1.0 - score / math.sqrt(2)) outputs = docsearch.similarity_search_with_relevance_scores('foo', k=1) output, score = outputs[0] assert ou...
@pytest.mark.requires('faiss') def test_faiss_similarity_search_with_relevance_scores() ->None: """Test the similarity search with normalized similarities.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings(), relevance_score_fn=lambda score: 1.0 - score / math.sqrt(...
Test the similarity search with normalized similarities.
_load_sheet_from_id
"""Load a sheet and all tabs from an ID.""" from googleapiclient.discovery import build creds = self._load_credentials() sheets_service = build('sheets', 'v4', credentials=creds) spreadsheet = sheets_service.spreadsheets().get(spreadsheetId=id).execute() sheets = spreadsheet.get('sheets', []) documents = [] for sheet i...
def _load_sheet_from_id(self, id: str) ->List[Document]: """Load a sheet and all tabs from an ID.""" from googleapiclient.discovery import build creds = self._load_credentials() sheets_service = build('sheets', 'v4', credentials=creds) spreadsheet = sheets_service.spreadsheets().get(spreadsheetId=id...
Load a sheet and all tabs from an ID.
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() input_text = f"""{inputs[self.input_key]} SQLQuery:""" _run_manager.on_text(input_text, verbose=self.verbose) table_names_to_use = inputs.get('table_names_to_use') table_info = self.database.get_table_info(table_names=table_names_to_use) llm_in...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() input_text = f'{inputs[self.input_key]}\nSQLQuery:' _run_manager.on_text(input_text, verbose=self.verbose) ta...
null
_import_dashvector
from langchain_community.vectorstores.dashvector import DashVector return DashVector
def _import_dashvector() ->Any: from langchain_community.vectorstores.dashvector import DashVector return DashVector
null
_document_details_for_docset_id
"""Gets all document details for the given docset ID""" url = f'{self.api}/docsets/{docset_id}/documents' all_documents = [] while url: response = requests.get(url, headers={'Authorization': f'Bearer {self.access_token}'}) if response.ok: data = response.json() all_documents.extend(data[...
def _document_details_for_docset_id(self, docset_id: str) ->List[Dict]: """Gets all document details for the given docset ID""" url = f'{self.api}/docsets/{docset_id}/documents' all_documents = [] while url: response = requests.get(url, headers={'Authorization': f'Bearer {self.access...
Gets all document details for the given docset ID
test_with_metadatas_with_scores
"""Test end to end construction and scored search.""" texts = ['hello bagel', 'hello langchain'] metadatas = [{'page': str(i)} for i in range(len(texts))] txt_search = Bagel.from_texts(cluster_name='testing', texts=texts, metadatas=metadatas) output = txt_search.similarity_search_with_score('hello bagel', k=1) asse...
def test_with_metadatas_with_scores() ->None: """Test end to end construction and scored search.""" texts = ['hello bagel', 'hello langchain'] metadatas = [{'page': str(i)} for i in range(len(texts))] txt_search = Bagel.from_texts(cluster_name='testing', texts=texts, metadatas=metadatas) out...
Test end to end construction and scored search.
validate_environment
"""Validate that python package exists in environment.""" try: from vllm import LLM as VLLModel except ImportError: raise ImportError( 'Could not import vllm python package. Please install it with `pip install vllm`.' ) values['client'] = VLLModel(model=values['model'], tensor_parallel_size= ...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that python package exists in environment.""" try: from vllm import LLM as VLLModel except ImportError: raise ImportError( 'Could not import vllm python package. Please install it with `pip install ...
Validate that python package exists in environment.
max_marginal_relevance_search
embeddings = self._embedding.embed_query(query) docs = self.max_marginal_relevance_search_by_vector(embeddings, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult) return docs
def max_marginal_relevance_search(self, query: str, k: int=4, fetch_k: int= 20, lambda_mult: float=0.5, **kwargs: Any) ->List[Document]: embeddings = self._embedding.embed_query(query) docs = self.max_marginal_relevance_search_by_vector(embeddings, k=k, fetch_k=fetch_k, lambda_mult=lambda_mult) ...
null
test_loadnotebookwithimage_notehasplaintextonlywithresourcesremoved
documents = EverNoteLoader(self.example_notebook_path( 'sample_notebook_with_media.enex'), False).load() note = documents[0] assert note.page_content == """When you pick this mug up with your thumb on top and middle finger through the loop, your ring finger slides into the mug under the loop where it is too hot to ...
def test_loadnotebookwithimage_notehasplaintextonlywithresourcesremoved(self ) ->None: documents = EverNoteLoader(self.example_notebook_path( 'sample_notebook_with_media.enex'), False).load() note = documents[0] assert note.page_content == """When you pick this mug up with your thumb on top and ...
null
test_redis_from_documents
"""Test from_documents constructor.""" docs = [Document(page_content=t, metadata={'a': 'b'}) for t in texts] docsearch = Redis.from_documents(docs, FakeEmbeddings(), redis_url= TEST_REDIS_URL) output = docsearch.similarity_search('foo', k=1, return_metadata=True) assert 'a' in output[0].metadata.keys() assert 'b' i...
def test_redis_from_documents(texts: List[str]) ->None: """Test from_documents constructor.""" docs = [Document(page_content=t, metadata={'a': 'b'}) for t in texts] docsearch = Redis.from_documents(docs, FakeEmbeddings(), redis_url= TEST_REDIS_URL) output = docsearch.similarity_search('foo', k=1...
Test from_documents constructor.
test_delete_fail_no_ids
index = mock_index(DIRECT_ACCESS_INDEX) vectorsearch = default_databricks_vector_search(index) with pytest.raises(ValueError) as ex: vectorsearch.delete() assert 'ids must be provided.' in str(ex.value)
@pytest.mark.requires('databricks', 'databricks.vector_search') def test_delete_fail_no_ids() ->None: index = mock_index(DIRECT_ACCESS_INDEX) vectorsearch = default_databricks_vector_search(index) with pytest.raises(ValueError) as ex: vectorsearch.delete() assert 'ids must be provided.' in str(e...
null
_call
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() response = self.chain.run(**inputs, callbacks=_run_manager.get_child( 'original')) initial_response = response input_prompt = self.chain.prompt.format(**inputs) _run_manager.on_text(text='Initial response: ' + response + '\n\n', verbose ...
def _call(self, inputs: Dict[str, Any], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, Any]: _run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() response = self.chain.run(**inputs, callbacks=_run_manager.get_child( 'original')) initial_response = res...
null
_fetch_valid_connection_docs
if self.ignore_load_errors: try: return self.session.get(url, **self.requests_kwargs) except Exception as e: warnings.warn(str(e)) return None return self.session.get(url, **self.requests_kwargs)
def _fetch_valid_connection_docs(self, url: str) ->Any: if self.ignore_load_errors: try: return self.session.get(url, **self.requests_kwargs) except Exception as e: warnings.warn(str(e)) return None return self.session.get(url, **self.requests_kwargs)
null
test_timescalevector_with_filter_no_match
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = TimescaleVector.from_texts(texts=texts, collection_name= 'test_collection_filter', embedding=FakeEmbeddingsWithAdaDimension(), metadatas=metadatas, service_url=SERVI...
def test_timescalevector_with_filter_no_match() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] docsearch = TimescaleVector.from_texts(texts=texts, collection_name= 'test_collection_filter', embedding=...
Test end to end construction and search.
_run
"""Use the tool. Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enable tracing, """
@abstractmethod def _run(self, *args: Any, **kwargs: Any) ->Any: """Use the tool. Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enable tracing, """
Use the tool. Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enable tracing,
_run
"""Get the schema for a specific table.""" return ', '.join(self.db.get_usable_table_names())
def _run(self, tool_input: str='', run_manager: Optional[ CallbackManagerForToolRun]=None) ->str: """Get the schema for a specific table.""" return ', '.join(self.db.get_usable_table_names())
Get the schema for a specific table.
_model_is_anthropic
return self._get_provider() == 'anthropic'
@property def _model_is_anthropic(self) ->bool: return self._get_provider() == 'anthropic'
null
load_prompt
"""Unified method for loading a prompt from LangChainHub or local fs.""" if (hub_result := try_load_from_hub(path, _load_prompt_from_file, 'prompts', {'py', 'json', 'yaml'})): return hub_result else: return _load_prompt_from_file(path)
def load_prompt(path: Union[str, Path]) ->BasePromptTemplate: """Unified method for loading a prompt from LangChainHub or local fs.""" if (hub_result := try_load_from_hub(path, _load_prompt_from_file, 'prompts', {'py', 'json', 'yaml'})): return hub_result else: return _load_prompt_fr...
Unified method for loading a prompt from LangChainHub or local fs.
check_dependency
for dep_id in task.dep: if dep_id == -1: continue dep_task = self.id_task_map[dep_id] if dep_task.failed() or dep_task.pending(): return False return True
def check_dependency(self, task: Task) ->bool: for dep_id in task.dep: if dep_id == -1: continue dep_task = self.id_task_map[dep_id] if dep_task.failed() or dep_task.pending(): return False return True
null
new
""" Create a new LangServe application. """ has_packages = package is not None and len(package) > 0 if noninteractive: if name is None: raise typer.BadParameter( 'name is required when --non-interactive is set') name_str = name pip_bool = bool(pip) else: name_str = name if na...
@app_cli.command() def new(name: Annotated[Optional[str], typer.Argument(help= 'The name of the folder to create')]=None, *, package: Annotated[ Optional[List[str]], typer.Option(help= 'Packages to seed the project with')]=None, pip: Annotated[Optional[ bool], typer.Option('--pip/--no-pip', help= 'P...
Create a new LangServe application.
_default_params
"""Default parameters for the model.""" raise NotImplementedError
@property def _default_params(self) ->Dict[str, Any]: """Default parameters for the model.""" raise NotImplementedError
Default parameters for the model.
_generate
completion = '' if self.streaming: for chunk in self._stream(messages, stop, run_manager, **kwargs): completion += chunk.text else: provider = self._get_provider() prompt = ChatPromptAdapter.convert_messages_to_prompt(provider=provider, messages=messages) params: Dict[str, Any] = {**kwar...
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->ChatResult: completion = '' if self.streaming: for chunk in self._stream(messages, stop, run_manager, **kwargs): completion += chu...
null
lc_serializable
return True
@property def lc_serializable(self) ->bool: return True
null
__init__
"""Create a new MutableExpander. Parameters ---------- parent_container The `st.container` that the expander will be created inside. The expander transparently deletes and recreates its underlying `st.expander` instance when its label changes, and it uses ...
def __init__(self, parent_container: DeltaGenerator, label: str, expanded: bool ): """Create a new MutableExpander. Parameters ---------- parent_container The `st.container` that the expander will be created inside. The expander transparently deletes and recreat...
Create a new MutableExpander. Parameters ---------- parent_container The `st.container` that the expander will be created inside. The expander transparently deletes and recreates its underlying `st.expander` instance when its label changes, and it uses `parent_container` to ensure it recreates this un...