method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
test_messages_to_prompt_dict_raises_with_mismatched_examples
pytest.importorskip('google.generativeai') with pytest.raises(ChatGooglePalmError) as e: _messages_to_prompt_dict([HumanMessage(example=True, content= 'Human example #1'), AIMessage(example=False, content='AI example #1')] ) assert 'Human example message must be immediately followed' in str(e)
def test_messages_to_prompt_dict_raises_with_mismatched_examples() ->None: pytest.importorskip('google.generativeai') with pytest.raises(ChatGooglePalmError) as e: _messages_to_prompt_dict([HumanMessage(example=True, content= 'Human example #1'), AIMessage(example=False, content= ...
null
_insert_texts
if not texts: return [] embeddings = self._embedding.embed_documents(texts) to_insert = [{self._text_key: t, self._embedding_key: embedding, **m} for t, m, embedding in zip(texts, metadatas, embeddings)] insert_result = self._collection.insert_many(to_insert) return insert_result.inserted_ids
def _insert_texts(self, texts: List[str], metadatas: List[Dict[str, Any]] ) ->List: if not texts: return [] embeddings = self._embedding.embed_documents(texts) to_insert = [{self._text_key: t, self._embedding_key: embedding, **m} for t, m, embedding in zip(texts, metadatas, embeddings)] ...
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 ids...
def add_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]]= None, ids: Optional[List[str]]=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:...
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.
get_format_instructions
return XML_FORMAT_INSTRUCTIONS.format(tags=self.tags)
def get_format_instructions(self) ->str: return XML_FORMAT_INSTRUCTIONS.format(tags=self.tags)
null
load
text = '' for line in open(self.file_path, 'r'): data = json.loads(line)['_airbyte_data'] text += stringify_dict(data) metadata = {'source': self.file_path} return [Document(page_content=text, metadata=metadata)]
def load(self) ->List[Document]: text = '' for line in open(self.file_path, 'r'): data = json.loads(line)['_airbyte_data'] text += stringify_dict(data) metadata = {'source': self.file_path} return [Document(page_content=text, metadata=metadata)]
null
prepare_cosmos
"""Prepare the CosmosDB client. Use this function or the context manager to make sure your database is ready. """ try: from azure.cosmos import PartitionKey except ImportError as exc: raise ImportError( 'You must install the azure-cosmos package to use the CosmosDBChatMessageHistory.Ple...
def prepare_cosmos(self) ->None: """Prepare the CosmosDB client. Use this function or the context manager to make sure your database is ready. """ try: from azure.cosmos import PartitionKey except ImportError as exc: raise ImportError( 'You must install the azure...
Prepare the CosmosDB client. Use this function or the context manager to make sure your database is ready.
_call
return self.transform_cb(inputs)
def _call(self, inputs: Dict[str, str], run_manager: Optional[ CallbackManagerForChainRun]=None) ->Dict[str, str]: return self.transform_cb(inputs)
null
test_clear_messages
sql_history, other_history = sql_histories sql_history.add_user_message('Hello!') sql_history.add_ai_message('Hi there!') assert len(sql_history.messages) == 2 other_history.add_user_message('Hellox') assert len(other_history.messages) == 1 assert len(sql_history.messages) == 2 sql_history.clear() assert len(sql_histor...
def test_clear_messages(sql_histories: Tuple[SQLChatMessageHistory, SQLChatMessageHistory]) ->None: sql_history, other_history = sql_histories sql_history.add_user_message('Hello!') sql_history.add_ai_message('Hi there!') assert len(sql_history.messages) == 2 other_history.add_user_message('Hell...
null
from_llm
"""Load and use LLMChain with either a specific prompt key or custom prompt.""" if custom_prompt is not None: prompt = custom_prompt elif prompt_key is not None and prompt_key in PROMPT_MAP: prompt = PROMPT_MAP[prompt_key] else: raise ValueError( f'Must specify prompt_key if custom_prompt not provid...
@classmethod def from_llm(cls, llm: BaseLanguageModel, base_embeddings: Embeddings, prompt_key: Optional[str]=None, custom_prompt: Optional[ BasePromptTemplate]=None, **kwargs: Any) ->HypotheticalDocumentEmbedder: """Load and use LLMChain with either a specific prompt key or custom prompt.""" if custom_...
Load and use LLMChain with either a specific prompt key or custom prompt.
from_components
""" Create a structured query output parser from components. Args: allowed_comparators: allowed comparators allowed_operators: allowed operators Returns: a structured query output parser """ ast_parse: Callable if fix_invalid: def ast_parse(raw_...
@classmethod def from_components(cls, allowed_comparators: Optional[Sequence[Comparator] ]=None, allowed_operators: Optional[Sequence[Operator]]=None, allowed_attributes: Optional[Sequence[str]]=None, fix_invalid: bool=False ) ->StructuredQueryOutputParser: """ Create a structured query output p...
Create a structured query output parser from components. Args: allowed_comparators: allowed comparators allowed_operators: allowed operators Returns: a structured query output parser
f
"""Return 2.""" return 2
def f(x: int) ->int: """Return 2.""" return 2
Return 2.
test_correct_get_tracer_project
cases = [self.SetProperTracerProjectTestCase(test_name= "default to 'default' when no project provided", envvars={}, expected_project_name='default'), self.SetProperTracerProjectTestCase( test_name='use session_name for legacy tracers', envvars={ 'LANGCHAIN_SESSION': 'old_timey_session'}, expected_proje...
def test_correct_get_tracer_project(self) ->None: cases = [self.SetProperTracerProjectTestCase(test_name= "default to 'default' when no project provided", envvars={}, expected_project_name='default'), self. SetProperTracerProjectTestCase(test_name= 'use session_name for legacy tracer...
null
raise_deprecation
warnings.warn( '`VectorDBQAWithSourcesChain` is deprecated - please use `from langchain.chains import RetrievalQAWithSourcesChain`' ) return values
@root_validator() def raise_deprecation(cls, values: Dict) ->Dict: warnings.warn( '`VectorDBQAWithSourcesChain` is deprecated - please use `from langchain.chains import RetrievalQAWithSourcesChain`' ) return values
null
input_keys
"""Expect input key. :meta private: """ return [self.input_key]
@property def input_keys(self) ->List[str]: """Expect input key. :meta private: """ return [self.input_key]
Expect input key. :meta private:
embeddings
return None
@property def embeddings(self) ->Optional[Embeddings]: return None
null
line
"""Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (s...
def line(self, x0: int, y0: int, x1: int, y1: int, char: str) ->None: """Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. ...
Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (str): character to draw the line with.
get_num_tokens
"""Count approximate number of tokens""" return round(len(text) / 4.6)
def get_num_tokens(self, text: str) ->int: """Count approximate number of tokens""" return round(len(text) / 4.6)
Count approximate number of tokens
func
return call_func_with_variable_args(self.func, input, config, run_manager. get_sync(), **kwargs)
def func(input: Input, run_manager: AsyncCallbackManagerForChainRun, config: RunnableConfig) ->Output: return call_func_with_variable_args(self.func, input, config, run_manager.get_sync(), **kwargs)
null
transform_documents
"""Translate text documents using Google Translate. Arguments: source_language_code: ISO 639 language code of the input document. target_language_code: ISO 639 language code of the output document. For supported languages, refer to: https://cloud.google.c...
def transform_documents(self, documents: Sequence[Document], **kwargs: Any ) ->Sequence[Document]: """Translate text documents using Google Translate. Arguments: source_language_code: ISO 639 language code of the input document. target_language_code: ISO 639 language code of the...
Translate text documents using Google Translate. Arguments: source_language_code: ISO 639 language code of the input document. target_language_code: ISO 639 language code of the output document. For supported languages, refer to: https://cloud.google.com/translate/docs/languages mime_type: ...
_load_few_shot_prompt
"""Load the "few shot" prompt from the config.""" config = _load_template('suffix', config) config = _load_template('prefix', config) if 'example_prompt_path' in config: if 'example_prompt' in config: raise ValueError( 'Only one of example_prompt and example_prompt_path should be specified.' ...
def _load_few_shot_prompt(config: dict) ->FewShotPromptTemplate: """Load the "few shot" prompt from the config.""" config = _load_template('suffix', config) config = _load_template('prefix', config) if 'example_prompt_path' in config: if 'example_prompt' in config: raise ValueError( ...
Load the "few shot" prompt from the config.
filter_complex_metadata
"""Filter out metadata types that are not supported for a vector store.""" updated_documents = [] for document in documents: filtered_metadata = {} for key, value in document.metadata.items(): if not isinstance(value, allowed_types): continue filtered_metadata[key] = value docume...
def filter_complex_metadata(documents: List[Document], *, allowed_types: Tuple[Type, ...]=(str, bool, int, float)) ->List[Document]: """Filter out metadata types that are not supported for a vector store.""" updated_documents = [] for document in documents: filtered_metadata = {} for key...
Filter out metadata types that are not supported for a vector store.
get_cassandra_connection
contact_points = [cp.strip() for cp in os.environ.get( 'CASSANDRA_CONTACT_POINTS', '').split(',') if cp.strip()] CASSANDRA_KEYSPACE = os.environ['CASSANDRA_KEYSPACE'] CASSANDRA_USERNAME = os.environ.get('CASSANDRA_USERNAME') CASSANDRA_PASSWORD = os.environ.get('CASSANDRA_PASSWORD') if CASSANDRA_USERNAME and CASSAND...
def get_cassandra_connection(): contact_points = [cp.strip() for cp in os.environ.get( 'CASSANDRA_CONTACT_POINTS', '').split(',') if cp.strip()] CASSANDRA_KEYSPACE = os.environ['CASSANDRA_KEYSPACE'] CASSANDRA_USERNAME = os.environ.get('CASSANDRA_USERNAME') CASSANDRA_PASSWORD = os.environ.get('CA...
null
test_loads_llmchain
llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello') prompt = PromptTemplate.from_template('hello {name}!') chain = LLMChain(llm=llm, prompt=prompt) chain_string = dumps(chain) chain2 = loads(chain_string, secrets_map={'OPENAI_API_KEY': 'hello'}) assert chain2 == chain assert dumps(chain2) == chain_st...
@pytest.mark.requires('openai') def test_loads_llmchain() ->None: llm = OpenAI(model='davinci', temperature=0.5, openai_api_key='hello') prompt = PromptTemplate.from_template('hello {name}!') chain = LLMChain(llm=llm, prompt=prompt) chain_string = dumps(chain) chain2 = loads(chain_string, secrets_ma...
null
__init__
""" Args: collection: MongoDB collection to add the texts to. embedding: Text embedding model to use. text_key: MongoDB field that will contain the text for each document. embedding_key: MongoDB field that will contain the embedding for ...
def __init__(self, collection: Collection[MongoDBDocumentType], embedding: Embeddings, *, index_name: str='default', text_key: str='text', embedding_key: str='embedding', relevance_score_fn: str='cosine'): """ Args: collection: MongoDB collection to add the texts to. embeddin...
Args: collection: MongoDB collection to add the texts to. embedding: Text embedding model to use. text_key: MongoDB field that will contain the text for each document. embedding_key: MongoDB field that will contain the embedding for each document. index_name: Name of the Atlas Search...
format_docs
return '\n\n'.join(f"""Wikipedia {i + 1}: {doc.page_content}""" for i, doc in enumerate(docs))
def format_docs(docs): return '\n\n'.join(f'Wikipedia {i + 1}:\n{doc.page_content}' for i, doc in enumerate(docs))
null
memory_variables
"""Will always return list of memory variables. :meta private: """ return [self.memory_key]
@property def memory_variables(self) ->List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key]
Will always return list of memory variables. :meta private:
_prep_texts
"""Embed and create the documents""" _ids = ids or (str(uuid.uuid4()) for _ in texts) _metadatas: Iterable[dict] = metadatas or ({} for _ in texts) embedded_texts = self._embedding.embed_documents(list(texts)) return [{'id': _id, 'vec': vec, f'{self._text_key}': text, 'metadata': metadata} for _id, vec, text, metad...
def _prep_texts(self, texts: Iterable[str], metadatas: Optional[List[dict]], ids: Optional[List[str]]) ->List[dict]: """Embed and create the documents""" _ids = ids or (str(uuid.uuid4()) for _ in texts) _metadatas: Iterable[dict] = metadatas or ({} for _ in texts) embedded_texts = self._embedding.em...
Embed and create the documents
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.
_detect_pii
analyzer_results = analyzer.analyze(text=inputs['text'], language='en') return bool(analyzer_results)
def _detect_pii(inputs: dict) ->bool: analyzer_results = analyzer.analyze(text=inputs['text'], language='en') return bool(analyzer_results)
null
test_confluence_pagination
loader = ConfluenceLoader(url='https://templates.atlassian.net/wiki/') docs = loader.load(space_key='RD', limit=3, max_pages=5) assert len(docs) == 5 assert docs[0].page_content is not None
@pytest.mark.skipif(not confluence_installed, reason= 'Atlassian package not installed') def test_confluence_pagination() ->None: loader = ConfluenceLoader(url='https://templates.atlassian.net/wiki/') docs = loader.load(space_key='RD', limit=3, max_pages=5) assert len(docs) == 5 assert docs[0].page_...
null
handle_starttag
"""Hook when a new tag is encountered.""" self.depth += 1 self.stack.append(defaultdict(list)) self.data = None
def handle_starttag(self, tag: str, attrs: Any) ->None: """Hook when a new tag is encountered.""" self.depth += 1 self.stack.append(defaultdict(list)) self.data = None
Hook when a new tag is encountered.
test_simple_action_strlist_w_some_emb
str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str2 = base.stringify_embedding(list(encoded_keyword + str2)) encoded_str3 = base.stringify_embedding(list(encoded_keyword + str3)) expected = [{'a_namespace': str1}, {'a_namespace': encoded_str2}, { 'a_namespace': encoded_str3}] assert base.embed([str1, base.Emb...
@pytest.mark.requires('vowpal_wabbit_next') def test_simple_action_strlist_w_some_emb() ->None: str1 = 'test1' str2 = 'test2' str3 = 'test3' encoded_str2 = base.stringify_embedding(list(encoded_keyword + str2)) encoded_str3 = base.stringify_embedding(list(encoded_keyword + str3)) expected = [{'a...
null
transform_output
return response.json()[0]['generated_text']
@classmethod def transform_output(cls, response: Any) ->str: return response.json()[0]['generated_text']
null
__init__
self.connection_string = connection_string self.embedding_function = embedding_function self.collection_name = collection_name self.collection_metadata = collection_metadata self._distance_strategy = distance_strategy self.pre_delete_collection = pre_delete_collection self.logger = logger or logging.getLogger(__name__)...
def __init__(self, connection_string: str, embedding_function: Embeddings, collection_name: str=_LANGCHAIN_DEFAULT_COLLECTION_NAME, collection_metadata: Optional[dict]=None, distance_strategy: DistanceStrategy=DEFAULT_DISTANCE_STRATEGY, pre_delete_collection: bool =False, logger: Optional[logging.Logger...
null
__init__
"""Initialize with a path.""" self.file_path = path
def __init__(self, path: str): """Initialize with a path.""" self.file_path = path
Initialize with a path.
__init__
""" Initialize the IMessageChatLoader. Args: path (str or Path, optional): Path to the chat.db SQLite file. Defaults to None, in which case the default path ~/Library/Messages/chat.db will be used. """ if path is None: path = Path.home() / 'Librar...
def __init__(self, path: Optional[Union[str, Path]]=None): """ Initialize the IMessageChatLoader. Args: path (str or Path, optional): Path to the chat.db SQLite file. Defaults to None, in which case the default path ~/Library/Messages/chat.db will be used...
Initialize the IMessageChatLoader. Args: path (str or Path, optional): Path to the chat.db SQLite file. Defaults to None, in which case the default path ~/Library/Messages/chat.db will be used.
load
"""Load from a list of image data or file paths""" try: from transformers import BlipForConditionalGeneration, BlipProcessor except ImportError: raise ImportError( '`transformers` package not found, please install with `pip install transformers`.' ) processor = BlipProcessor.from_pretrained(self...
def load(self) ->List[Document]: """Load from a list of image data or file paths""" try: from transformers import BlipForConditionalGeneration, BlipProcessor except ImportError: raise ImportError( '`transformers` package not found, please install with `pip install transformers`.'...
Load from a list of image data or file paths
create_structured_chat_agent
"""Create an agent aimed at supporting tools with multiple inputs. Examples: .. code-block:: python from langchain import hub from langchain_community.chat_models import ChatOpenAI from langchain.agents import AgentExecutor, create_structured_chat_agent p...
def create_structured_chat_agent(llm: BaseLanguageModel, tools: Sequence[ BaseTool], prompt: ChatPromptTemplate) ->Runnable: """Create an agent aimed at supporting tools with multiple inputs. Examples: .. code-block:: python from langchain import hub from langchain_commun...
Create an agent aimed at supporting tools with multiple inputs. Examples: .. code-block:: python from langchain import hub from langchain_community.chat_models import ChatOpenAI from langchain.agents import AgentExecutor, create_structured_chat_agent prompt = hub.pull("hwchase17...
_create_retry_decorator
min_seconds = 4 max_seconds = 10 max_retries = llm.max_retries if llm.max_retries is not None else 3 return retry(reraise=True, stop=stop_after_attempt(max_retries), wait= wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry =retry_if_exception_type((RequestException, ConnectTimeout, ReadTime...
def _create_retry_decorator(llm: Nebula) ->Callable[[Any], Any]: min_seconds = 4 max_seconds = 10 max_retries = llm.max_retries if llm.max_retries is not None else 3 return retry(reraise=True, stop=stop_after_attempt(max_retries), wait= wait_exponential(multiplier=1, min=min_seconds, max=max_sec...
null
test_from_texts
vs = zep_vectorstore.from_texts(**texts_metadatas, collection_name= mock_collection_config.name, api_url='http://localhost:8000') vs._collection.add_documents.assert_called_once_with( texts_metadatas_as_zep_documents)
@pytest.mark.requires('zep_python') def test_from_texts(zep_vectorstore: ZepVectorStore, mock_collection_config: CollectionConfig, mock_collection: 'DocumentCollection', texts_metadatas: Dict[str, Any], texts_metadatas_as_zep_documents: List ['ZepDocument']) ->None: vs = zep_vectorstore.from_texts(**tex...
null
test_logging
logger = logging.getLogger('test_logging') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) handler = LoggingCallbackHandler(logger, extra={'test': 'test_extra'}) handler.on_text('test', run_id=uuid.uuid4()) assert len(caplog.record_tuples) == 1 record = caplog.records[0] assert record...
def test_logging(caplog: pytest.LogCaptureFixture, capsys: pytest. CaptureFixture[str]) ->None: logger = logging.getLogger('test_logging') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) handler = LoggingCallbackHandler(logger, extra={'test': 'test_extra'}) han...
null
fn
return 'fake_uuid'
def fn(self: Any, **kwargs: Any) ->str: return 'fake_uuid'
null
_num_thought_containers
"""The number of 'thought containers' we're currently showing: the number of completed thought containers, the history container (if it exists), and the current thought container (if it exists). """ count = len(self._completed_thoughts) if self._history_container is not None: count += 1 if s...
@property def _num_thought_containers(self) ->int: """The number of 'thought containers' we're currently showing: the number of completed thought containers, the history container (if it exists), and the current thought container (if it exists). """ count = len(self._completed_thoughts) ...
The number of 'thought containers' we're currently showing: the number of completed thought containers, the history container (if it exists), and the current thought container (if it exists).
test_load_success_multiple_arxiv_identifiers
"""Test a query of arxiv identifiers that returns the correct answer""" docs = api_client.load('1605.08386v1 2212.00794v2 2308.07912') assert len(docs) == 3 assert_docs(docs)
def test_load_success_multiple_arxiv_identifiers(api_client: ArxivAPIWrapper ) ->None: """Test a query of arxiv identifiers that returns the correct answer""" docs = api_client.load('1605.08386v1 2212.00794v2 2308.07912') assert len(docs) == 3 assert_docs(docs)
Test a query of arxiv identifiers that returns the correct answer
_get_document_for_video_id
captions = self._get_transcripe_for_video_id(video_id) video_response = self.youtube_client.videos().list(part='id,snippet', id= video_id).execute() return Document(page_content=captions, metadata=video_response.get('items')[0])
def _get_document_for_video_id(self, video_id: str, **kwargs: Any) ->Document: captions = self._get_transcripe_for_video_id(video_id) video_response = self.youtube_client.videos().list(part='id,snippet', id=video_id).execute() return Document(page_content=captions, metadata=video_response.get( ...
null
test_octoai_endpoint_text_generation
"""Test valid call to OctoAI text generation model.""" llm = OctoAIEndpoint(endpoint_url= 'https://mpt-7b-demo-f1kzsig6xes9.octoai.run/generate', octoai_api_token='<octoai_api_token>', model_kwargs={'max_new_tokens': 200, 'temperature': 0.75, 'top_p': 0.95, 'repetition_penalty': 1, 'seed': None, 'stop'...
def test_octoai_endpoint_text_generation() ->None: """Test valid call to OctoAI text generation model.""" llm = OctoAIEndpoint(endpoint_url= 'https://mpt-7b-demo-f1kzsig6xes9.octoai.run/generate', octoai_api_token='<octoai_api_token>', model_kwargs={ 'max_new_tokens': 200, 'temperature':...
Test valid call to OctoAI text generation model.
test_similarity_search_exact_search_unknown_distance_strategy
"""Test end to end construction and search with unknown distance strategy.""" with pytest.raises(KeyError): texts = ['foo', 'bar', 'baz'] ElasticsearchStore.from_texts(texts, FakeEmbeddings(), ** elasticsearch_connection, index_name=index_name, strategy= ElasticsearchStore.ExactRetrievalStrategy...
def test_similarity_search_exact_search_unknown_distance_strategy(self, elasticsearch_connection: dict, index_name: str) ->None: """Test end to end construction and search with unknown distance strategy.""" with pytest.raises(KeyError): texts = ['foo', 'bar', 'baz'] ElasticsearchStore.from_t...
Test end to end construction and search with unknown distance strategy.
add_message
"""Append the message to the record in SingleStoreDB""" self._create_table_if_not_exists() conn = self.connection_pool.connect() try: cur = conn.cursor() try: cur.execute('INSERT INTO {} ({}, {}) VALUES (%s, %s)'.format(self. table_name, self.session_id_field, self.message_field), (self. ...
def add_message(self, message: BaseMessage) ->None: """Append the message to the record in SingleStoreDB""" self._create_table_if_not_exists() conn = self.connection_pool.connect() try: cur = conn.cursor() try: cur.execute('INSERT INTO {} ({}, {}) VALUES (%s, %s)'.format( ...
Append the message to the record in SingleStoreDB
_import_koboldai
from langchain_community.llms.koboldai import KoboldApiLLM return KoboldApiLLM
def _import_koboldai() ->Any: from langchain_community.llms.koboldai import KoboldApiLLM return KoboldApiLLM
null
__init__
self._approve = approve self._should_check = should_check
def __init__(self, approve: Callable[[Any], bool]=_default_approve, should_check: Callable[[Dict[str, Any]], bool]=_default_true): self._approve = approve self._should_check = should_check
null
serialize_chat_messages
"""Extract the input messages from the run.""" if isinstance(messages, list) and messages: if isinstance(messages[0], dict): chat_messages = _get_messages_from_run_dict(messages) elif isinstance(messages[0], list): chat_messages = _get_messages_from_run_dict(messages[0]) else: raise ...
def serialize_chat_messages(self, messages: List[Dict]) ->str: """Extract the input messages from the run.""" if isinstance(messages, list) and messages: if isinstance(messages[0], dict): chat_messages = _get_messages_from_run_dict(messages) elif isinstance(messages[0], list): ...
Extract the input messages from the run.
_make_id
return f'{_hash(prompt)}#{_hash(llm_string)}'
@staticmethod def _make_id(prompt: str, llm_string: str) ->str: return f'{_hash(prompt)}#{_hash(llm_string)}'
null
config_specs
mapper_config_specs = [s for mapper in self.keys.values() if mapper is not None for s in mapper.config_specs] for spec in mapper_config_specs: if spec.id.endswith(CONTEXT_CONFIG_SUFFIX_GET): getter_key = spec.id.split('/')[1] if getter_key in self.keys: raise ValueError( ...
@property def config_specs(self) ->List[ConfigurableFieldSpec]: mapper_config_specs = [s for mapper in self.keys.values() if mapper is not None for s in mapper.config_specs] for spec in mapper_config_specs: if spec.id.endswith(CONTEXT_CONFIG_SUFFIX_GET): getter_key = spec.id.split('/...
null
_run
"""Use the Clickup API to run an operation.""" return self.api_wrapper.run(self.mode, instructions)
def _run(self, instructions: str, run_manager: Optional[ CallbackManagerForToolRun]=None) ->str: """Use the Clickup API to run an operation.""" return self.api_wrapper.run(self.mode, instructions)
Use the Clickup API to run an operation.
from_llm
"""Create a SQLDatabaseChain from an LLM and a database connection. *Security note*: Make sure that the database connection uses credentials that are narrowly-scoped to only include the permissions this chain needs. Failure to do so may result in data corruption or loss, since this chai...
@classmethod def from_llm(cls, llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional [BasePromptTemplate]=None, **kwargs: Any) ->SQLDatabaseChain: """Create a SQLDatabaseChain from an LLM and a database connection. *Security note*: Make sure that the database connection uses credentials ...
Create a SQLDatabaseChain from an LLM and a database connection. *Security note*: Make sure that the database connection uses credentials that are narrowly-scoped to only include the permissions this chain needs. Failure to do so may result in data corruption or loss, since this chain may attempt commands ...
__init__
"""Initialize the LLMThought. Args: parent_container: The container we're writing into. labeler: The labeler to use for this thought. expanded: Whether the thought should be expanded by default. collapse_on_complete: Whether the thought should be collapsed. ...
def __init__(self, parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool): """Initialize the LLMThought. Args: parent_container: The container we're writing into. labeler: The labeler to use for this thought. expande...
Initialize the LLMThought. Args: parent_container: The container we're writing into. labeler: The labeler to use for this thought. expanded: Whether the thought should be expanded by default. collapse_on_complete: Whether the thought should be collapsed.
exists
"""Check if the provided keys exist in the database. Args: keys: A list of keys to check. Returns: A list of boolean values indicating the existence of each key. """
@abstractmethod def exists(self, keys: Sequence[str]) ->List[bool]: """Check if the provided keys exist in the database. Args: keys: A list of keys to check. Returns: A list of boolean values indicating the existence of each key. """
Check if the provided keys exist in the database. Args: keys: A list of keys to check. Returns: A list of boolean values indicating the existence of each key.
test_bs_html_loader
"""Test unstructured loader.""" file_path = EXAMPLES / 'example.html' blob = Blob.from_path(file_path) parser = BS4HTMLParser(get_text_separator='|') docs = list(parser.lazy_parse(blob)) assert isinstance(docs, list) assert len(docs) == 1 metadata = docs[0].metadata content = docs[0].page_content assert metadata['title...
@pytest.mark.requires('bs4', 'lxml') def test_bs_html_loader() ->None: """Test unstructured loader.""" file_path = EXAMPLES / 'example.html' blob = Blob.from_path(file_path) parser = BS4HTMLParser(get_text_separator='|') docs = list(parser.lazy_parse(blob)) assert isinstance(docs, list) asse...
Test unstructured loader.
test_unstructured_xml_loader
"""Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DIRECTORY, 'factbook.xml') loader = UnstructuredXMLLoader(str(file_path)) docs = loader.load() assert len(docs) == 1
def test_unstructured_xml_loader() ->None: """Test unstructured loader.""" file_path = os.path.join(EXAMPLE_DIRECTORY, 'factbook.xml') loader = UnstructuredXMLLoader(str(file_path)) docs = loader.load() assert len(docs) == 1
Test unstructured loader.
format_prompt
""" Format prompt. Should return a PromptValue. Args: **kwargs: Keyword arguments to use for formatting. Returns: PromptValue. """ messages = self.format_messages(**kwargs) return ChatPromptValue(messages=messages)
def format_prompt(self, **kwargs: Any) ->PromptValue: """ Format prompt. Should return a PromptValue. Args: **kwargs: Keyword arguments to use for formatting. Returns: PromptValue. """ messages = self.format_messages(**kwargs) return ChatPromptValue(m...
Format prompt. Should return a PromptValue. Args: **kwargs: Keyword arguments to use for formatting. Returns: PromptValue.
delete
"""Delete by vector IDs. Args: ids: List of ids to delete. """ if ids is None: raise ValueError('No ids provided to delete.') rows: List[Dict[str, Any]] = [{'id': id} for id in ids] for row in rows: self._client.from_(self.table_name).delete().eq('id', row['id']).execute()
def delete(self, ids: Optional[List[str]]=None, **kwargs: Any) ->None: """Delete by vector IDs. Args: ids: List of ids to delete. """ if ids is None: raise ValueError('No ids provided to delete.') rows: List[Dict[str, Any]] = [{'id': id} for id in ids] for row in row...
Delete by vector IDs. Args: ids: List of ids to delete.
set_db
from arango.database import Database if not isinstance(db, Database): msg = '**db** parameter must inherit from arango.database.Database' raise TypeError(msg) self.__db: Database = db self.set_schema()
def set_db(self, db: Any) ->None: from arango.database import Database if not isinstance(db, Database): msg = '**db** parameter must inherit from arango.database.Database' raise TypeError(msg) self.__db: Database = db self.set_schema()
null
on_chain_start
"""Run when chain starts running."""
def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any], *, run_id: UUID, parent_run_id: Optional[UUID]=None, tags: Optional[ List[str]]=None, metadata: Optional[Dict[str, Any]]=None, **kwargs: Any ) ->Any: """Run when chain starts running."""
Run when chain starts running.
test_vertexai_single_call
if model_name: model = ChatVertexAI(model_name=model_name) else: model = ChatVertexAI() message = HumanMessage(content='Hello') response = model([message]) assert isinstance(response, AIMessage) assert isinstance(response.content, str)
@pytest.mark.scheduled @pytest.mark.parametrize('model_name', model_names_to_test) def test_vertexai_single_call(model_name: str) ->None: if model_name: model = ChatVertexAI(model_name=model_name) else: model = ChatVertexAI() message = HumanMessage(content='Hello') response = model([mess...
null
test_google_vertex_ai_search_get_relevant_documents
"""Test the get_relevant_documents() method.""" retriever = GoogleVertexAISearchRetriever() documents = retriever.get_relevant_documents("What are Alphabet's Other Bets?") assert len(documents) > 0 for doc in documents: assert isinstance(doc, Document) assert doc.page_content assert doc.metadata['id'] a...
@pytest.mark.requires('google.api_core') def test_google_vertex_ai_search_get_relevant_documents() ->None: """Test the get_relevant_documents() method.""" retriever = GoogleVertexAISearchRetriever() documents = retriever.get_relevant_documents( "What are Alphabet's Other Bets?") assert len(docum...
Test the get_relevant_documents() method.
output_keys
"""Expect input key. :meta private: """ _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = _output_keys + ['intermediate_steps'] if self.metadata_keys is not None: _output_keys += self.metadata_keys return _output_keys
@property def output_keys(self) ->List[str]: """Expect input key. :meta private: """ _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = _output_keys + ['intermediate_steps'] if self.metadata_keys is not None: _output_keys += self.metadat...
Expect input key. :meta private:
_import_serpapi
from langchain_community.utilities.serpapi import SerpAPIWrapper return SerpAPIWrapper
def _import_serpapi() ->Any: from langchain_community.utilities.serpapi import SerpAPIWrapper return SerpAPIWrapper
null
test_hyde_from_llm
"""Test loading HyDE from all prompts.""" for key in PROMPT_MAP: embedding = HypotheticalDocumentEmbedder.from_llm(FakeLLM(), FakeEmbeddings(), key) embedding.embed_query('foo')
def test_hyde_from_llm() ->None: """Test loading HyDE from all prompts.""" for key in PROMPT_MAP: embedding = HypotheticalDocumentEmbedder.from_llm(FakeLLM(), FakeEmbeddings(), key) embedding.embed_query('foo')
Test loading HyDE from all prompts.
build_extra_kwargs
"""Build extra kwargs from values and extra_kwargs. Args: extra_kwargs: Extra kwargs passed in by user. values: Values passed in by user. all_required_field_names: All required field names for the pydantic class. """ for field_name in list(values): if field_name in extra_kwargs: ...
def build_extra_kwargs(extra_kwargs: Dict[str, Any], values: Dict[str, Any], all_required_field_names: Set[str]) ->Dict[str, Any]: """Build extra kwargs from values and extra_kwargs. Args: extra_kwargs: Extra kwargs passed in by user. values: Values passed in by user. all_required_f...
Build extra kwargs from values and extra_kwargs. Args: extra_kwargs: Extra kwargs passed in by user. values: Values passed in by user. all_required_field_names: All required field names for the pydantic class.
_generate
llm_input = self._to_chat_prompt(messages) llm_result = self.llm._generate(prompts=[llm_input], stop=stop, run_manager =run_manager, **kwargs) return self._to_chat_result(llm_result)
def _generate(self, messages: List[BaseMessage], stop: Optional[List[str]]= None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->ChatResult: llm_input = self._to_chat_prompt(messages) llm_result = self.llm._generate(prompts=[llm_input], stop=stop, run_manager=run_manager...
null
on_chain_end
"""If either the `parent_run_id` or the `run_id` is in `self.prompts`, then log the outputs to Argilla, and pop the run from `self.prompts`. The behavior differs if the output is a list or not. """ if not any(key in self.prompts for key in [str(kwargs['parent_run_id']), str(kwargs['run_id'])...
def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) ->None: """If either the `parent_run_id` or the `run_id` is in `self.prompts`, then log the outputs to Argilla, and pop the run from `self.prompts`. The behavior differs if the output is a list or not. """ if not any(key in s...
If either the `parent_run_id` or the `run_id` is in `self.prompts`, then log the outputs to Argilla, and pop the run from `self.prompts`. The behavior differs if the output is a list or not.
get_num_tokens_from_messages
"""Calculate num tokens with tiktoken package. Official documentation: https://github.com/openai/openai-cookbook/blob/ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb""" if sys.version_info[1] <= 7: return super().get_num_tokens_from_messages(messages) model, encoding = self._get_encodin...
def get_num_tokens_from_messages(self, messages: list[BaseMessage]) ->int: """Calculate num tokens with tiktoken package. Official documentation: https://github.com/openai/openai-cookbook/blob/ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb""" if sys.version_info[1] <= 7: re...
Calculate num tokens with tiktoken package. Official documentation: https://github.com/openai/openai-cookbook/blob/ main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
test_promptlayer_openai_chat_stop_valid
"""Test promptlayer openai stop logic on valid configuration.""" query = 'write an ordered list of five items' first_llm = PromptLayerOpenAIChat(stop='3', temperature=0) first_output = first_llm(query) second_llm = PromptLayerOpenAIChat(temperature=0) second_output = second_llm(query, stop=['3']) assert first_output ==...
def test_promptlayer_openai_chat_stop_valid() ->None: """Test promptlayer openai stop logic on valid configuration.""" query = 'write an ordered list of five items' first_llm = PromptLayerOpenAIChat(stop='3', temperature=0) first_output = first_llm(query) second_llm = PromptLayerOpenAIChat(temperatu...
Test promptlayer openai stop logic on valid configuration.
test_json_spec_from_file
"""Test JsonSpec can be constructed from a file.""" path = tmp_path / 'test.json' path.write_text('{"foo": "bar"}') spec = JsonSpec.from_file(path) assert spec.dict_ == {'foo': 'bar'}
def test_json_spec_from_file(tmp_path: Path) ->None: """Test JsonSpec can be constructed from a file.""" path = tmp_path / 'test.json' path.write_text('{"foo": "bar"}') spec = JsonSpec.from_file(path) assert spec.dict_ == {'foo': 'bar'}
Test JsonSpec can be constructed from a file.
_invocation_params
params = {**self._default_params, **kwargs} if stop is not None: params['stop'] = stop if params.get('stream'): params['incremental_output'] = True message_dicts = [convert_message_to_dict(m) for m in messages] if message_dicts[-1]['role'] != 'user': raise ValueError('Last message should be user message.') ...
def _invocation_params(self, messages: List[BaseMessage], stop: Any, ** kwargs: Any) ->Dict[str, Any]: params = {**self._default_params, **kwargs} if stop is not None: params['stop'] = stop if params.get('stream'): params['incremental_output'] = True message_dicts = [convert_message_...
null
embeddings
return self._embeddings
@property def embeddings(self) ->Embeddings: return self._embeddings
null
_build_istr
ks = ','.join(column_names) _data = [] for n in transac: n = ','.join([f"'{self.escape_str(str(_n))}'" for _n in n]) _data.append(f'({n})') i_str = f""" INSERT INTO TABLE {self.config.database}.{self.config.table}({ks}) VALUES {','.join(_data)...
def _build_istr(self, transac: Iterable, column_names: Iterable[str]) ->str: ks = ','.join(column_names) _data = [] for n in transac: n = ','.join([f"'{self.escape_str(str(_n))}'" for _n in n]) _data.append(f'({n})') i_str = f""" INSERT INTO TABLE {se...
null
test_exception_handling_str
expected = 'foo bar' _tool = _FakeExceptionTool(handle_tool_error=expected) actual = _tool.run({}) assert expected == actual
def test_exception_handling_str() ->None: expected = 'foo bar' _tool = _FakeExceptionTool(handle_tool_error=expected) actual = _tool.run({}) assert expected == actual
null
results
results = self._search_api_results(query, **kwargs) return results
def results(self, query: str, **kwargs: Any) ->dict: results = self._search_api_results(query, **kwargs) return results
null
InputType
return self.runnable.InputType
@property def InputType(self) ->Type[Input]: return self.runnable.InputType
null
save
"""Raise error - saving not supported for Agent Executors.""" raise ValueError( 'Saving not supported for agent executors. If you are trying to save the agent, please use the `.save_agent(...)`' )
def save(self, file_path: Union[Path, str]) ->None: """Raise error - saving not supported for Agent Executors.""" raise ValueError( 'Saving not supported for agent executors. If you are trying to save the agent, please use the `.save_agent(...)`' )
Raise error - saving not supported for Agent Executors.
concatenate_rows
"""Combine message information in a readable format ready to be used.""" return f'{sender} on {date}: {text}\n\n'
def concatenate_rows(date: str, sender: str, text: str) ->str: """Combine message information in a readable format ready to be used.""" return f'{sender} on {date}: {text}\n\n'
Combine message information in a readable format ready to be used.
test_test_group_dependencies
"""Check if someone is attempting to add additional test dependencies. Only dependencies associated with test running infrastructure should be added to the test group; e.g., pytest, pytest-cov etc. Examples of dependencies that should NOT be included: boto3, azure, postgres, etc. """ test_group_deps =...
def test_test_group_dependencies(poetry_conf: Mapping[str, Any]) ->None: """Check if someone is attempting to add additional test dependencies. Only dependencies associated with test running infrastructure should be added to the test group; e.g., pytest, pytest-cov etc. Examples of dependencies that s...
Check if someone is attempting to add additional test dependencies. Only dependencies associated with test running infrastructure should be added to the test group; e.g., pytest, pytest-cov etc. Examples of dependencies that should NOT be included: boto3, azure, postgres, etc.
_convert_chunk_to_message_message
data = json.loads(chunk.encode('utf-8')) return AIMessageChunk(content=data.get('response', ''))
def _convert_chunk_to_message_message(self, chunk: str) ->AIMessageChunk: data = json.loads(chunk.encode('utf-8')) return AIMessageChunk(content=data.get('response', ''))
null
load_embedding_model
"""Load the embedding model.""" if not instruct: import sentence_transformers client = sentence_transformers.SentenceTransformer(model_id) else: from InstructorEmbedding import INSTRUCTOR client = INSTRUCTOR(model_id) if importlib.util.find_spec('torch') is not None: import torch cuda_device_cou...
def load_embedding_model(model_id: str, instruct: bool=False, device: int=0 ) ->Any: """Load the embedding model.""" if not instruct: import sentence_transformers client = sentence_transformers.SentenceTransformer(model_id) else: from InstructorEmbedding import INSTRUCTOR ...
Load the embedding model.
test_hub_runnable_configurable_fields
mock_pull.side_effect = repo_lookup original: HubRunnable = HubRunnable('efriis/my-prompt-1') obj_configurable = original.configurable_fields(owner_repo_commit= ConfigurableField(id='owner_repo_commit', name='Hub ID')) templated_1 = obj_configurable.invoke({}) assert templated_1.messages[1].content == '1' templated...
@patch('langchain.hub.pull') def test_hub_runnable_configurable_fields(mock_pull: Mock) ->None: mock_pull.side_effect = repo_lookup original: HubRunnable = HubRunnable('efriis/my-prompt-1') obj_configurable = original.configurable_fields(owner_repo_commit= ConfigurableField(id='owner_repo_commit', n...
null
run_no_throw
"""Execute a SQL command and return a string representing the results. If the statement returns rows, a string of the results is returned. If the statement returns no rows, an empty string is returned. If the statement throws an error, the error message is returned. """ try: return...
def run_no_throw(self, command: str, fetch: str='all') ->str: """Execute a SQL command and return a string representing the results. If the statement returns rows, a string of the results is returned. If the statement returns no rows, an empty string is returned. If the statement throws an...
Execute a SQL command and return a string representing the results. If the statement returns rows, a string of the results is returned. If the statement returns no rows, an empty string is returned. If the statement throws an error, the error message is returned.
test_blob_initialized_with_binary_data
"""Test reading blob IO if blob content hasn't been read yet.""" data = b'Hello, World!' blob = Blob(data=data) assert blob.as_string() == 'Hello, World!' assert blob.as_bytes() == data assert blob.source is None with blob.as_bytes_io() as bytes_io: assert bytes_io.read() == data
def test_blob_initialized_with_binary_data() ->None: """Test reading blob IO if blob content hasn't been read yet.""" data = b'Hello, World!' blob = Blob(data=data) assert blob.as_string() == 'Hello, World!' assert blob.as_bytes() == data assert blob.source is None with blob.as_bytes_io() as...
Test reading blob IO if blob content hasn't been read yet.
test_batch
"""Test batch tokens from Chat__ModuleName__.""" llm = Chat__ModuleName__() result = llm.batch(["I'm Pickle Rick", "I'm not Pickle Rick"]) for token in result: assert isinstance(token.content, str)
def test_batch() ->None: """Test batch tokens from Chat__ModuleName__.""" llm = Chat__ModuleName__() result = llm.batch(["I'm Pickle Rick", "I'm not Pickle Rick"]) for token in result: assert isinstance(token.content, str)
Test batch tokens from Chat__ModuleName__.
_type
return 'self_ask'
@property def _type(self) ->str: return 'self_ask'
null
similarity_search
""" Return docs most similar to query. """ if self.embedding_func is None: raise ValueError('embedding_func is None!!!') embeddings = self.embedding_func.embed_query(query) docs = self.similarity_search_by_vector(embeddings, k) return docs
def similarity_search(self, query: str, k: int=DEFAULT_TOPN, **kwargs: Any ) ->List[Document]: """ Return docs most similar to query. """ if self.embedding_func is None: raise ValueError('embedding_func is None!!!') embeddings = self.embedding_func.embed_query(query) docs = ...
Return docs most similar to query.
load
"""Makes a call to Cube's REST API metadata endpoint. Returns: A list of documents with attributes: - page_content=column_title + column_description - metadata - table_name - column_name - column_data_type ...
def load(self) ->List[Document]: """Makes a call to Cube's REST API metadata endpoint. Returns: A list of documents with attributes: - page_content=column_title + column_description - metadata - table_name - column_name ...
Makes a call to Cube's REST API metadata endpoint. Returns: A list of documents with attributes: - page_content=column_title + column_description - metadata - table_name - column_name - column_data_type - column_member_type - column_title ...
_invocation_params
"""Get the parameters used to invoke the model.""" openai_creds: Dict[str, Any] = {'api_key': cast(SecretStr, self. anyscale_api_key).get_secret_value(), 'api_base': self.anyscale_api_base} return {**openai_creds, **{'model': self.model_name}, **super()._default_params }
@property def _invocation_params(self) ->Dict[str, Any]: """Get the parameters used to invoke the model.""" openai_creds: Dict[str, Any] = {'api_key': cast(SecretStr, self. anyscale_api_key).get_secret_value(), 'api_base': self. anyscale_api_base} return {**openai_creds, **{'model': self.mod...
Get the parameters used to invoke the model.
test_add_documents_with_ids
ids = [uuid.uuid4().hex for _ in range(len(texts))] Pinecone.from_texts(texts=texts, ids=ids, embedding=embedding_openai, index_name=index_name, namespace=index_name) index_stats = self.index.describe_index_stats() assert index_stats['namespaces'][index_name]['vector_count'] == len(texts) ids_1 = [uuid.uuid4().hex ...
def test_add_documents_with_ids(self, texts: List[str], embedding_openai: OpenAIEmbeddings) ->None: ids = [uuid.uuid4().hex for _ in range(len(texts))] Pinecone.from_texts(texts=texts, ids=ids, embedding=embedding_openai, index_name=index_name, namespace=index_name) index_stats = self.index.desc...
null
set_model
"""Set the model used for embedding. The default model used is all-mpnet-base-v2 Args: model_name: A string which represents the name of model. """ self.model = model_name self.client.model_name = model_name
def set_model(self, model_name: str) ->None: """Set the model used for embedding. The default model used is all-mpnet-base-v2 Args: model_name: A string which represents the name of model. """ self.model = model_name self.client.model_name = model_name
Set the model used for embedding. The default model used is all-mpnet-base-v2 Args: model_name: A string which represents the name of model.
on_chat_model_start
self.messages = [_convert_message_to_dict(message) for message in messages[0]] self.prompt = self.messages[-1]['content']
def on_chat_model_start(self, serialized: Dict[str, Any], messages: List[ List[BaseMessage]], **kwargs: Any) ->None: self.messages = [_convert_message_to_dict(message) for message in messages[0]] self.prompt = self.messages[-1]['content']
null
test_openai_embedding_with_empty_string
"""Test openai embeddings with empty string.""" import openai document = ['', 'abc'] embedding = OpenAIEmbeddings() output = embedding.embed_documents(document) assert len(output) == 2 assert len(output[0]) == 1536 expected_output = openai.Embedding.create(input='', model= 'text-embedding-ada-002')['data'][0]['embe...
@pytest.mark.skip(reason='Unblock scheduled testing. TODO: fix.') @pytest.mark.scheduled def test_openai_embedding_with_empty_string() ->None: """Test openai embeddings with empty string.""" import openai document = ['', 'abc'] embedding = OpenAIEmbeddings() output = embedding.embed_documents(docume...
Test openai embeddings with empty string.
test_saving_loading_round_trip
"""Test saving/loading a Fake LLM.""" fake_llm = FakeLLM() fake_llm.save(file_path=tmp_path / 'fake_llm.yaml') loaded_llm = load_llm(tmp_path / 'fake_llm.yaml') assert loaded_llm == fake_llm
@patch('langchain_community.llms.loading.get_type_to_cls_dict', lambda : { 'fake': lambda : FakeLLM}) def test_saving_loading_round_trip(tmp_path: Path) ->None: """Test saving/loading a Fake LLM.""" fake_llm = FakeLLM() fake_llm.save(file_path=tmp_path / 'fake_llm.yaml') loaded_llm = load_llm(tmp_pa...
Test saving/loading a Fake LLM.
initialize
""" Initialize a vector store with a set of documents. By default, the documents will be compatible with the default metadata field info. You can override these defaults by passing in your own values. :param embeddings: an Embeddings to use for generating queries :param collection_name: name of the ...
def initialize(embeddings: Optional[Embeddings]=None, collection_name: str= defaults.DEFAULT_COLLECTION_NAME, documents: List[Document]=defaults. DEFAULT_DOCUMENTS): """ Initialize a vector store with a set of documents. By default, the documents will be compatible with the default metadata field in...
Initialize a vector store with a set of documents. By default, the documents will be compatible with the default metadata field info. You can override these defaults by passing in your own values. :param embeddings: an Embeddings to use for generating queries :param collection_name: name of the Qdrant collection to use...
test_invoke
"""Test invoke tokens from Chat__ModuleName__.""" llm = Chat__ModuleName__() result = llm.invoke("I'm Pickle Rick", config=dict(tags=['foo'])) assert isinstance(result.content, str)
def test_invoke() ->None: """Test invoke tokens from Chat__ModuleName__.""" llm = Chat__ModuleName__() result = llm.invoke("I'm Pickle Rick", config=dict(tags=['foo'])) assert isinstance(result.content, str)
Test invoke tokens from Chat__ModuleName__.