method_name stringlengths 1 78 | method_body stringlengths 3 9.66k | full_code stringlengths 31 10.7k | docstring stringlengths 4 4.74k ⌀ |
|---|---|---|---|
_llm_type | """Return type of llm."""
return 'oci_model_deployment_vllm_endpoint' | @property
def _llm_type(self) ->str:
"""Return type of llm."""
return 'oci_model_deployment_vllm_endpoint' | Return type of llm. |
_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 |
test__split_list_works_correctly | """Test splitting works correctly."""
docs = [Document(page_content='foo'), Document(page_content='bar'),
Document(page_content='baz'), Document(page_content='foo' * 2),
Document(page_content='bar'), Document(page_content='baz')]
doc_list = split_list_of_docs(docs, _fake_docs_len_func, 10)
expected_result = [[D... | def test__split_list_works_correctly() ->None:
"""Test splitting works correctly."""
docs = [Document(page_content='foo'), Document(page_content='bar'),
Document(page_content='baz'), Document(page_content='foo' * 2),
Document(page_content='bar'), Document(page_content='baz')]
doc_list = spli... | Test splitting works correctly. |
_import_steamship_image_generation | from langchain_community.tools.steamship_image_generation import SteamshipImageGenerationTool
return SteamshipImageGenerationTool | def _import_steamship_image_generation() ->Any:
from langchain_community.tools.steamship_image_generation import SteamshipImageGenerationTool
return SteamshipImageGenerationTool | null |
__init__ | try:
from playwright.sync_api import sync_playwright
except ImportError:
raise ImportError(
'Could not import playwright python package. Please install it with `pip install playwright`.'
)
self.browser: Browser = sync_playwright().start().chromium.launch(headless=
False)
self.page: Page = se... | def __init__(self) ->None:
try:
from playwright.sync_api import sync_playwright
except ImportError:
raise ImportError(
'Could not import playwright python package. Please install it with `pip install playwright`.'
)
self.browser: Browser = sync_playwright().start().ch... | null |
_format_prompt_with_error_handling | if not isinstance(inner_input, dict):
raise TypeError(
f'Expected mapping type as input to {self.__class__.__name__}. Received {type(inner_input)}.'
)
missing = set(self.input_variables).difference(inner_input)
if missing:
raise KeyError(
f'Input to {self.__class__.__name__} is missing v... | def _format_prompt_with_error_handling(self, inner_input: Dict) ->PromptValue:
if not isinstance(inner_input, dict):
raise TypeError(
f'Expected mapping type as input to {self.__class__.__name__}. Received {type(inner_input)}.'
)
missing = set(self.input_variables).difference(inn... | null |
_filter_results | output = []
types = self.json_result_types if self.json_result_types is not None else []
for task in res.get('tasks', []):
for result in task.get('result', []):
for item in result.get('items', []):
if len(types) == 0 or item.get('type', '') in types:
self._cleanup_unnecessary_ite... | def _filter_results(self, res: dict) ->list:
output = []
types = self.json_result_types if self.json_result_types is not None else [
]
for task in res.get('tasks', []):
for result in task.get('result', []):
for item in result.get('items', []):
if len(types) == 0 o... | null |
_get_labels | """Get node and edge labels from the Neptune statistics summary"""
summary = self._get_summary()
n_labels = summary['nodeLabels']
e_labels = summary['edgeLabels']
return n_labels, e_labels | def _get_labels(self) ->Tuple[List[str], List[str]]:
"""Get node and edge labels from the Neptune statistics summary"""
summary = self._get_summary()
n_labels = summary['nodeLabels']
e_labels = summary['edgeLabels']
return n_labels, e_labels | Get node and edge labels from the Neptune statistics summary |
create_collection | """Creates the corresponding collection in SemaDB."""
payload = {'id': self.collection_name, 'vectorSize': self.vector_size,
'distanceMetric': self._get_internal_distance_strategy()}
response = requests.post(SemaDB.BASE_URL + '/collections', json=payload,
headers=self.headers)
return response.status_code == 200 | def create_collection(self) ->bool:
"""Creates the corresponding collection in SemaDB."""
payload = {'id': self.collection_name, 'vectorSize': self.vector_size,
'distanceMetric': self._get_internal_distance_strategy()}
response = requests.post(SemaDB.BASE_URL + '/collections', json=payload,
... | Creates the corresponding collection in SemaDB. |
embeddings | return self._embed_fn | @property
def embeddings(self) ->Embeddings:
return self._embed_fn | null |
_client_params | """Get the parameters used for the client."""
return self._default_params | @property
def _client_params(self) ->Dict[str, Any]:
"""Get the parameters used for the client."""
return self._default_params | Get the parameters used for the client. |
_on_chat_model_start | """Process the Chat Model Run upon start.""" | def _on_chat_model_start(self, run: Run) ->None:
"""Process the Chat Model Run upon start.""" | Process the Chat Model Run upon start. |
is_lc_serializable | """Return whether this model can be serialized by Langchain."""
return True | @classmethod
def is_lc_serializable(cls) ->bool:
"""Return whether this model can be serialized by Langchain."""
return True | Return whether this model can be serialized by Langchain. |
_create_chat_result | generations = []
for res in response['choices']:
message = _convert_dict_to_message(res['message'])
gen = ChatGeneration(message=message, generation_info=dict(
finish_reason=res.get('finish_reason')))
generations.append(gen)
token_usage = response.get('usage', {})
set_model_value = self.model
if sel... | def _create_chat_result(self, response: Mapping[str, Any]) ->ChatResult:
generations = []
for res in response['choices']:
message = _convert_dict_to_message(res['message'])
gen = ChatGeneration(message=message, generation_info=dict(
finish_reason=res.get('finish_reason')))
ge... | null |
set_cluster_driver_port | if v and values['endpoint_name']:
raise ValueError('Cannot set both endpoint_name and cluster_driver_port.')
elif values['endpoint_name']:
return None
elif v is None:
raise ValueError(
'Must set cluster_driver_port to connect to a cluster driver.')
elif int(v) <= 0:
raise ValueError(f'Invalid cl... | @validator('cluster_driver_port', always=True)
def set_cluster_driver_port(cls, v: Any, values: Dict[str, Any]) ->Optional[str
]:
if v and values['endpoint_name']:
raise ValueError(
'Cannot set both endpoint_name and cluster_driver_port.')
elif values['endpoint_name']:
return Non... | null |
serve | """
Starts a demo app for this template.
"""
project_dir = get_package_root()
pyproject = project_dir / 'pyproject.toml'
get_langserve_export(pyproject)
host_str = host if host is not None else '127.0.0.1'
script = ('langchain_cli.dev_scripts:create_demo_server' if not
configurable else
'langchain_cli.d... | @package_cli.command()
def serve(*, port: Annotated[Optional[int], typer.Option(help=
'The port to run the server on')]=None, host: Annotated[Optional[str],
typer.Option(help='The host to run the server on')]=None, configurable:
Annotated[bool, typer.Option('--configurable/--no-configurable', help=
'Whe... | Starts a demo app for this template. |
__init__ | self.wandb = wandb_module
self.trace_tree = trace_module | def __init__(self, wandb_module: Any, trace_module: Any):
self.wandb = wandb_module
self.trace_tree = trace_module | null |
test_elasticsearch_embedding_documents | """Test Elasticsearch embedding documents."""
documents = ['foo bar', 'bar foo', 'foo']
embedding = ElasticsearchEmbeddings.from_credentials(model_id)
output = embedding.embed_documents(documents)
assert len(output) == 3
assert len(output[0]) == 768
assert len(output[1]) == 768
assert len(output[2]) == 768 | def test_elasticsearch_embedding_documents(model_id: str) ->None:
"""Test Elasticsearch embedding documents."""
documents = ['foo bar', 'bar foo', 'foo']
embedding = ElasticsearchEmbeddings.from_credentials(model_id)
output = embedding.embed_documents(documents)
assert len(output) == 3
assert le... | Test Elasticsearch embedding documents. |
flatten | """Flatten generations into a single list.
Unpack List[List[Generation]] -> List[LLMResult] where each returned LLMResult
contains only a single Generation. If token usage information is available,
it is kept only for the LLMResult corresponding to the top-choice
Generation,... | def flatten(self) ->List[LLMResult]:
"""Flatten generations into a single list.
Unpack List[List[Generation]] -> List[LLMResult] where each returned LLMResult
contains only a single Generation. If token usage information is available,
it is kept only for the LLMResult corresponding ... | Flatten generations into a single list.
Unpack List[List[Generation]] -> List[LLMResult] where each returned LLMResult
contains only a single Generation. If token usage information is available,
it is kept only for the LLMResult corresponding to the top-choice
Generation, to avoid over-counting of token us... |
resolve_criteria | """Resolve the criteria for the pairwise evaluator.
Args:
criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
Returns:
dict: The resolved criteria.
"""
if criteria is None:
_default_criteria = [Criteria.HELPFULNESS, Criteria.RELEVANCE, Criteria
.CORRECTNESS, C... | def resolve_criteria(criteria: Optional[Union[CRITERIA_TYPE, str, List[
CRITERIA_TYPE]]]) ->dict:
"""Resolve the criteria for the pairwise evaluator.
Args:
criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
Returns:
dict: The resolved criteria.
"""
if criteri... | Resolve the criteria for the pairwise evaluator.
Args:
criteria (Union[CRITERIA_TYPE, str], optional): The criteria to use.
Returns:
dict: The resolved criteria. |
test_opensearch_script_scoring | """Test end to end indexing and search using Script Scoring Search."""
pre_filter_val = {'bool': {'filter': {'term': {'text': 'bar'}}}}
docsearch = OpenSearchVectorSearch.from_texts(texts, FakeEmbeddings(),
opensearch_url=DEFAULT_OPENSEARCH_URL, is_appx_search=False)
output = docsearch.similarity_search('foo', k=1,... | def test_opensearch_script_scoring() ->None:
"""Test end to end indexing and search using Script Scoring Search."""
pre_filter_val = {'bool': {'filter': {'term': {'text': 'bar'}}}}
docsearch = OpenSearchVectorSearch.from_texts(texts, FakeEmbeddings(),
opensearch_url=DEFAULT_OPENSEARCH_URL, is_appx_s... | Test end to end indexing and search using Script Scoring Search. |
delete_collection | """Deletes the corresponding collection in SemaDB."""
response = requests.delete(SemaDB.BASE_URL +
f'/collections/{self.collection_name}', headers=self.headers)
return response.status_code == 200 | def delete_collection(self) ->bool:
"""Deletes the corresponding collection in SemaDB."""
response = requests.delete(SemaDB.BASE_URL +
f'/collections/{self.collection_name}', headers=self.headers)
return response.status_code == 200 | Deletes the corresponding collection in SemaDB. |
_import_playwright_ClickTool | from langchain_community.tools.playwright import ClickTool
return ClickTool | def _import_playwright_ClickTool() ->Any:
from langchain_community.tools.playwright import ClickTool
return ClickTool | null |
stream | yield from self.transform(iter([input]), config, **kwargs) | def stream(self, input: Input, config: Optional[RunnableConfig]=None, **
kwargs: Optional[Any]) ->Iterator[Output]:
yield from self.transform(iter([input]), config, **kwargs) | null |
test_huggingface_text_generation | """Test valid call to HuggingFace text generation model."""
llm = HuggingFaceHub(repo_id='gpt2', model_kwargs={'max_new_tokens': 10})
output = llm('Say foo:')
assert isinstance(output, str) | def test_huggingface_text_generation() ->None:
"""Test valid call to HuggingFace text generation model."""
llm = HuggingFaceHub(repo_id='gpt2', model_kwargs={'max_new_tokens': 10})
output = llm('Say foo:')
assert isinstance(output, str) | Test valid call to HuggingFace text generation model. |
test_semantic_search | """Test on semantic similarity."""
docs = store.similarity_search('food', k=4)
print(docs)
kinds = [d.metadata['kind'] for d in docs]
assert 'fruit' in kinds
assert 'treat' in kinds
assert 'planet' not in kinds | def test_semantic_search(self, store: BigQueryVectorSearch) ->None:
"""Test on semantic similarity."""
docs = store.similarity_search('food', k=4)
print(docs)
kinds = [d.metadata['kind'] for d in docs]
assert 'fruit' in kinds
assert 'treat' in kinds
assert 'planet' not in kinds | Test on semantic similarity. |
__init__ | """
Set up the RDFlib graph
:param source_file: either a path for a local file or a URL
:param serialization: serialization of the input
:param query_endpoint: SPARQL endpoint for queries, read access
:param update_endpoint: SPARQL endpoint for UPDATE queries, write access
... | def __init__(self, source_file: Optional[str]=None, serialization: Optional
[str]='ttl', query_endpoint: Optional[str]=None, update_endpoint:
Optional[str]=None, standard: Optional[str]='rdf', local_copy: Optional
[str]=None) ->None:
"""
Set up the RDFlib graph
:param source_file: eithe... | Set up the RDFlib graph
:param source_file: either a path for a local file or a URL
:param serialization: serialization of the input
:param query_endpoint: SPARQL endpoint for queries, read access
:param update_endpoint: SPARQL endpoint for UPDATE queries, write access
:param standard: RDF, RDFS, or OWL
:param local_c... |
__init__ | super().__init__(**kwargs)
self._validate_uri()
try:
from mlflow.deployments import get_deploy_client
self._client = get_deploy_client(self.target_uri)
except ImportError as e:
raise ImportError(
f'Failed to create the client. Please run `pip install mlflow{self._mlflow_extras}` to install required ... | def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
self._validate_uri()
try:
from mlflow.deployments import get_deploy_client
self._client = get_deploy_client(self.target_uri)
except ImportError as e:
raise ImportError(
f'Failed to create the client. Please... | null |
search | """Return the fake document."""
document = Document(page_content=_PAGE_CONTENT)
return document | def search(self, search: str) ->Union[str, Document]:
"""Return the fake document."""
document = Document(page_content=_PAGE_CONTENT)
return document | Return the fake document. |
test_json_schema_evaluator_requires_reference | assert json_schema_evaluator.requires_reference is True | @pytest.mark.requires('jsonschema')
def test_json_schema_evaluator_requires_reference(json_schema_evaluator:
JsonSchemaEvaluator) ->None:
assert json_schema_evaluator.requires_reference is True | null |
_import_google_finance | from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
return GoogleFinanceAPIWrapper | def _import_google_finance() ->Any:
from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
return GoogleFinanceAPIWrapper | null |
__init__ | """Initialize the PubMedLoader.
Args:
query: The query to be passed to the PubMed API.
load_max_docs: The maximum number of documents to load.
Defaults to 3.
"""
self.query = query
self.load_max_docs = load_max_docs
self._client = PubMedAPIWrapper(top_k_results=loa... | def __init__(self, query: str, load_max_docs: Optional[int]=3):
"""Initialize the PubMedLoader.
Args:
query: The query to be passed to the PubMed API.
load_max_docs: The maximum number of documents to load.
Defaults to 3.
"""
self.query = query
self.loa... | Initialize the PubMedLoader.
Args:
query: The query to be passed to the PubMed API.
load_max_docs: The maximum number of documents to load.
Defaults to 3. |
test_pandas_output_parser_row_col_1 | expected_output = {'1': 2}
actual_output = parser.parse_folder('row:1[chicken]')
assert actual_output == expected_output | def test_pandas_output_parser_row_col_1() ->None:
expected_output = {'1': 2}
actual_output = parser.parse_folder('row:1[chicken]')
assert actual_output == expected_output | null |
split_list_of_docs | """Split Documents into subsets that each meet a cumulative length constraint.
Args:
docs: The full list of Documents.
length_func: Function for computing the cumulative length of a set of Documents.
token_max: The maximum cumulative length of any subset of Documents.
**kwargs: Arbi... | def split_list_of_docs(docs: List[Document], length_func: Callable,
token_max: int, **kwargs: Any) ->List[List[Document]]:
"""Split Documents into subsets that each meet a cumulative length constraint.
Args:
docs: The full list of Documents.
length_func: Function for computing the cumulativ... | Split Documents into subsets that each meet a cumulative length constraint.
Args:
docs: The full list of Documents.
length_func: Function for computing the cumulative length of a set of Documents.
token_max: The maximum cumulative length of any subset of Documents.
**kwargs: Arbitrary additional keywor... |
from_params | """Instantiate retriever from params.
Args:
url (str): Vespa app URL.
content_field (str): Field in results to return as Document page_content.
k (Optional[int]): Number of Documents to return. Defaults to None.
metadata_fields(Sequence[str] or "*"): Fields in re... | @classmethod
def from_params(cls, url: str, content_field: str, *, k: Optional[int]=None,
metadata_fields: Union[Sequence[str], Literal['*']]=(), sources: Union[
Sequence[str], Literal['*'], None]=None, _filter: Optional[str]=None,
yql: Optional[str]=None, **kwargs: Any) ->VespaRetriever:
"""Instantiate... | Instantiate retriever from params.
Args:
url (str): Vespa app URL.
content_field (str): Field in results to return as Document page_content.
k (Optional[int]): Number of Documents to return. Defaults to None.
metadata_fields(Sequence[str] or "*"): Fields in results to include in
document metada... |
is_lc_serializable | return True | @classmethod
def is_lc_serializable(cls) ->bool:
return True | null |
__init__ | """Initialize the embedder.
Args:
underlying_embeddings: the embedder to use for computing embeddings.
document_embedding_store: The store to use for caching document embeddings.
"""
super().__init__()
self.document_embedding_store = document_embedding_store
self.underlying_embe... | def __init__(self, underlying_embeddings: Embeddings,
document_embedding_store: BaseStore[str, List[float]]) ->None:
"""Initialize the embedder.
Args:
underlying_embeddings: the embedder to use for computing embeddings.
document_embedding_store: The store to use for caching docu... | Initialize the embedder.
Args:
underlying_embeddings: the embedder to use for computing embeddings.
document_embedding_store: The store to use for caching document embeddings. |
_import_neo4j_vector | from langchain_community.vectorstores.neo4j_vector import Neo4jVector
return Neo4jVector | def _import_neo4j_vector() ->Any:
from langchain_community.vectorstores.neo4j_vector import Neo4jVector
return Neo4jVector | null |
output_keys | """Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
return _output_keys | @property
def output_keys(self) ->List[str]:
"""Return the output keys.
:meta private:
"""
_output_keys = [self.output_key]
return _output_keys | Return the output keys.
:meta private: |
evaluate | """Synchronously process the page and return the resulting text.
Args:
page: The page to process.
browser: The browser instance.
response: The response from page.goto().
Returns:
text: The text content of the page.
"""
pass | @abstractmethod
def evaluate(self, page: 'Page', browser: 'Browser', response: 'Response'
) ->str:
"""Synchronously process the page and return the resulting text.
Args:
page: The page to process.
browser: The browser instance.
response: The response from page.goto()... | Synchronously process the page and return the resulting text.
Args:
page: The page to process.
browser: The browser instance.
response: The response from page.goto().
Returns:
text: The text content of the page. |
test__split_list_long_single_doc | """Test splitting of a long single doc."""
docs = [Document(page_content='foo' * 100)]
with pytest.raises(ValueError):
split_list_of_docs(docs, _fake_docs_len_func, 100) | def test__split_list_long_single_doc() ->None:
"""Test splitting of a long single doc."""
docs = [Document(page_content='foo' * 100)]
with pytest.raises(ValueError):
split_list_of_docs(docs, _fake_docs_len_func, 100) | Test splitting of a long single doc. |
test_create_external_handler | """If we're using a Streamlit that *does* expose its own callback handler,
delegate to that implementation.
"""
mock_streamlit_module = MagicMock()
def external_import_success(name: str, globals: Any, locals: Any, fromlist:
Any, level: int) ->Any:
if name == 'streamlit.external.langchain':
... | def test_create_external_handler(self) ->None:
"""If we're using a Streamlit that *does* expose its own callback handler,
delegate to that implementation.
"""
mock_streamlit_module = MagicMock()
def external_import_success(name: str, globals: Any, locals: Any,
fromlist: Any, level: ... | If we're using a Streamlit that *does* expose its own callback handler,
delegate to that implementation. |
__init__ | try:
from upstash_redis import Redis
except ImportError:
raise ImportError(
'Could not import upstash redis python package. Please install it with `pip install upstash_redis`.'
)
if url == '' or token == '':
raise ValueError(
'UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN are n... | def __init__(self, session_id: str, url: str='', token: str='', key_prefix:
str='message_store:', ttl: Optional[int]=None):
try:
from upstash_redis import Redis
except ImportError:
raise ImportError(
'Could not import upstash redis python package. Please install it with `pip inst... | null |
test_extract_images_text_from_pdf | """Test extract image from pdf and recognize text with rapid ocr"""
_assert_with_parser(PyPDFParser(extract_images=True))
_assert_with_parser(PDFMinerParser(extract_images=True))
_assert_with_parser(PyMuPDFParser(extract_images=True))
_assert_with_parser(PyPDFium2Parser(extract_images=True)) | @pytest.mark.requires('rapidocr_onnxruntime')
def test_extract_images_text_from_pdf() ->None:
"""Test extract image from pdf and recognize text with rapid ocr"""
_assert_with_parser(PyPDFParser(extract_images=True))
_assert_with_parser(PDFMinerParser(extract_images=True))
_assert_with_parser(PyMuPDFPars... | Test extract image from pdf and recognize text with rapid ocr |
is_lc_serializable | return True | @classmethod
def is_lc_serializable(cls) ->bool:
return True | null |
test_load_success | """Test that returns the correct answer"""
output = tfds_client.load()
assert isinstance(output, list)
assert len(output) == MAX_DOCS
assert isinstance(output[0], Document)
assert len(output[0].page_content) > 0
assert isinstance(output[0].page_content, str)
assert isinstance(output[0].metadata, dict) | def test_load_success(tfds_client: TensorflowDatasets) ->None:
"""Test that returns the correct answer"""
output = tfds_client.load()
assert isinstance(output, list)
assert len(output) == MAX_DOCS
assert isinstance(output[0], Document)
assert len(output[0].page_content) > 0
assert isinstance... | Test that returns the correct answer |
get_indexes | """Helper to see your available indexes in marqo, useful if the
from_texts method was used without an index name specified
Returns:
List[Dict[str, str]]: The list of indexes
"""
return self._client.get_indexes()['results'] | def get_indexes(self) ->List[Dict[str, str]]:
"""Helper to see your available indexes in marqo, useful if the
from_texts method was used without an index name specified
Returns:
List[Dict[str, str]]: The list of indexes
"""
return self._client.get_indexes()['results'] | Helper to see your available indexes in marqo, useful if the
from_texts method was used without an index name specified
Returns:
List[Dict[str, str]]: The list of indexes |
get_input_schema | return _seq_input_schema(self.steps, config) | def get_input_schema(self, config: Optional[RunnableConfig]=None) ->Type[
BaseModel]:
return _seq_input_schema(self.steps, config) | null |
test_annoy_search_not_found | """Test what happens when document is not found."""
texts = ['foo', 'bar', 'baz']
docsearch = Annoy.from_texts(texts, FakeEmbeddings())
docsearch.docstore = InMemoryDocstore({})
with pytest.raises(ValueError):
docsearch.similarity_search('foo') | def test_annoy_search_not_found() ->None:
"""Test what happens when document is not found."""
texts = ['foo', 'bar', 'baz']
docsearch = Annoy.from_texts(texts, FakeEmbeddings())
docsearch.docstore = InMemoryDocstore({})
with pytest.raises(ValueError):
docsearch.similarity_search('foo') | Test what happens when document is not found. |
test_visit_structured_query | query = 'What is the capital of France?'
structured_query = StructuredQuery(query=query, filter=None, limit=None)
expected: Tuple[str, Dict] = (query, {})
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
assert expected == actual | def test_visit_structured_query() ->None:
query = 'What is the capital of France?'
structured_query = StructuredQuery(query=query, filter=None, limit=None)
expected: Tuple[str, Dict] = (query, {})
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
assert expected == actual | null |
_run | try:
from amadeus import ResponseError
except ImportError as e:
raise ImportError(
'Unable to import amadeus, please install with `pip install amadeus`.'
) from e
RESULTS_PER_PAGE = 10
client = self.client
earliestDeparture = dt.strptime(departureDateTimeEarliest, '%Y-%m-%dT%H:%M:%S')
latestDepa... | def _run(self, originLocationCode: str, destinationLocationCode: str,
departureDateTimeEarliest: str, departureDateTimeLatest: str,
page_number: int=1, run_manager: Optional[CallbackManagerForToolRun]=None
) ->list:
try:
from amadeus import ResponseError
except ImportError as e:
rais... | null |
resize_base64_image | """
Resize an image encoded as a Base64 string
:param base64_string: Base64 string
:param size: Image size
:return: Re-sized Base64 string
"""
img_data = base64.b64decode(base64_string)
img = Image.open(io.BytesIO(img_data))
resized_img = img.resize(size, Image.LANCZOS)
buffered = io.BytesIO()
resi... | def resize_base64_image(base64_string, size=(128, 128)):
"""
Resize an image encoded as a Base64 string
:param base64_string: Base64 string
:param size: Image size
:return: Re-sized Base64 string
"""
img_data = base64.b64decode(base64_string)
img = Image.open(io.BytesIO(img_data))
r... | Resize an image encoded as a Base64 string
:param base64_string: Base64 string
:param size: Image size
:return: Re-sized Base64 string |
_identifying_params | return {**{'endpoint': self.endpoint, 'model': self.model}, **super().
_identifying_params} | @property
def _identifying_params(self) ->Dict[str, Any]:
return {**{'endpoint': self.endpoint, 'model': self.model}, **super().
_identifying_params} | null |
_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} | @property
def _identifying_params(self) ->Mapping[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} | Get the identifying parameters. |
get_or_create | """
Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created.
"""
created = False
collection = cls.get_by_name(session, name)
if collection:
return collection, created
collection = cls(name=name, cmetadata=cmetadata)
session.add(collection)
... | @classmethod
def get_or_create(cls, session: Session, name: str, cmetadata: Optional[
dict]=None) ->Tuple['CollectionStore', bool]:
"""
Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created.
"""
created = False
collection = cl... | Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created. |
validate_environment | """Validate that the required Python package exists."""
try:
from stackapi import StackAPI
values['client'] = StackAPI('stackoverflow')
except ImportError:
raise ImportError(
"The 'stackapi' Python package is not installed. Please install it with `pip install stackapi`."
)
return values | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that the required Python package exists."""
try:
from stackapi import StackAPI
values['client'] = StackAPI('stackoverflow')
except ImportError:
raise ImportError(
"The 'stackapi' Python pack... | Validate that the required Python package exists. |
_load_blocks | """Read a block and its children."""
result_lines_arr: List[str] = []
cur_block_id: str = block_id
while cur_block_id:
data = self._request(BLOCK_URL.format(block_id=cur_block_id))
for result in data['results']:
result_obj = result[result['type']]
if 'rich_text' not in result_obj:
co... | def _load_blocks(self, block_id: str, num_tabs: int=0) ->str:
"""Read a block and its children."""
result_lines_arr: List[str] = []
cur_block_id: str = block_id
while cur_block_id:
data = self._request(BLOCK_URL.format(block_id=cur_block_id))
for result in data['results']:
re... | Read a block and its children. |
_prepare_draft_message | draft_message = EmailMessage()
draft_message.set_content(message)
draft_message['To'] = ', '.join(to)
draft_message['Subject'] = subject
if cc is not None:
draft_message['Cc'] = ', '.join(cc)
if bcc is not None:
draft_message['Bcc'] = ', '.join(bcc)
encoded_message = base64.urlsafe_b64encode(draft_message.as_by... | def _prepare_draft_message(self, message: str, to: List[str], subject: str,
cc: Optional[List[str]]=None, bcc: Optional[List[str]]=None) ->dict:
draft_message = EmailMessage()
draft_message.set_content(message)
draft_message['To'] = ', '.join(to)
draft_message['Subject'] = subject
if cc is not N... | null |
get_prompt | """Get default prompt for a language model.
Args:
llm: Language model to get prompt for.
Returns:
Prompt to use for the language model.
"""
for condition, prompt in self.conditionals:
if condition(llm):
return prompt
return self.default_prompt | def get_prompt(self, llm: BaseLanguageModel) ->BasePromptTemplate:
"""Get default prompt for a language model.
Args:
llm: Language model to get prompt for.
Returns:
Prompt to use for the language model.
"""
for condition, prompt in self.conditionals:
if ... | Get default prompt for a language model.
Args:
llm: Language model to get prompt for.
Returns:
Prompt to use for the language model. |
handle_endtag | """Hook when a tag is closed."""
self.depth -= 1
top_of_stack = dict(self.stack.pop(-1))
is_leaf = self.data is not None
value = self.data if is_leaf else top_of_stack
self.stack[-1][tag].append(value)
self.data = None | def handle_endtag(self, tag: str) ->None:
"""Hook when a tag is closed."""
self.depth -= 1
top_of_stack = dict(self.stack.pop(-1))
is_leaf = self.data is not None
value = self.data if is_leaf else top_of_stack
self.stack[-1][tag].append(value)
self.data = None | Hook when a tag is closed. |
similarity_search_by_vector | """Perform a similarity search with MyScale by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): where condition string.
Defaults to Non... | def similarity_search_by_vector(self, embedding: List[float], k: int=4,
where_str: Optional[str]=None, **kwargs: Any) ->List[Document]:
"""Perform a similarity search with MyScale by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults... | Perform a similarity search with MyScale by vectors
Args:
query (str): query string
k (int, optional): Top K neighbors to retrieve. Defaults to 4.
where_str (Optional[str], optional): where condition string.
Defaults to None.
NOTE: Please do not let end-user to... |
add_resource | """
Add a resource to the resources list.
Args:
resource (str): The resource to be added.
"""
self.resources.append(resource) | def add_resource(self, resource: str) ->None:
"""
Add a resource to the resources list.
Args:
resource (str): The resource to be added.
"""
self.resources.append(resource) | Add a resource to the resources list.
Args:
resource (str): The resource to be added. |
_import_huggingface_text_gen_inference | from langchain_community.llms.huggingface_text_gen_inference import HuggingFaceTextGenInference
return HuggingFaceTextGenInference | def _import_huggingface_text_gen_inference() ->Any:
from langchain_community.llms.huggingface_text_gen_inference import HuggingFaceTextGenInference
return HuggingFaceTextGenInference | null |
test_ignore_images | html2text_transformer = Html2TextTransformer(ignore_images=False)
multiple_tags_html = (
"<h1>First heading.</h1><p>First paragraph with an <img src='example.jpg' alt='Example image' width='500' height='600'></p>"
)
documents = [Document(page_content=multiple_tags_html)]
docs_transformed = html2text_transformer... | @pytest.mark.requires('html2text')
def test_ignore_images() ->None:
html2text_transformer = Html2TextTransformer(ignore_images=False)
multiple_tags_html = (
"<h1>First heading.</h1><p>First paragraph with an <img src='example.jpg' alt='Example image' width='500' height='600'></p>"
)
document... | null |
_identifying_params | """Get the identifying parameters."""
return self._default_params | @property
def _identifying_params(self) ->Mapping[str, Any]:
"""Get the identifying parameters."""
return self._default_params | Get the identifying parameters. |
custom_document_builder | return Document(page_content='Mock content!', metadata={'page_number': -1,
'original_filename': 'Mock filename!'}) | def custom_document_builder(_: Dict) ->Document:
return Document(page_content='Mock content!', metadata={'page_number':
-1, 'original_filename': 'Mock filename!'}) | null |
test_raise_error_if_path_is_not_directory | loader = DirectoryLoader(__file__)
with pytest.raises(ValueError) as e:
loader.load()
assert str(e.value) == f"Expected directory, got file: '{__file__}'" | def test_raise_error_if_path_is_not_directory() ->None:
loader = DirectoryLoader(__file__)
with pytest.raises(ValueError) as e:
loader.load()
assert str(e.value) == f"Expected directory, got file: '{__file__}'" | null |
from_retrievers | if default_prompt and not default_retriever:
raise ValueError(
'`default_retriever` must be specified if `default_prompt` is provided. Received only `default_prompt`.'
)
destinations = [f"{r['name']}: {r['description']}" for r in retriever_infos]
destinations_str = '\n'.join(destinations)
router_tem... | @classmethod
def from_retrievers(cls, llm: BaseLanguageModel, retriever_infos: List[Dict
[str, Any]], default_retriever: Optional[BaseRetriever]=None,
default_prompt: Optional[PromptTemplate]=None, default_chain: Optional[
Chain]=None, **kwargs: Any) ->MultiRetrievalQAChain:
if default_prompt and not de... | null |
finish_run | """To finish the run."""
with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id=self.
mlf_expid):
self.mlflow.end_run() | def finish_run(self) ->None:
"""To finish the run."""
with self.mlflow.start_run(run_id=self.run.info.run_id, experiment_id=
self.mlf_expid):
self.mlflow.end_run() | To finish the run. |
validate_environment | """Validate that api key is in your environment variable."""
gplaces_api_key = get_from_dict_or_env(values, 'gplaces_api_key',
'GPLACES_API_KEY')
values['gplaces_api_key'] = gplaces_api_key
try:
import googlemaps
values['google_map_client'] = googlemaps.Client(gplaces_api_key)
except ImportError:
raise ... | @root_validator()
def validate_environment(cls, values: Dict) ->Dict:
"""Validate that api key is in your environment variable."""
gplaces_api_key = get_from_dict_or_env(values, 'gplaces_api_key',
'GPLACES_API_KEY')
values['gplaces_api_key'] = gplaces_api_key
try:
import googlemaps
... | Validate that api key is in your environment variable. |
validate_prompt_input_variables | """Validate that prompt input variables are consistent."""
memory_keys = values['memory'].memory_variables
input_key = values['input_key']
if input_key in memory_keys:
raise ValueError(
f"The input key {input_key} was also found in the memory keys ({memory_keys}) - please provide keys that don't overlap."
... | @root_validator()
def validate_prompt_input_variables(cls, values: Dict) ->Dict:
"""Validate that prompt input variables are consistent."""
memory_keys = values['memory'].memory_variables
input_key = values['input_key']
if input_key in memory_keys:
raise ValueError(
f"The input key {... | Validate that prompt input variables are consistent. |
_format_func | self._validate_func(func)
if isinstance(func, Operator):
value = self.OPERATOR_MAP[func.value]
elif isinstance(func, Comparator):
value = self.COMPARATOR_MAP[func.value]
return f'{value}' | def _format_func(self, func: Union[Operator, Comparator]) ->str:
self._validate_func(func)
if isinstance(func, Operator):
value = self.OPERATOR_MAP[func.value]
elif isinstance(func, Comparator):
value = self.COMPARATOR_MAP[func.value]
return f'{value}' | null |
test_load_returns_limited_doc_content_chars | """Test that returns limited doc_content_chars_max"""
doc_content_chars_max = 100
api_client = ArxivAPIWrapper(doc_content_chars_max=doc_content_chars_max)
docs = api_client.load('1605.08386')
assert len(docs[0].page_content) == doc_content_chars_max | def test_load_returns_limited_doc_content_chars() ->None:
"""Test that returns limited doc_content_chars_max"""
doc_content_chars_max = 100
api_client = ArxivAPIWrapper(doc_content_chars_max=doc_content_chars_max)
docs = api_client.load('1605.08386')
assert len(docs[0].page_content) == doc_content_c... | Test that returns limited doc_content_chars_max |
_legacy_stream | prompt = self._format_messages_as_text(messages)
for stream_resp in self._create_generate_stream(prompt, stop, **kwargs):
if stream_resp:
chunk = _stream_response_to_chat_generation_chunk(stream_resp)
yield chunk
if run_manager:
run_manager.on_llm_new_token(chunk.text, verbose=se... | @deprecated('0.0.3', alternative='_stream')
def _legacy_stream(self, messages: List[BaseMessage], stop: Optional[List[
str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **
kwargs: Any) ->Iterator[ChatGenerationChunk]:
prompt = self._format_messages_as_text(messages)
for stream_resp in se... | null |
__init__ | """Initialize the OBSDirectoryLoader with the specified settings.
Args:
bucket (str): The name of the OBS bucket to be used.
endpoint (str): The endpoint URL of your OBS bucket.
config (dict): The parameters for connecting to OBS, provided as a dictionary. The dictionary cou... | def __init__(self, bucket: str, endpoint: str, config: Optional[dict]=None,
prefix: str=''):
"""Initialize the OBSDirectoryLoader with the specified settings.
Args:
bucket (str): The name of the OBS bucket to be used.
endpoint (str): The endpoint URL of your OBS bucket.
... | Initialize the OBSDirectoryLoader with the specified settings.
Args:
bucket (str): The name of the OBS bucket to be used.
endpoint (str): The endpoint URL of your OBS bucket.
config (dict): The parameters for connecting to OBS, provided as a dictionary. The dictionary could have the following keys:
... |
list_packages | conn = http.client.HTTPSConnection('api.github.com')
headers = {'Accept': 'application/vnd.github+json', 'X-GitHub-Api-Version':
'2022-11-28', 'User-Agent': 'langchain-cli'}
conn.request('GET', '/repos/langchain-ai/langchain/contents/templates',
headers=headers)
res = conn.getresponse()
res_str = res.read()
dat... | def list_packages(*, contains: Optional[str]=None):
conn = http.client.HTTPSConnection('api.github.com')
headers = {'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'langchain-cli'}
conn.request('GET', '/repos/langchain-ai/langchain/contents/templates',
... | null |
similarity_search_with_score_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_with_score_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[Tuple[Document, float]]:
"""Return docs most similar to embedding 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_property": "foo",
"int_property":... |
clear | """Nothing to clear, got a memory like a vault."""
pass | def clear(self) ->None:
"""Nothing to clear, got a memory like a vault."""
pass | Nothing to clear, got a memory like a vault. |
test_finish_custom | """Test custom finish."""
parser = SelfAskOutputParser(finish_string='Finally: ')
_input = 'Finally: 4'
output = parser.invoke(_input)
expected_output = AgentFinish(return_values={'output': '4'}, log=_input)
assert output == expected_output | def test_finish_custom() ->None:
"""Test custom finish."""
parser = SelfAskOutputParser(finish_string='Finally: ')
_input = 'Finally: 4'
output = parser.invoke(_input)
expected_output = AgentFinish(return_values={'output': '4'}, log=_input)
assert output == expected_output | Test custom finish. |
input_iter | for token in STREAMED_TOKENS:
yield token | def input_iter(_: Any) ->Iterator[str]:
for token in STREAMED_TOKENS:
yield token | null |
__init__ | """Initialize with a web path."""
if not web_path.startswith('https://www.ifixit.com'):
raise ValueError("web path must start with 'https://www.ifixit.com'")
path = web_path.replace('https://www.ifixit.com', '')
allowed_paths = ['/Device', '/Guide', '/Answers', '/Teardown']
""" TODO: Add /Wiki """
if not any(path.s... | def __init__(self, web_path: str):
"""Initialize with a web path."""
if not web_path.startswith('https://www.ifixit.com'):
raise ValueError("web path must start with 'https://www.ifixit.com'")
path = web_path.replace('https://www.ifixit.com', '')
allowed_paths = ['/Device', '/Guide', '/Answers',... | Initialize with a web path. |
test_cassandra_add_extra | """Test end to end construction with further insertions."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i} for i in range(len(texts))]
docsearch = _vectorstore_from_texts(texts, metadatas=metadatas)
texts2 = ['foo2', 'bar2', 'baz2']
metadatas2 = [{'page': i + 3} for i in range(len(texts))]
docsearch.add_texts(t... | def test_cassandra_add_extra() ->None:
"""Test end to end construction with further insertions."""
texts = ['foo', 'bar', 'baz']
metadatas = [{'page': i} for i in range(len(texts))]
docsearch = _vectorstore_from_texts(texts, metadatas=metadatas)
texts2 = ['foo2', 'bar2', 'baz2']
metadatas2 = [{'... | Test end to end construction with further insertions. |
f | args_: map[str] = map(str, args)
return f' {op_name} '.join(args_) | def f(*args: Any) ->str:
args_: map[str] = map(str, args)
return f' {op_name} '.join(args_) | null |
EmbedAndKeep | return Embed(anything, keep=True) | def EmbedAndKeep(anything: Any) ->Any:
return Embed(anything, keep=True) | null |
test_llm_on_chat_dataset | llm = OpenAI(temperature=0)
eval_config = RunEvalConfig(evaluators=[EvaluatorType.QA, EvaluatorType.
CRITERIA])
run_on_dataset(dataset_name=chat_dataset_name, llm_or_chain_factory=llm,
client=client, evaluation=eval_config, project_name=eval_project_name,
tags=['shouldpass'])
_check_all_feedback_passed(eval... | def test_llm_on_chat_dataset(chat_dataset_name: str, eval_project_name: str,
client: Client) ->None:
llm = OpenAI(temperature=0)
eval_config = RunEvalConfig(evaluators=[EvaluatorType.QA, EvaluatorType
.CRITERIA])
run_on_dataset(dataset_name=chat_dataset_name, llm_or_chain_factory=llm,
cl... | null |
load | """Load from a file path."""
return [doc for doc in self.lazy_load()] | def load(self) ->List[Document]:
"""Load from a file path."""
return [doc for doc in self.lazy_load()] | Load from a file path. |
_call | """First try to lookup in queries, else return 'foo' or 'bar'."""
response = self.responses[self.i]
if self.i < len(self.responses) - 1:
self.i += 1
else:
self.i = 0
return response | def _call(self, messages: List[BaseMessage], stop: Optional[List[str]]=None,
run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any) ->str:
"""First try to lookup in queries, else return 'foo' or 'bar'."""
response = self.responses[self.i]
if self.i < len(self.responses) - 1:
self.i... | First try to lookup in queries, else return 'foo' or 'bar'. |
_search_api_results | request_details = self._prepare_request(query, **kwargs)
response = requests.get(url=request_details['url'], params=request_details[
'params'], headers=request_details['headers'])
response.raise_for_status()
return response.json() | def _search_api_results(self, query: str, **kwargs: Any) ->dict:
request_details = self._prepare_request(query, **kwargs)
response = requests.get(url=request_details['url'], params=
request_details['params'], headers=request_details['headers'])
response.raise_for_status()
return response.json() | null |
_default_score_normalizer | return 1 - 1 / (1 + np.exp(val)) | def _default_score_normalizer(val: float) ->float:
return 1 - 1 / (1 + np.exp(val)) | null |
build_extra | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = get_pydantic_field_names(cls)
extra = values.get('model_kwargs', {})
for field_name in list(values):
if field_name in extra:
raise ValueError(f'Found {field_name} supplied twice.')
if field_name not in all_re... | @root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) ->Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = get_pydantic_field_names(cls)
extra = values.get('model_kwargs', {})
for field_name in list(values):
if field_n... | Build extra kwargs from additional params that were passed in. |
__init__ | """Initialize the sentence_transformer."""
super().__init__(**kwargs)
try:
from InstructorEmbedding import INSTRUCTOR
self.client = INSTRUCTOR(self.model_name, cache_folder=self.
cache_folder, **self.model_kwargs)
except ImportError as e:
raise ImportError('Dependencies for InstructorEmbedding not f... | def __init__(self, **kwargs: Any):
"""Initialize the sentence_transformer."""
super().__init__(**kwargs)
try:
from InstructorEmbedding import INSTRUCTOR
self.client = INSTRUCTOR(self.model_name, cache_folder=self.
cache_folder, **self.model_kwargs)
except ImportError as e:
... | Initialize the sentence_transformer. |
select_examples | """Select which examples to use based on semantic similarity."""
if self.input_keys:
input_variables = {key: input_variables[key] for key in self.input_keys}
vectorstore_kwargs = self.vectorstore_kwargs or {}
query = ' '.join(sorted_values(input_variables))
example_docs = self.vectorstore.similarity_search(query, k... | def select_examples(self, input_variables: Dict[str, str]) ->List[dict]:
"""Select which examples to use based on semantic similarity."""
if self.input_keys:
input_variables = {key: input_variables[key] for key in self.input_keys
}
vectorstore_kwargs = self.vectorstore_kwargs or {}
q... | Select which examples to use based on semantic similarity. |
retrieve_existing_fts_index | """
Check if the fulltext index exists in the Neo4j database
This method queries the Neo4j database for existing fts indexes
with the specified name.
Returns:
(Tuple): keyword index information
"""
index_information = self.query(
"SHOW INDEXES YIELD name, type, ... | def retrieve_existing_fts_index(self, text_node_properties: List[str]=[]
) ->Optional[str]:
"""
Check if the fulltext index exists in the Neo4j database
This method queries the Neo4j database for existing fts indexes
with the specified name.
Returns:
(Tuple): keywor... | Check if the fulltext index exists in the Neo4j database
This method queries the Neo4j database for existing fts indexes
with the specified name.
Returns:
(Tuple): keyword index information |
with_listeners | """
Bind lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Called before the runnable starts running, with the Run object.
on_end: Called after the runnable finishes running, with the Run object.
on_error: Called if the runnable throws an error, with the Run object.... | def with_listeners(self, *, on_start: Optional[Listener]=None, on_end:
Optional[Listener]=None, on_error: Optional[Listener]=None) ->RunnableEach[
Input, Output]:
"""
Bind lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Called before the runnable starts running, with ... | Bind lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Called before the runnable starts running, with the Run object.
on_end: Called after the runnable finishes running, with the Run object.
on_error: Called if the runnable throws an error, with the Run object.
The Run object contains informatio... |
_select_relevance_score_fn | """
The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
- embedding dimensionality
- etc.
"""
i... | def _select_relevance_score_fn(self) ->Callable[[float], float]:
"""
The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are ... | The 'correct' relevance function
may differ depending on a few things, including:
- the distance / similarity metric used by the VectorStore
- the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
- embedding dimensionality
- etc. |
test_openai_streaming | """Test streaming tokens from OpenAI."""
llm = OpenAI(max_tokens=10)
generator = llm.stream("I'm Pickle Rick")
assert isinstance(generator, Generator)
for token in generator:
assert isinstance(token, str) | @pytest.mark.scheduled
def test_openai_streaming() ->None:
"""Test streaming tokens from OpenAI."""
llm = OpenAI(max_tokens=10)
generator = llm.stream("I'm Pickle Rick")
assert isinstance(generator, Generator)
for token in generator:
assert isinstance(token, str) | Test streaming tokens from OpenAI. |
test_forefrontai_api_key_masked_when_passed_from_env | """Test that the API key is masked when passed from an environment variable."""
monkeypatch.setenv('FOREFRONTAI_API_KEY', 'secret-api-key')
llm = ForefrontAI(temperature=0.2)
print(llm.forefrontai_api_key, end='')
captured = capsys.readouterr()
assert captured.out == '**********' | def test_forefrontai_api_key_masked_when_passed_from_env(monkeypatch:
MonkeyPatch, capsys: CaptureFixture) ->None:
"""Test that the API key is masked when passed from an environment variable."""
monkeypatch.setenv('FOREFRONTAI_API_KEY', 'secret-api-key')
llm = ForefrontAI(temperature=0.2)
print(llm.... | Test that the API key is masked when passed from an environment variable. |
__init__ | try:
from motor.motor_asyncio import AsyncIOMotorClient
except ImportError as e:
raise ImportError(
'Cannot import from motor, please install with `pip install motor`.'
) from e
if not connection_string:
raise ValueError('connection_string must be provided.')
if not db_name:
raise ValueE... | def __init__(self, connection_string: str, db_name: str, collection_name:
str, *, filter_criteria: Optional[Dict]=None) ->None:
try:
from motor.motor_asyncio import AsyncIOMotorClient
except ImportError as e:
raise ImportError(
'Cannot import from motor, please install with `pip ... | null |
save | df = self.pd.DataFrame(data)
table = self.pa.Table.from_pandas(df)
if os.path.exists(self.persist_path):
backup_path = str(self.persist_path) + '-backup'
os.rename(self.persist_path, backup_path)
try:
self.pq.write_table(table, self.persist_path)
except Exception as exc:
os.rename(backup... | def save(self, data: Any) ->None:
df = self.pd.DataFrame(data)
table = self.pa.Table.from_pandas(df)
if os.path.exists(self.persist_path):
backup_path = str(self.persist_path) + '-backup'
os.rename(self.persist_path, backup_path)
try:
self.pq.write_table(table, self.persi... | null |
add_texts | """Upload texts with metadata (properties) to Marqo.
You can either have marqo generate ids for each document or you can provide
your own by including a "_id" field in the metadata objects.
Args:
texts (Iterable[str]): am iterator of texts - assumed to preserve an
order... | def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]=
None, **kwargs: Any) ->List[str]:
"""Upload texts with metadata (properties) to Marqo.
You can either have marqo generate ids for each document or you can provide
your own by including a "_id" field in the metadata objec... | Upload texts with metadata (properties) to Marqo.
You can either have marqo generate ids for each document or you can provide
your own by including a "_id" field in the metadata objects.
Args:
texts (Iterable[str]): am iterator of texts - assumed to preserve an
order that matches the metadatas.
metadatas ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.