method_name stringlengths 1 78 | method_body stringlengths 3 9.66k | full_code stringlengths 31 10.7k | docstring stringlengths 4 4.74k ⌀ |
|---|---|---|---|
_load_qa_with_sources_chain | if 'combine_documents_chain' in config:
combine_documents_chain_config = config.pop('combine_documents_chain')
combine_documents_chain = load_chain_from_config(
combine_documents_chain_config)
elif 'combine_documents_chain_path' in config:
combine_documents_chain = load_chain(config.pop(
'co... | def _load_qa_with_sources_chain(config: dict, **kwargs: Any
) ->QAWithSourcesChain:
if 'combine_documents_chain' in config:
combine_documents_chain_config = config.pop('combine_documents_chain')
combine_documents_chain = load_chain_from_config(
combine_documents_chain_config)
eli... | null |
test_pwd_command_persistent | """Test correct functionality when the bash process is persistent."""
session = BashProcess(persistent=True, strip_newlines=True)
commands = ['pwd']
output = session.run(commands)
assert subprocess.check_output('pwd', shell=True).decode().strip() in output
session.run(['cd ..'])
new_output = session.run(['pwd'])
assert... | @pytest.mark.skip(reason='flaky on GHA, TODO to fix')
@pytest.mark.skipif(sys.platform.startswith('win'), reason=
'Test not supported on Windows')
def test_pwd_command_persistent() ->None:
"""Test correct functionality when the bash process is persistent."""
session = BashProcess(persistent=True, strip_newl... | Test correct functionality when the bash process is persistent. |
test_sql_chain_with_memory | valid_prompt_with_history = """
Only use the following tables:
{table_info}
Question: {input}
Given an input question, first create a syntactically correct
{dialect} query to run.
Always limit your query to at most {top_k} results.
Relevant pieces of previous conversation:
{history}
... | def test_sql_chain_with_memory() ->None:
valid_prompt_with_history = """
Only use the following tables:
{table_info}
Question: {input}
Given an input question, first create a syntactically correct
{dialect} query to run.
Always limit your query to at most {top_k} results.
Relevant piec... | 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.
kwargs: vectorstore specific parameters.
Returns:
List of id... | def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]=
None, **kwargs: Any) ->List[str]:
"""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 ass... | 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.
kwargs: vectorstore specific parameters.
Returns:
List of ids from adding the texts into the vectorstore. |
load_json_to_dict | """Load json file to a dictionary.
Parameters:
json_path (str): The path to the json file.
Returns:
(dict): The dictionary representation of the json file.
"""
with open(json_path, 'r') as f:
data = json.load(f)
return data | def load_json_to_dict(json_path: Union[str, Path]) ->dict:
"""Load json file to a dictionary.
Parameters:
json_path (str): The path to the json file.
Returns:
(dict): The dictionary representation of the json file.
"""
with open(json_path, 'r') as f:
data = json.load(f)
... | Load json file to a dictionary.
Parameters:
json_path (str): The path to the json file.
Returns:
(dict): The dictionary representation of the json file. |
test_openai_functions_router | revise = mocker.Mock(side_effect=lambda kw:
f"Revised draft: no more {kw['notes']}!")
accept = mocker.Mock(side_effect=lambda kw: f"Accepted draft: {kw['draft']}!")
router = OpenAIFunctionsRouter({'revise': revise, 'accept': accept},
functions=[{'name': 'revise', 'description':
'Sends the draft for revision... | def test_openai_functions_router(snapshot: SnapshotAssertion, mocker:
MockerFixture) ->None:
revise = mocker.Mock(side_effect=lambda kw:
f"Revised draft: no more {kw['notes']}!")
accept = mocker.Mock(side_effect=lambda kw:
f"Accepted draft: {kw['draft']}!")
router = OpenAIFunctionsRouter... | null |
__deepcopy__ | """Deepcopy the tracer."""
return self | def __deepcopy__(self, memo: dict) ->BaseTracer:
"""Deepcopy the tracer."""
return self | Deepcopy the tracer. |
test_neo4jvector_hybrid_retrieval_query2 | """Test custom retrieval_query with hybrid search."""
text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts)
text_embedding_pairs = list(zip(texts, text_embeddings))
docsearch = Neo4jVector.from_embeddings(text_embeddings=
text_embedding_pairs, embedding=FakeEmbeddingsWithOsDimension(), url=
u... | def test_neo4jvector_hybrid_retrieval_query2() ->None:
"""Test custom retrieval_query with hybrid search."""
text_embeddings = FakeEmbeddingsWithOsDimension().embed_documents(texts)
text_embedding_pairs = list(zip(texts, text_embeddings))
docsearch = Neo4jVector.from_embeddings(text_embeddings=
... | Test custom retrieval_query with hybrid search. |
__init__ | super().__init__(**kwargs)
self.run_map: Dict[str, Run] = {} | def __init__(self, **kwargs: Any) ->None:
super().__init__(**kwargs)
self.run_map: Dict[str, Run] = {} | null |
test_visit_comparison | comp = Comparison(comparator=Comparator.EQ, attribute='foo', value='1')
expected = {'term': {'metadata.foo.keyword': '1'}}
actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
assert expected == actual | def test_visit_comparison() ->None:
comp = Comparison(comparator=Comparator.EQ, attribute='foo', value='1')
expected = {'term': {'metadata.foo.keyword': '1'}}
actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
assert expected == actual | null |
toy_dir | """Yield a pre-populated directory to test the blob loader."""
with tempfile.TemporaryDirectory() as temp_dir:
with open(os.path.join(temp_dir, 'test.txt'), 'w') as test_txt:
test_txt.write('This is a test.txt file.')
with open(os.path.join(temp_dir, 'test.html'), 'w') as test_html:
test_html.wr... | @pytest.fixture
def toy_dir() ->Generator[Path, None, None]:
"""Yield a pre-populated directory to test the blob loader."""
with tempfile.TemporaryDirectory() as temp_dir:
with open(os.path.join(temp_dir, 'test.txt'), 'w') as test_txt:
test_txt.write('This is a test.txt file.')
with ... | Yield a pre-populated directory to test the blob loader. |
to_messages | """Return prompt as messages."""
return [HumanMessage(content=self.text)] | def to_messages(self) ->List[BaseMessage]:
"""Return prompt as messages."""
return [HumanMessage(content=self.text)] | Return prompt as messages. |
test_sql_database_run_update | """Test that update commands run successfully and returned in correct format."""
engine = create_engine('sqlite:///:memory:')
metadata_obj.create_all(engine)
stmt = insert(user).values(user_id=13, user_name='Harrison', user_company='Foo'
)
with engine.connect() as conn:
conn.execute(stmt)
db = SQLDatabase(engin... | def test_sql_database_run_update() ->None:
"""Test that update commands run successfully and returned in correct format."""
engine = create_engine('sqlite:///:memory:')
metadata_obj.create_all(engine)
stmt = insert(user).values(user_id=13, user_name='Harrison',
user_company='Foo')
with engin... | Test that update commands run successfully and returned in correct format. |
test_similarity_search | """Test similarity search"""
from bagel.config import Settings
setting = Settings(bagel_api_impl='rest', bagel_server_host='api.bageldb.ai')
bagel = Bagel(client_settings=setting)
bagel.add_texts(texts=['hello bagel', 'hello langchain'])
result = bagel.similarity_search(query='bagel', k=1)
assert result == [Document(pa... | def test_similarity_search() ->None:
"""Test similarity search"""
from bagel.config import Settings
setting = Settings(bagel_api_impl='rest', bagel_server_host=
'api.bageldb.ai')
bagel = Bagel(client_settings=setting)
bagel.add_texts(texts=['hello bagel', 'hello langchain'])
result = bag... | Test similarity search |
_response_to_generation | """Converts a stream response to a generation chunk."""
try:
generation_info = {'is_blocked': response.is_blocked,
'safety_attributes': response.safety_attributes}
except Exception:
generation_info = None
return GenerationChunk(text=response.text, generation_info=generation_info) | def _response_to_generation(self, response: TextGenerationResponse
) ->GenerationChunk:
"""Converts a stream response to a generation chunk."""
try:
generation_info = {'is_blocked': response.is_blocked,
'safety_attributes': response.safety_attributes}
except Exception:
genera... | Converts a stream response to a generation chunk. |
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. |
test_model_response | parser = OpenAIFunctionsAgentOutputParser()
msg = AIMessage(content='Model response.')
result = parser.invoke(msg)
assert isinstance(result, AgentFinish)
assert result.return_values == {'output': 'Model response.'}
assert result.log == 'Model response.' | def test_model_response() ->None:
parser = OpenAIFunctionsAgentOutputParser()
msg = AIMessage(content='Model response.')
result = parser.invoke(msg)
assert isinstance(result, AgentFinish)
assert result.return_values == {'output': 'Model response.'}
assert result.log == 'Model response.' | null |
on_agent_action | """Run when agent action is received.
Args:
action (AgentAction): The agent action.
Returns:
Any: The result of the callback.
"""
handle_event(self.handlers, 'on_agent_action', 'ignore_agent', action,
run_id=self.run_id, parent_run_id=self.parent_run_id, tags=self.t... | def on_agent_action(self, action: AgentAction, **kwargs: Any) ->Any:
"""Run when agent action is received.
Args:
action (AgentAction): The agent action.
Returns:
Any: The result of the callback.
"""
handle_event(self.handlers, 'on_agent_action', 'ignore_agent', ... | Run when agent action is received.
Args:
action (AgentAction): The agent action.
Returns:
Any: The result of the callback. |
ignore_llm | """Whether to ignore LLM callbacks."""
return self.ignore_llm_ | @property
def ignore_llm(self) ->bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_ | Whether to ignore LLM callbacks. |
_get_post_headers | """Returns headers that should be attached to each post request."""
return {'x-api-key': self._vectara_api_key, 'customer-id': self.
_vectara_customer_id, 'Content-Type': 'application/json', 'X-Source':
self._source} | def _get_post_headers(self) ->dict:
"""Returns headers that should be attached to each post request."""
return {'x-api-key': self._vectara_api_key, 'customer-id': self.
_vectara_customer_id, 'Content-Type': 'application/json',
'X-Source': self._source} | Returns headers that should be attached to each post request. |
from_llm | """Create a TrajectoryEvalChain object from a language model chain.
Args:
llm (BaseChatModel): The language model chain.
agent_tools (Optional[Sequence[BaseTool]]): A list of tools
available to the agent.
output_parser (Optional[TrajectoryOutputParser]): The ... | @classmethod
def from_llm(cls, llm: BaseLanguageModel, agent_tools: Optional[Sequence[
BaseTool]]=None, output_parser: Optional[TrajectoryOutputParser]=None,
**kwargs: Any) ->'TrajectoryEvalChain':
"""Create a TrajectoryEvalChain object from a language model chain.
Args:
llm (BaseChatMo... | Create a TrajectoryEvalChain object from a language model chain.
Args:
llm (BaseChatModel): The language model chain.
agent_tools (Optional[Sequence[BaseTool]]): A list of tools
available to the agent.
output_parser (Optional[TrajectoryOutputParser]): The output parser
used to parse the cha... |
_identifying_params | """Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {'eas_service_url': self.eas_service_url, 'eas_service_token': self.
eas_service_token, **{'model_kwargs': _model_kwargs}} | @property
def _identifying_params(self) ->Dict[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {'eas_service_url': self.eas_service_url, 'eas_service_token':
self.eas_service_token, **{'model_kwargs': _model_kwargs}} | Get the identifying parameters. |
load | """Load documents."""
if self.dropbox_folder_path is not None:
return self._load_documents_from_folder(self.dropbox_folder_path)
else:
return self._load_documents_from_paths() | def load(self) ->List[Document]:
"""Load documents."""
if self.dropbox_folder_path is not None:
return self._load_documents_from_folder(self.dropbox_folder_path)
else:
return self._load_documents_from_paths() | Load documents. |
__repr__ | return str(self) | def __repr__(self) ->str:
return str(self) | null |
similarity_search_with_score | """Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. D... | def similarity_search_with_score(self, query: str, k: int=4, filter:
Optional[dict]=None, namespace: Optional[str]=None) ->List[Tuple[
Document, float]]:
"""Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
... | Return pinecone documents most similar to query, along with scores.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Dictionary of argument(s) to filter on metadata
namespace: Namespace to search in. Default will search in '' namespace.
Return... |
__exit__ | """Close file that stdout was piped to."""
sys.stdout.close()
sys.stdout = self._original_stdout | def __exit__(self, *_: Any) ->None:
"""Close file that stdout was piped to."""
sys.stdout.close()
sys.stdout = self._original_stdout | Close file that stdout was piped to. |
_import_azure_cognitive_services_AzureCogsImageAnalysisTool | from langchain_community.tools.azure_cognitive_services import AzureCogsImageAnalysisTool
return AzureCogsImageAnalysisTool | def _import_azure_cognitive_services_AzureCogsImageAnalysisTool() ->Any:
from langchain_community.tools.azure_cognitive_services import AzureCogsImageAnalysisTool
return AzureCogsImageAnalysisTool | null |
lazy_load | yield from self._get_notes() | def lazy_load(self) ->Iterator[Document]:
yield from self._get_notes() | null |
_generate | generations: List[List[Generation]] = []
generation_config = {'stop_sequences': stop, 'temperature': self.
temperature, 'top_p': self.top_p, 'top_k': self.top_k,
'max_output_tokens': self.max_output_tokens, 'candidate_count': self.n}
for prompt in prompts:
if self.is_gemini:
res = completion_with_re... | def _generate(self, prompts: List[str], stop: Optional[List[str]]=None,
run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any
) ->LLMResult:
generations: List[List[Generation]] = []
generation_config = {'stop_sequences': stop, 'temperature': self.
temperature, 'top_p': self.top_p, ... | null |
setup_class | url = 'http://127.0.0.1:8080/fwww/'
cls.pod = 'vdb'
cls.store = 'langchain_test_store'
vector_index = 'v'
vector_type = 'cosine_fraction_float'
vector_dimension = 10
embeddings = ConsistentFakeEmbeddings()
cls.vectorstore = Jaguar(cls.pod, cls.store, vector_index, vector_type,
vector_dimension, url, embeddings) | @classmethod
def setup_class(cls) ->None:
url = 'http://127.0.0.1:8080/fwww/'
cls.pod = 'vdb'
cls.store = 'langchain_test_store'
vector_index = 'v'
vector_type = 'cosine_fraction_float'
vector_dimension = 10
embeddings = ConsistentFakeEmbeddings()
cls.vectorstore = Jaguar(cls.pod, cls.st... | null |
false | return False | def false(self) ->bool:
return False | null |
test_typescript_code_splitter | splitter = RecursiveCharacterTextSplitter.from_language(Language.TS,
chunk_size=CHUNK_SIZE, chunk_overlap=0)
code = """
function helloWorld(): void {
console.log("Hello, World!");
}
// Call the function
helloWorld();
"""
chunks = splitter.split_text(code)
assert chunks == ['function', 'helloWorld():', 'void ... | def test_typescript_code_splitter() ->None:
splitter = RecursiveCharacterTextSplitter.from_language(Language.TS,
chunk_size=CHUNK_SIZE, chunk_overlap=0)
code = """
function helloWorld(): void {
console.log("Hello, World!");
}
// Call the function
helloWorld();
"""
chunks = splitter.split_text... | null |
similarity_search | """Return docs most similar to query.
By default, supports Approximate Search.
Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of ... | def similarity_search(self, query: str, k: int=4, **kwargs: Any) ->List[
Document]:
"""Return docs most similar to query.
By default, supports Approximate Search.
Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
... | Return docs most similar to query.
By default, supports Approximate Search.
Also supports Script Scoring and Painless Scripting.
Args:
query: Text to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
Returns:
List of Documents most similar to the query.
Optional Args:
ve... |
_get_scenexplain | return SceneXplainTool(**kwargs) | def _get_scenexplain(**kwargs: Any) ->BaseTool:
return SceneXplainTool(**kwargs) | null |
create_list | """
Creates a new list.
"""
query_dict, error = load_query(query, fault_tolerant=True)
if query_dict is None:
return {'Error': error}
location = self.folder_id if self.folder_id else self.space_id
url = f'{DEFAULT_URL}/folder/{location}/list'
payload = extract_dict_elements_from_component_fields(que... | def create_list(self, query: str) ->Dict:
"""
Creates a new list.
"""
query_dict, error = load_query(query, fault_tolerant=True)
if query_dict is None:
return {'Error': error}
location = self.folder_id if self.folder_id else self.space_id
url = f'{DEFAULT_URL}/folder/{locatio... | Creates a new list. |
from_credentials | """Initialize callback handler from Arthur credentials.
Args:
model_id (str): The ID of the arthur model to log to.
arthur_url (str, optional): The URL of the Arthur instance to log to.
Defaults to "https://app.arthur.ai".
arthur_login (str, optional): The lo... | @classmethod
def from_credentials(cls, model_id: str, arthur_url: Optional[str]=
'https://app.arthur.ai', arthur_login: Optional[str]=None,
arthur_password: Optional[str]=None) ->ArthurCallbackHandler:
"""Initialize callback handler from Arthur credentials.
Args:
model_id (str): The ID ... | Initialize callback handler from Arthur credentials.
Args:
model_id (str): The ID of the arthur model to log to.
arthur_url (str, optional): The URL of the Arthur instance to log to.
Defaults to "https://app.arthur.ai".
arthur_login (str, optional): The login to use to connect to Arthur.
De... |
test_load_nonexistent_dataset | """Tests that ValueError is thrown for nonexistent dataset name"""
page_content_column = 'text'
name = 'v3'
loader = HuggingFaceDatasetLoader(HUGGING_FACE_EXAMPLE_DATASET,
page_content_column, name)
with pytest.raises(ValueError):
loader.load() | @pytest.mark.requires('datasets')
@pytest.fixture
def test_load_nonexistent_dataset() ->None:
"""Tests that ValueError is thrown for nonexistent dataset name"""
page_content_column = 'text'
name = 'v3'
loader = HuggingFaceDatasetLoader(HUGGING_FACE_EXAMPLE_DATASET,
page_content_column, name)
... | Tests that ValueError is thrown for nonexistent dataset name |
test_prompttemplate_validation | """Test that few shot works when prefix and suffix are PromptTemplates."""
prefix = PromptTemplate(input_variables=['content'], template=
'This is a test about {content}.')
suffix = PromptTemplate(input_variables=['new_content'], template=
'Now you try to talk about {new_content}.')
examples = [{'question': 'fo... | def test_prompttemplate_validation() ->None:
"""Test that few shot works when prefix and suffix are PromptTemplates."""
prefix = PromptTemplate(input_variables=['content'], template=
'This is a test about {content}.')
suffix = PromptTemplate(input_variables=['new_content'], template=
'Now yo... | Test that few shot works when prefix and suffix are PromptTemplates. |
_get_invocation_params | """Get the parameters used to invoke the model FOR THE CALLBACKS."""
return {**self._default_params, **super()._get_invocation_params(stop=stop,
**kwargs)} | def _get_invocation_params(self, stop: Optional[List[str]]=None, **kwargs: Any
) ->Dict[str, Any]:
"""Get the parameters used to invoke the model FOR THE CALLBACKS."""
return {**self._default_params, **super()._get_invocation_params(stop=
stop, **kwargs)} | Get the parameters used to invoke the model FOR THE CALLBACKS. |
test_call | """Test that call runs."""
twilio = TwilioAPIWrapper()
output = twilio.run('Message', '+16162904619')
assert output | def test_call() ->None:
"""Test that call runs."""
twilio = TwilioAPIWrapper()
output = twilio.run('Message', '+16162904619')
assert output | Test that call runs. |
__init__ | """Instantiate a prompt cache using Momento as a backend.
Note: to instantiate the cache client passed to MomentoCache,
you must have a Momento account. See https://gomomento.com/.
Args:
cache_client (CacheClient): The Momento cache client.
cache_name (str): The name of... | def __init__(self, cache_client: momento.CacheClient, cache_name: str, *,
ttl: Optional[timedelta]=None, ensure_cache_exists: bool=True):
"""Instantiate a prompt cache using Momento as a backend.
Note: to instantiate the cache client passed to MomentoCache,
you must have a Momento account. See ... | Instantiate a prompt cache using Momento as a backend.
Note: to instantiate the cache client passed to MomentoCache,
you must have a Momento account. See https://gomomento.com/.
Args:
cache_client (CacheClient): The Momento cache client.
cache_name (str): The name of the cache to use to store the data.
tt... |
_get_relevant_documents | """
Get the relevant documents for a given query.
Args:
query: The query to search for.
Returns:
A list of relevant documents.
"""
merged_documents = self.merge_documents(query, run_manager)
return merged_documents | def _get_relevant_documents(self, query: str, *, run_manager:
CallbackManagerForRetrieverRun) ->List[Document]:
"""
Get the relevant documents for a given query.
Args:
query: The query to search for.
Returns:
A list of relevant documents.
"""
merged_... | Get the relevant documents for a given query.
Args:
query: The query to search for.
Returns:
A list of relevant documents. |
_import_metaphor_search | from langchain_community.tools.metaphor_search import MetaphorSearchResults
return MetaphorSearchResults | def _import_metaphor_search() ->Any:
from langchain_community.tools.metaphor_search import MetaphorSearchResults
return MetaphorSearchResults | null |
__add__ | if isinstance(other, ChatMessageChunk):
if self.role != other.role:
raise ValueError(
'Cannot concatenate ChatMessageChunks with different roles.')
return self.__class__(role=self.role, content=merge_content(self.
content, other.content), additional_kwargs=self._merge_kwargs_dict(
... | def __add__(self, other: Any) ->BaseMessageChunk:
if isinstance(other, ChatMessageChunk):
if self.role != other.role:
raise ValueError(
'Cannot concatenate ChatMessageChunks with different roles.')
return self.__class__(role=self.role, content=merge_content(self.
... | null |
_call | """Run the chain and generate the output.
Args:
inputs (Dict[str, str]): The input values for the chain.
run_manager (Optional[CallbackManagerForChainRun]): The callback
manager for the chain run.
Returns:
Dict[str, Any]: The output values of the cha... | def _call(self, inputs: Dict[str, str], run_manager: Optional[
CallbackManagerForChainRun]=None) ->Dict[str, Any]:
"""Run the chain and generate the output.
Args:
inputs (Dict[str, str]): The input values for the chain.
run_manager (Optional[CallbackManagerForChainRun]): The cal... | Run the chain and generate the output.
Args:
inputs (Dict[str, str]): The input values for the chain.
run_manager (Optional[CallbackManagerForChainRun]): The callback
manager for the chain run.
Returns:
Dict[str, Any]: The output values of the chain. |
test_retrieval_qa_with_sources_chain_saving_loading | """Test saving and loading."""
loader = DirectoryLoader('docs/extras/modules/', glob='*.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = FAISS.from_documents(texts, embeddi... | def test_retrieval_qa_with_sources_chain_saving_loading(tmp_path: str) ->None:
"""Test saving and loading."""
loader = DirectoryLoader('docs/extras/modules/', glob='*.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_d... | Test saving and loading. |
test_agent_iterator_reset | """Test reset functionality of AgentExecutorIterator."""
agent = _get_agent()
agent_iter = agent.iter(inputs='when was langchain made')
assert isinstance(agent_iter, AgentExecutorIterator)
iterator = iter(agent_iter)
next(iterator)
assert agent_iter.iterations == 1
assert agent_iter.time_elapsed > 0.0
assert agent_iter... | def test_agent_iterator_reset() ->None:
"""Test reset functionality of AgentExecutorIterator."""
agent = _get_agent()
agent_iter = agent.iter(inputs='when was langchain made')
assert isinstance(agent_iter, AgentExecutorIterator)
iterator = iter(agent_iter)
next(iterator)
assert agent_iter.it... | Test reset functionality of AgentExecutorIterator. |
on_llm_start | """Run when LLM starts."""
self.step += 1
self.llm_starts += 1
self.starts += 1
resp = self._init_resp()
resp.update({'action': 'on_llm_start'})
resp.update(flatten_dict(serialized))
resp.update(self.get_custom_callback_meta())
for prompt in prompts:
prompt_resp = deepcopy(resp)
prompt_resp['prompts'] = prompt
... | def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], **
kwargs: Any) ->None:
"""Run when LLM starts."""
self.step += 1
self.llm_starts += 1
self.starts += 1
resp = self._init_resp()
resp.update({'action': 'on_llm_start'})
resp.update(flatten_dict(serialized))
resp.u... | Run when LLM starts. |
search | issues = self.jira.jql(query)
parsed_issues = self.parse_issues(issues)
parsed_issues_str = 'Found ' + str(len(parsed_issues)) + ' issues:\n' + str(
parsed_issues)
return parsed_issues_str | def search(self, query: str) ->str:
issues = self.jira.jql(query)
parsed_issues = self.parse_issues(issues)
parsed_issues_str = 'Found ' + str(len(parsed_issues)
) + ' issues:\n' + str(parsed_issues)
return parsed_issues_str | null |
__init__ | """Create a new MarkdownHeaderTextSplitter.
Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
strip_headers: Strip split headers from the content of the chunk
"""
self.return_each_line = return_each_line
self... | def __init__(self, headers_to_split_on: List[Tuple[str, str]],
return_each_line: bool=False, strip_headers: bool=True):
"""Create a new MarkdownHeaderTextSplitter.
Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
... | Create a new MarkdownHeaderTextSplitter.
Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
strip_headers: Strip split headers from the content of the chunk |
_fetch_page | try:
return self.wiki_client.page(title=page, auto_suggest=False)
except (self.wiki_client.exceptions.PageError, self.wiki_client.exceptions.
DisambiguationError):
return None | def _fetch_page(self, page: str) ->Optional[str]:
try:
return self.wiki_client.page(title=page, auto_suggest=False)
except (self.wiki_client.exceptions.PageError, self.wiki_client.
exceptions.DisambiguationError):
return None | null |
_evaluate_strings | """Evaluate the prediction string.
Args:
prediction (str): The prediction string to evaluate.
input (str, optional): Not used in this evaluator.
reference (str): The reference string to compare against.
Returns:
dict: A dictionary containing the evaluati... | def _evaluate_strings(self, prediction: str, input: Optional[str]=None,
reference: Optional[str]=None, **kwargs: Any) ->dict:
"""Evaluate the prediction string.
Args:
prediction (str): The prediction string to evaluate.
input (str, optional): Not used in this evaluator.
... | Evaluate the prediction string.
Args:
prediction (str): The prediction string to evaluate.
input (str, optional): Not used in this evaluator.
reference (str): The reference string to compare against.
Returns:
dict: A dictionary containing the evaluation score. |
_default_approximate_search_query | """For Approximate k-NN Search, this is the default query."""
return {'size': k, 'query': {'knn': {vector_field: {'vector': query_vector,
'k': k}}}} | def _default_approximate_search_query(query_vector: List[float], k: int=4,
vector_field: str='vector_field') ->Dict:
"""For Approximate k-NN Search, this is the default query."""
return {'size': k, 'query': {'knn': {vector_field: {'vector':
query_vector, 'k': k}}}} | For Approximate k-NN Search, this is the default query. |
_completion_with_retry | """Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator(llm, max_retries=llm.max_retries,
run_manager=run_manager)
@retry_decorator
def _completion_with_retry(prompt: LanguageModelInput, is_gemini: bool,
stream: bool, **kwargs: Any) ->Any:
generation_config = kwargs.get('g... | def _completion_with_retry(llm: GoogleGenerativeAI, prompt:
LanguageModelInput, is_gemini: bool=False, stream: bool=False,
run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->Any:
"""Use tenacity to retry the completion call."""
retry_decorator = _create_retry_decorator(llm, max_retri... | Use tenacity to retry the completion call. |
test_clarifai_with_metadatas_with_scores | """Test end to end construction and scored search."""
texts = ['oof', 'rab', 'zab']
metadatas = [{'page': str(i)} for i in range(len(texts))]
USER_ID = 'minhajul'
APP_ID = 'test-lang-2'
NUMBER_OF_DOCS = 1
docsearch = Clarifai.from_texts(user_id=USER_ID, app_id=APP_ID, texts=texts,
pat=None, number_of_docs=NUMBER_OF... | def test_clarifai_with_metadatas_with_scores() ->None:
"""Test end to end construction and scored search."""
texts = ['oof', 'rab', 'zab']
metadatas = [{'page': str(i)} for i in range(len(texts))]
USER_ID = 'minhajul'
APP_ID = 'test-lang-2'
NUMBER_OF_DOCS = 1
docsearch = Clarifai.from_texts(... | Test end to end construction and scored search. |
_is_openai_parts_format | return 'type' in part | def _is_openai_parts_format(part: dict) ->bool:
return 'type' in part | null |
__init__ | self.history: List[Dict[str, Union[int, float]]] = [{'step': 0, 'score': 0}]
self.step: int = step
self.i: int = 0
self.window_size: int = window_size
self.queue: deque = deque()
self.sum: float = 0.0 | def __init__(self, window_size: int, step: int):
self.history: List[Dict[str, Union[int, float]]] = [{'step': 0, 'score': 0}
]
self.step: int = step
self.i: int = 0
self.window_size: int = window_size
self.queue: deque = deque()
self.sum: float = 0.0 | null |
_evaluate_strings | """
Evaluate the string distance between the prediction and the reference.
Args:
prediction (str): The prediction string.
reference (Optional[str], optional): The reference string.
input (Optional[str], optional): The input string.
callbacks (Callbacks, o... | def _evaluate_strings(self, *, prediction: str, reference: Optional[str]=
None, input: Optional[str]=None, callbacks: Callbacks=None, tags:
Optional[List[str]]=None, metadata: Optional[Dict[str, Any]]=None,
include_run_info: bool=False, **kwargs: Any) ->dict:
"""
Evaluate the string distance bet... | Evaluate the string distance between the prediction and the reference.
Args:
prediction (str): The prediction string.
reference (Optional[str], optional): The reference string.
input (Optional[str], optional): The input string.
callbacks (Callbacks, optional): The callbacks to use.
**kwargs: Additi... |
__init__ | """Initialize with a file path."""
try:
import fitz
except ImportError:
raise ImportError(
'`PyMuPDF` package not found, please install it with `pip install pymupdf`'
)
super().__init__(file_path, headers=headers)
self.extract_images = extract_images
self.text_kwargs = kwargs | def __init__(self, file_path: str, *, headers: Optional[Dict]=None,
extract_images: bool=False, **kwargs: Any) ->None:
"""Initialize with a file path."""
try:
import fitz
except ImportError:
raise ImportError(
'`PyMuPDF` package not found, please install it with `pip install ... | Initialize with a file path. |
_get_doc_title | try:
return re.findall('^#\\s+(.*)', data, re.MULTILINE)[0]
except IndexError:
pass
try:
return re.findall('^(.*)\\n=+\\n', data, re.MULTILINE)[0]
except IndexError:
return file_name | def _get_doc_title(data: str, file_name: str) ->str:
try:
return re.findall('^#\\s+(.*)', data, re.MULTILINE)[0]
except IndexError:
pass
try:
return re.findall('^(.*)\\n=+\\n', data, re.MULTILINE)[0]
except IndexError:
return file_name | null |
_import_e2b_data_analysis | from langchain_community.tools.e2b_data_analysis.tool import E2BDataAnalysisTool
return E2BDataAnalysisTool | def _import_e2b_data_analysis() ->Any:
from langchain_community.tools.e2b_data_analysis.tool import E2BDataAnalysisTool
return E2BDataAnalysisTool | null |
_generate | if self.streaming:
stream_iter = self._stream(messages, stop=stop, run_manager=run_manager,
**kwargs)
return generate_from_stream(stream_iter)
request = get_cohere_chat_request(messages, **self._default_params, **kwargs)
response = self.client.chat(**request)
message = AIMessage(content=response.text)
g... | def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]=
None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any
) ->ChatResult:
if self.streaming:
stream_iter = self._stream(messages, stop=stop, run_manager=
run_manager, **kwargs)
return gene... | null |
trim_last_node | """Remove the last node if it exists and has a single incoming edge,
ie. if removing it would not leave the graph without a "last" node."""
last_node = self.last_node()
if last_node:
if len(self.nodes) == 1 or len([edge for edge in self.edges if edge.
target == last_node.id]) == 1:
self.remo... | def trim_last_node(self) ->None:
"""Remove the last node if it exists and has a single incoming edge,
ie. if removing it would not leave the graph without a "last" node."""
last_node = self.last_node()
if last_node:
if len(self.nodes) == 1 or len([edge for edge in self.edges if edge
... | Remove the last node if it exists and has a single incoming edge,
ie. if removing it would not leave the graph without a "last" node. |
__init__ | self.embedding = embedding
self.index_name = index_name
self.query_field = query_field
self.vector_query_field = vector_query_field
self.distance_strategy = (DistanceStrategy.COSINE if distance_strategy is
None else DistanceStrategy[distance_strategy])
self.strategy = strategy
if es_connection is not None:
self... | def __init__(self, index_name: str, *, embedding: Optional[Embeddings]=None,
es_connection: Optional['Elasticsearch']=None, es_url: Optional[str]=
None, es_cloud_id: Optional[str]=None, es_user: Optional[str]=None,
es_api_key: Optional[str]=None, es_password: Optional[str]=None,
vector_query_field: str=... | null |
close | """Mock Gradient close."""
return | def close(self) ->None:
"""Mock Gradient close."""
return | Mock Gradient close. |
test_implements_string_evaluator_protocol | assert issubclass(chain_cls, StringEvaluator) | @pytest.mark.parametrize('chain_cls', [QAEvalChain, ContextQAEvalChain,
CotQAEvalChain])
def test_implements_string_evaluator_protocol(chain_cls: Type[LLMChain]
) ->None:
assert issubclass(chain_cls, StringEvaluator) | null |
test_invoke | """Test invoke tokens from ChatMistralAI"""
llm = ChatMistralAI()
result = llm.invoke("I'm Pickle Rick", config=dict(tags=['foo']))
assert isinstance(result.content, str) | def test_invoke() ->None:
"""Test invoke tokens from ChatMistralAI"""
llm = ChatMistralAI()
result = llm.invoke("I'm Pickle Rick", config=dict(tags=['foo']))
assert isinstance(result.content, str) | Test invoke tokens from ChatMistralAI |
run | data = {'extracted_text': [{'body': {'text': 'Hello World'}}],
'file_extracted_data': [{'language': 'en'}], 'field_metadata': [{
'metadata': {'metadata': {'paragraphs': [{'end': 66, 'sentences': [{
'start': 1, 'end': 67}]}]}}}]}
return json.dumps(data) | def run(self: Any, **args: Any) ->str:
data = {'extracted_text': [{'body': {'text': 'Hello World'}}],
'file_extracted_data': [{'language': 'en'}], 'field_metadata': [{
'metadata': {'metadata': {'paragraphs': [{'end': 66, 'sentences': [
{'start': 1, 'end': 67}]}]}}}]}
return json.dumps(da... | null |
on_chain_start | if self.__has_valid_config is False:
return
try:
name = serialized.get('id', [None, None, None, None])[3]
type = 'chain'
metadata = metadata or {}
agentName = metadata.get('agent_name')
if agentName is None:
agentName = metadata.get('agentName')
if name == 'AgentExecutor' or name == ... | def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any],
*, run_id: UUID, parent_run_id: Union[UUID, None]=None, tags: Union[
List[str], None]=None, metadata: Union[Dict[str, Any], None]=None, **
kwargs: Any) ->Any:
if self.__has_valid_config is False:
return
try:
... | null |
test_redis_from_existing | """Test adding a new document"""
docsearch = Redis.from_texts(texts, FakeEmbeddings(), index_name=
TEST_INDEX_NAME, redis_url=TEST_REDIS_URL)
schema: Dict = docsearch.schema
docsearch.write_schema('test_schema.yml')
docsearch2 = Redis.from_existing_index(FakeEmbeddings(), index_name=
TEST_INDEX_NAME, redis_url=... | def test_redis_from_existing(texts: List[str]) ->None:
"""Test adding a new document"""
docsearch = Redis.from_texts(texts, FakeEmbeddings(), index_name=
TEST_INDEX_NAME, redis_url=TEST_REDIS_URL)
schema: Dict = docsearch.schema
docsearch.write_schema('test_schema.yml')
docsearch2 = Redis.fr... | Test adding a new document |
_Module | for stmt in tree.body:
self.dispatch(stmt) | def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt) | null |
__init__ | super().__init__()
if not collection_name:
raise ValueError(
'collection_name must be specified when using ZepVectorStore.')
try:
from zep_python import ZepClient
except ImportError:
raise ImportError(
'Could not import zep-python python package. Please install it with `pip install zep-pytho... | def __init__(self, collection_name: str, api_url: str, *, api_key: Optional
[str]=None, config: Optional[CollectionConfig]=None, embedding:
Optional[Embeddings]=None) ->None:
super().__init__()
if not collection_name:
raise ValueError(
'collection_name must be specified when using Ze... | null |
get_user_agent | from langchain_community import __version__
return f'langchain/{__version__}' | @staticmethod
def get_user_agent() ->str:
from langchain_community import __version__
return f'langchain/{__version__}' | null |
on_chain_error | self.on_chain_error_common() | def on_chain_error(self, *args: Any, **kwargs: Any) ->Any:
self.on_chain_error_common() | null |
similarity_search_by_vector | """Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Filter on metadata properties, e.g.
{
"str_proper... | def similarity_search_by_vector(self, embedding: List[float], k: int=
DEFAULT_TOP_K, filter: Optional[Dict[str, Any]]=None, brute_force: bool
=False, fraction_lists_to_search: Optional[float]=None, **kwargs: Any
) ->List[Document]:
"""Return docs most similar to embedding vector.
Args:
... | Return docs most similar to embedding vector.
Args:
embedding: Embedding to look up documents similar to.
k: Number of Documents to return. Defaults to 4.
filter: Filter on metadata properties, e.g.
{
"str_property": "foo",
"int_property":... |
config_with_context | """Patch a runnable config with context getters and setters.
Args:
config: The runnable config.
steps: The runnable steps.
Returns:
The patched runnable config.
"""
return _config_with_context(config, steps, _setter, _getter, threading.Event) | def config_with_context(config: RunnableConfig, steps: List[Runnable]
) ->RunnableConfig:
"""Patch a runnable config with context getters and setters.
Args:
config: The runnable config.
steps: The runnable steps.
Returns:
The patched runnable config.
"""
return _config_... | Patch a runnable config with context getters and setters.
Args:
config: The runnable config.
steps: The runnable steps.
Returns:
The patched runnable config. |
_Attribute | self.dispatch(t.value)
if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int):
self.write(' ')
self.write('.')
self.write(t.attr) | def _Attribute(self, t):
self.dispatch(t.value)
if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int):
self.write(' ')
self.write('.')
self.write(t.attr) | null |
_import_beam | from langchain_community.llms.beam import Beam
return Beam | def _import_beam() ->Any:
from langchain_community.llms.beam import Beam
return Beam | null |
_restore_template_vars | """Restore template variables replaced with placeholders to original values."""
if isinstance(obj, str):
for placeholder, value in placeholders.items():
obj = obj.replace(placeholder, f'{{{{{value}}}}}')
elif isinstance(obj, dict):
for key, value in obj.items():
obj[key] = self._restore_template... | def _restore_template_vars(self, obj: Any, placeholders: Dict[str, str]) ->Any:
"""Restore template variables replaced with placeholders to original values."""
if isinstance(obj, str):
for placeholder, value in placeholders.items():
obj = obj.replace(placeholder, f'{{{{{value}}}}}')
elif... | Restore template variables replaced with placeholders to original values. |
clear | """Clear memory contents."""
self.chat_memory.clear() | def clear(self) ->None:
"""Clear memory contents."""
self.chat_memory.clear() | Clear memory contents. |
_kwargs_post_fine_tune_request | """Build the kwargs for the Post request, used by sync
Args:
prompt (str): prompt used in query
kwargs (dict): model kwargs in payload
Returns:
Dict[str, Union[str,dict]]: _description_
"""
_model_kwargs = self.model_kwargs or {}
_params = {**_model_kwargs, ... | def _kwargs_post_fine_tune_request(self, inputs: Sequence[str], kwargs:
Mapping[str, Any]) ->Mapping[str, Any]:
"""Build the kwargs for the Post request, used by sync
Args:
prompt (str): prompt used in query
kwargs (dict): model kwargs in payload
Returns:
Di... | Build the kwargs for the Post request, used by sync
Args:
prompt (str): prompt used in query
kwargs (dict): model kwargs in payload
Returns:
Dict[str, Union[str,dict]]: _description_ |
_search | result = self.database.search(index=','.join(indices), body=query)
return str(result) | def _search(self, indices: List[str], query: str) ->str:
result = self.database.search(index=','.join(indices), body=query)
return str(result) | null |
list_keys | """List records in the database based on the provided filters.
Args:
before: Filter to list records updated before this time.
after: Filter to list records updated after this time.
group_ids: Filter to list records with specific group IDs.
limit: optional limit o... | @abstractmethod
def list_keys(self, *, before: Optional[float]=None, after: Optional[float]
=None, group_ids: Optional[Sequence[str]]=None, limit: Optional[int]=None
) ->List[str]:
"""List records in the database based on the provided filters.
Args:
before: Filter to list records update... | List records in the database based on the provided filters.
Args:
before: Filter to list records updated before this time.
after: Filter to list records updated after this time.
group_ids: Filter to list records with specific group IDs.
limit: optional limit on the number of records to return.
Returns... |
on_chain_end | """Run when chain ends running."""
self.step += 1
self.chain_ends += 1
self.ends += 1
resp = self._init_resp()
resp.update({'action': 'on_chain_end', 'outputs': outputs['output']})
resp.update(self.get_custom_callback_meta())
self.on_chain_end_records.append(resp)
self.action_records.append(resp)
if self.stream_logs:
... | def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) ->None:
"""Run when chain ends running."""
self.step += 1
self.chain_ends += 1
self.ends += 1
resp = self._init_resp()
resp.update({'action': 'on_chain_end', 'outputs': outputs['output']})
resp.update(self.get_custom_callback_met... | Run when chain ends running. |
__init__ | """Initialize with Weaviate client."""
try:
import weaviate
except ImportError:
raise ImportError(
'Could not import weaviate python package. Please install it with `pip install weaviate-client`.'
)
if not isinstance(client, weaviate.Client):
raise ValueError(
f'client should be an i... | def __init__(self, client: Any, index_name: str, text_key: str, embedding:
Optional[Embeddings]=None, attributes: Optional[List[str]]=None,
relevance_score_fn: Optional[Callable[[float], float]]=
_default_score_normalizer, by_text: bool=True):
"""Initialize with Weaviate client."""
try:
impo... | Initialize with Weaviate client. |
test_chat_fireworks_multiple_completions | """Test ChatFireworks wrapper with multiple completions."""
chat = ChatFireworks(model_kwargs={'n': 5})
message = HumanMessage(content='Hello')
response = chat._generate([message])
assert isinstance(response, ChatResult)
assert len(response.generations) == 5
for generation in response.generations:
assert isinstance... | @pytest.mark.scheduled
def test_chat_fireworks_multiple_completions() ->None:
"""Test ChatFireworks wrapper with multiple completions."""
chat = ChatFireworks(model_kwargs={'n': 5})
message = HumanMessage(content='Hello')
response = chat._generate([message])
assert isinstance(response, ChatResult)
... | Test ChatFireworks wrapper with multiple completions. |
_litm_reordering | """Lost in the middle reorder: the less relevant documents will be at the
middle of the list and more relevant elements at beginning / end.
See: https://arxiv.org/abs//2307.03172"""
documents.reverse()
reordered_result = []
for i, value in enumerate(documents):
if i % 2 == 1:
reordered_result.append... | def _litm_reordering(documents: List[Document]) ->List[Document]:
"""Lost in the middle reorder: the less relevant documents will be at the
middle of the list and more relevant elements at beginning / end.
See: https://arxiv.org/abs//2307.03172"""
documents.reverse()
reordered_result = []
for i,... | Lost in the middle reorder: the less relevant documents will be at the
middle of the list and more relevant elements at beginning / end.
See: https://arxiv.org/abs//2307.03172 |
_custom_parser | """
The LLM response for `action_input` may be a multiline
string containing unescaped newlines, tabs or quotes. This function
replaces those characters with their escaped counterparts.
(newlines in JSON must be double-escaped: `\\n`)
"""
if isinstance(multiline_string, (bytes, bytearray)):
mult... | def _custom_parser(multiline_string: str) ->str:
"""
The LLM response for `action_input` may be a multiline
string containing unescaped newlines, tabs or quotes. This function
replaces those characters with their escaped counterparts.
(newlines in JSON must be double-escaped: `\\n`)
"""
if i... | The LLM response for `action_input` may be a multiline
string containing unescaped newlines, tabs or quotes. This function
replaces those characters with their escaped counterparts.
(newlines in JSON must be double-escaped: `\n`) |
yield_keys | """Yield keys in the store."""
if prefix:
pattern = self._get_prefixed_key(prefix)
else:
pattern = self._get_prefixed_key('*')
cursor, keys = self.client.scan(0, match=pattern)
for key in keys:
if self.namespace:
relative_key = key[len(self.namespace) + 1:]
yield relative_key
else:
... | def yield_keys(self, *, prefix: Optional[str]=None) ->Iterator[str]:
"""Yield keys in the store."""
if prefix:
pattern = self._get_prefixed_key(prefix)
else:
pattern = self._get_prefixed_key('*')
cursor, keys = self.client.scan(0, match=pattern)
for key in keys:
if self.names... | Yield keys in the store. |
test_opensearch_with_custom_field_name_appx_false | """Test Approximate Search with custom field name appx true."""
text_input = ['add', 'test', 'text', 'method']
docsearch = OpenSearchVectorSearch.from_texts(text_input, FakeEmbeddings(),
opensearch_url=DEFAULT_OPENSEARCH_URL)
output = docsearch.similarity_search('add', k=1)
assert output == [Document(page_content='... | def test_opensearch_with_custom_field_name_appx_false() ->None:
"""Test Approximate Search with custom field name appx true."""
text_input = ['add', 'test', 'text', 'method']
docsearch = OpenSearchVectorSearch.from_texts(text_input,
FakeEmbeddings(), opensearch_url=DEFAULT_OPENSEARCH_URL)
output... | Test Approximate Search with custom field name appx true. |
test_all | """Use to catch obvious breaking changes."""
assert __all__ == sorted(__all__, key=str.lower)
assert __all__ == ['aindex', 'GraphIndexCreator', 'index', 'IndexingResult',
'SQLRecordManager', 'VectorstoreIndexCreator'] | def test_all() ->None:
"""Use to catch obvious breaking changes."""
assert __all__ == sorted(__all__, key=str.lower)
assert __all__ == ['aindex', 'GraphIndexCreator', 'index',
'IndexingResult', 'SQLRecordManager', 'VectorstoreIndexCreator'] | Use to catch obvious breaking changes. |
set_meta | """document and name are reserved arcee keys. Anything else is metadata"""
values['_is_meta'] = values.get('field_name') not in ['document', 'name']
return values | @root_validator()
def set_meta(cls, values: Dict) ->Dict:
"""document and name are reserved arcee keys. Anything else is metadata"""
values['_is_meta'] = values.get('field_name') not in ['document', 'name']
return values | document and name are reserved arcee keys. Anything else is metadata |
test_trace_as_group_with_env_set | from langchain.chains.llm import LLMChain
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(input_variables=['product'], template=
'What is a good name for a company that makes {product}?')
chain = LLMChain(llm=llm, prompt=prompt)
with trace_as_chain_group('my_group_e... | def test_trace_as_group_with_env_set() ->None:
from langchain.chains.llm import LLMChain
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(input_variables=['product'], template=
'What is a good name for a company that makes {product}?')
chain =... | null |
_extract_fields | """Grab the existing fields from the Collection"""
from transwarp_hippo_api.hippo_client import HippoTable
if isinstance(self.col, HippoTable):
schema = self.col.schema
logger.debug(f'[_extract_fields] schema:{schema}')
for x in schema:
self.fields.append(x.name)
logger.debug(f'04 [_extract_fiel... | def _extract_fields(self) ->None:
"""Grab the existing fields from the Collection"""
from transwarp_hippo_api.hippo_client import HippoTable
if isinstance(self.col, HippoTable):
schema = self.col.schema
logger.debug(f'[_extract_fields] schema:{schema}')
for x in schema:
s... | Grab the existing fields from the Collection |
test_ifixit_loader_device | web_path = 'https://www.ifixit.com/Device/Standard_iPad'
loader = IFixitLoader(web_path)
""" Teardowns are just guides by a different name """
assert loader.page_type == 'Device'
assert loader.id == 'Standard_iPad' | def test_ifixit_loader_device() ->None:
web_path = 'https://www.ifixit.com/Device/Standard_iPad'
loader = IFixitLoader(web_path)
""" Teardowns are just guides by a different name """
assert loader.page_type == 'Device'
assert loader.id == 'Standard_iPad' | null |
_import_google_serper_tool_GoogleSerperRun | from langchain_community.tools.google_serper.tool import GoogleSerperRun
return GoogleSerperRun | def _import_google_serper_tool_GoogleSerperRun() ->Any:
from langchain_community.tools.google_serper.tool import GoogleSerperRun
return GoogleSerperRun | null |
_import_file_management_DeleteFileTool | from langchain_community.tools.file_management import DeleteFileTool
return DeleteFileTool | def _import_file_management_DeleteFileTool() ->Any:
from langchain_community.tools.file_management import DeleteFileTool
return DeleteFileTool | null |
_display_aggregate_results | if _is_jupyter_environment():
from IPython.display import HTML, display
display(HTML('<h3>Experiment Results:</h3>'))
display(aggregate_results)
else:
formatted_string = aggregate_results.to_string(float_format=lambda x:
f'{x:.2f}', justify='right')
print('\n Experiment Results:')
print(... | def _display_aggregate_results(aggregate_results: pd.DataFrame) ->None:
if _is_jupyter_environment():
from IPython.display import HTML, display
display(HTML('<h3>Experiment Results:</h3>'))
display(aggregate_results)
else:
formatted_string = aggregate_results.to_string(float_form... | null |
test_visit_comparison | comparator, value, expected = triplet
actual = DEFAULT_TRANSLATOR.visit_comparison(Comparison(comparator=
comparator, attribute='foo', value=value))
assert expected == actual | @pytest.mark.parametrize('triplet', [(Comparator.EQ, 2, 'foo = 2'), (
Comparator.LT, 2, 'foo < 2'), (Comparator.LTE, 2, 'foo <= 2'), (
Comparator.GT, 2, 'foo > 2'), (Comparator.GTE, 2, 'foo >= 2'), (
Comparator.LIKE, 'bar', "foo LIKE '%bar%'")])
def test_visit_comparison(triplet: Tuple[Comparator, Any, str]... | null |
_run | """Use the tool."""
query_params = {'text': query, 'language': self.language}
return self._call_eden_ai(query_params) | def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun]
=None) ->str:
"""Use the tool."""
query_params = {'text': query, 'language': self.language}
return self._call_eden_ai(query_params) | Use the tool. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.