method_name
stringlengths
1
78
method_body
stringlengths
3
9.66k
full_code
stringlengths
31
10.7k
docstring
stringlengths
4
4.74k
_import_slack_schedule_message
from langchain_community.tools.slack.schedule_message import SlackScheduleMessage return SlackScheduleMessage
def _import_slack_schedule_message() ->Any: from langchain_community.tools.slack.schedule_message import SlackScheduleMessage return SlackScheduleMessage
null
_generate
"""Run the LLM on the given prompt and input.""" from aphrodite import SamplingParams params = {**self._default_params, **kwargs, 'stop': stop} if 'logit_bias' in params: del params['logit_bias'] sampling_params = SamplingParams(**params) outputs = self.client.generate(prompts, sampling_params) generations = [] for...
def _generate(self, prompts: List[str], stop: Optional[List[str]]=None, run_manager: Optional[CallbackManagerForLLMRun]=None, **kwargs: Any ) ->LLMResult: """Run the LLM on the given prompt and input.""" from aphrodite import SamplingParams params = {**self._default_params, **kwargs, 'stop': stop} ...
Run the LLM on the given prompt and input.
test_media_search
"""Test for NASA Image and Video Library media search""" nasa = NasaAPIWrapper() query = ( '{"q": "saturn", + "year_start": "2002", "year_end": "2010", "page": 2}') output = nasa.run('search_media', query) assert output is not None assert 'collection' in output
def test_media_search() ->None: """Test for NASA Image and Video Library media search""" nasa = NasaAPIWrapper() query = ( '{"q": "saturn", + "year_start": "2002", "year_end": "2010", "page": 2}' ) output = nasa.run('search_media', query) assert output is not None assert 'collect...
Test for NASA Image and Video Library media search
__init__
self.document = guard_import('tcvectordb.model.document') tcvectordb = guard_import('tcvectordb') self.embedding_func = embedding self.index_params = index_params self.vdb_client = tcvectordb.VectorDBClient(url=connection_params.url, username=connection_params.username, key=connection_params.key, timeout =conne...
def __init__(self, embedding: Embeddings, connection_params: ConnectionParams, index_params: IndexParams=IndexParams(128), database_name: str='LangChainDatabase', collection_name: str= 'LangChainCollection', drop_old: Optional[bool]=False): self.document = guard_import('tcvectordb.model.document') t...
null
test_faiss_vector_sim_with_score_threshold
"""Test vector similarity.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings()) index_to_id = docsearch.index_to_docstore_id expected_docstore = InMemoryDocstore({index_to_id[0]: Document(page_content ='foo'), index_to_id[1]: Document(page_content='bar'), index_to_id[2]: Docume...
@pytest.mark.requires('faiss') def test_faiss_vector_sim_with_score_threshold() ->None: """Test vector similarity.""" texts = ['foo', 'bar', 'baz'] docsearch = FAISS.from_texts(texts, FakeEmbeddings()) index_to_id = docsearch.index_to_docstore_id expected_docstore = InMemoryDocstore({index_to_id[0]:...
Test vector similarity.
load
""" Get logs from Datadog. Returns: A list of Document objects. - page_content - metadata - id - service - status - tags - timestamp """ try: from ...
def load(self) ->List[Document]: """ Get logs from Datadog. Returns: A list of Document objects. - page_content - metadata - id - service - status - tags -...
Get logs from Datadog. Returns: A list of Document objects. - page_content - metadata - id - service - status - tags - timestamp
update
"""Update cache based on prompt and llm_string."""
@abstractmethod def update(self, prompt: str, llm_string: str, return_val: RETURN_VAL_TYPE ) ->None: """Update cache based on prompt and llm_string."""
Update cache based on prompt and llm_string.
__init__
"""Initialize with the LLM and a docstore.""" docstore_explorer = DocstoreExplorer(docstore) tools = [Tool(name='Search', func=docstore_explorer.search, description= 'Search for a term in the docstore.'), Tool(name='Lookup', func= docstore_explorer.lookup, description='Lookup a term in the docstore.')] agent = ...
def __init__(self, llm: BaseLanguageModel, docstore: Docstore, **kwargs: Any): """Initialize with the LLM and a docstore.""" docstore_explorer = DocstoreExplorer(docstore) tools = [Tool(name='Search', func=docstore_explorer.search, description ='Search for a term in the docstore.'), Tool(name='Looku...
Initialize with the LLM and a docstore.
from_parameter
"""Instantiate from an OpenAPI Parameter.""" location = APIPropertyLocation.from_str(parameter.param_in) cls._validate_location(location, parameter.name) cls._validate_content(parameter.content) schema = cls._get_schema(parameter, spec) schema_type = cls._get_schema_type(parameter, schema) default_val = schema.default ...
@classmethod def from_parameter(cls, parameter: Parameter, spec: OpenAPISpec ) ->'APIProperty': """Instantiate from an OpenAPI Parameter.""" location = APIPropertyLocation.from_str(parameter.param_in) cls._validate_location(location, parameter.name) cls._validate_content(parameter.content) schem...
Instantiate from an OpenAPI Parameter.
__init__
"""Initialize callback handler.""" wandb = import_wandb() import_pandas() import_textstat() spacy = import_spacy() super().__init__() self.job_type = job_type self.project = project self.entity = entity self.tags = tags self.group = group self.name = name self.notes = notes self.visualize = visualize self.complexity_me...
def __init__(self, job_type: Optional[str]=None, project: Optional[str]= 'langchain_callback_demo', entity: Optional[str]=None, tags: Optional[ Sequence]=None, group: Optional[str]=None, name: Optional[str]=None, notes: Optional[str]=None, visualize: bool=False, complexity_metrics: bool=False, stream_lo...
Initialize callback handler.
on_agent_finish
"""Run on agent end."""
def on_agent_finish(self, finish: AgentFinish, *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: """Run on agent end."""
Run on agent end.
run
"""Run command with own globals/locals and returns anything printed. Timeout after the specified number of seconds.""" warn_once() queue: multiprocessing.Queue = multiprocessing.Queue() if timeout is not None: p = multiprocessing.Process(target=self.worker, args=(command, self. globals, self.locals,...
def run(self, command: str, timeout: Optional[int]=None) ->str: """Run command with own globals/locals and returns anything printed. Timeout after the specified number of seconds.""" warn_once() queue: multiprocessing.Queue = multiprocessing.Queue() if timeout is not None: p = multiproce...
Run command with own globals/locals and returns anything printed. Timeout after the specified number of seconds.
_chain_type
return 'llm_chain'
@property def _chain_type(self) ->str: return 'llm_chain'
null
from_credentials
"""Instantiate embeddings from Elasticsearch credentials. Args: model_id (str): The model_id of the model deployed in the Elasticsearch cluster. input_field (str): The name of the key for the input text field in the document. Defaults to 'text_field'. ...
@classmethod def from_credentials(cls, model_id: str, *, es_cloud_id: Optional[str]=None, es_user: Optional[str]=None, es_password: Optional[str]=None, input_field: str='text_field') ->ElasticsearchEmbeddings: """Instantiate embeddings from Elasticsearch credentials. Args: model_id (str...
Instantiate embeddings from Elasticsearch credentials. Args: model_id (str): The model_id of the model deployed in the Elasticsearch cluster. input_field (str): The name of the key for the input text field in the document. Defaults to 'text_field'. es_cloud_id: (str, optional): The Elastics...
get_debug
"""Get the value of the `debug` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing debug from langchain root module is no longer supported' ) old_debug = langchain.debug except ImportError: ol...
def get_debug() ->bool: """Get the value of the `debug` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing debug from langchain root module is no longer supported' ) ...
Get the value of the `debug` global setting.
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
test_prompt_with_chat_model_and_parser
prompt = SystemMessagePromptTemplate.from_template('You are a nice assistant.' ) + '{question}' chat = FakeListChatModel(responses=['foo, bar']) parser = CommaSeparatedListOutputParser() chain = prompt | chat | parser assert isinstance(chain, RunnableSequence) assert chain.first == prompt assert chain.middle == [ch...
@freeze_time('2023-01-01') def test_prompt_with_chat_model_and_parser(mocker: MockerFixture, snapshot: SnapshotAssertion) ->None: prompt = SystemMessagePromptTemplate.from_template( 'You are a nice assistant.') + '{question}' chat = FakeListChatModel(responses=['foo, bar']) parser = CommaSeparat...
null
search
"""Return docs most similar to query using specified search type.""" if search_type == 'similarity': return self.similarity_search(query, **kwargs) elif search_type == 'mmr': return self.max_marginal_relevance_search(query, **kwargs) else: raise ValueError( f"search_type of {search_type} not allowed...
def search(self, query: str, search_type: str, **kwargs: Any) ->List[Document]: """Return docs most similar to query using specified search type.""" if search_type == 'similarity': return self.similarity_search(query, **kwargs) elif search_type == 'mmr': return self.max_marginal_relevance_se...
Return docs most similar to query using specified search type.
test_api_key_masked_when_passed_via_constructor
llm = VolcEngineMaasBase(volc_engine_maas_ak='secret-volc-ak', volc_engine_maas_sk='secret-volc-sk') print(llm.volc_engine_maas_ak, end='') captured = capsys.readouterr() assert captured.out == '**********'
def test_api_key_masked_when_passed_via_constructor(capsys: CaptureFixture ) ->None: llm = VolcEngineMaasBase(volc_engine_maas_ak='secret-volc-ak', volc_engine_maas_sk='secret-volc-sk') print(llm.volc_engine_maas_ak, end='') captured = capsys.readouterr() assert captured.out == '**********'
null
stream
result = self.invoke(input, config) for c in result: if self.sleep is not None: time.sleep(self.sleep) yield c
def stream(self, input: LanguageModelInput, config: Optional[RunnableConfig ]=None, *, stop: Optional[List[str]]=None, **kwargs: Any) ->Iterator[str]: result = self.invoke(input, config) for c in result: if self.sleep is not None: time.sleep(self.sleep) yield c
null
_import_xinference
from langchain_community.llms.xinference import Xinference return Xinference
def _import_xinference() ->Any: from langchain_community.llms.xinference import Xinference return Xinference
null
_get_message_data
msg = service.users().messages().get(userId='me', id=message['id']).execute() message_content = _extract_email_content(msg) in_reply_to = None email_data = msg['payload']['headers'] for values in email_data: name = values['name'] if name == 'In-Reply-To': in_reply_to = values['value'] if in_reply_to is ...
def _get_message_data(service: Any, message: Any) ->ChatSession: msg = service.users().messages().get(userId='me', id=message['id'] ).execute() message_content = _extract_email_content(msg) in_reply_to = None email_data = msg['payload']['headers'] for values in email_data: name = val...
null
validate_environment
"""Validate that group id and api key exists in environment.""" minimax_group_id = get_from_dict_or_env(values, 'minimax_group_id', 'MINIMAX_GROUP_ID') minimax_api_key = convert_to_secret_str(get_from_dict_or_env(values, 'minimax_api_key', 'MINIMAX_API_KEY')) values['minimax_group_id'] = minimax_group_id values...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: """Validate that group id and api key exists in environment.""" minimax_group_id = get_from_dict_or_env(values, 'minimax_group_id', 'MINIMAX_GROUP_ID') minimax_api_key = convert_to_secret_str(get_from_dict_or_env(values, '...
Validate that group id and api key exists in environment.
load
try: from google.cloud import bigquery except ImportError as ex: raise ImportError( 'Could not import google-cloud-bigquery python package. Please install it with `pip install google-cloud-bigquery`.' ) from ex bq_client = bigquery.Client(credentials=self.credentials, project=self. project, ...
def load(self) ->List[Document]: try: from google.cloud import bigquery except ImportError as ex: raise ImportError( 'Could not import google-cloud-bigquery python package. Please install it with `pip install google-cloud-bigquery`.' ) from ex bq_client = bigquery.Cli...
null
_run
"""Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.patch(_clean_url(data['url']), data['data']) except Exception as e: return repr(e)
def _run(self, text: str, run_manager: Optional[CallbackManagerForToolRun]=None ) ->str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.patch(_clean_url(data['url']), data[ 'data']) except Exception as e: return repr(e)
Run the tool.
clear
"""Clear session memory from the local file""" self.file_path.write_text(json.dumps([]))
def clear(self) ->None: """Clear session memory from the local file""" self.file_path.write_text(json.dumps([]))
Clear session memory from the local file
_identifying_params
"""Get the identifying parameters.""" return {**{'hardware': self.hardware}}
@property def _identifying_params(self) ->Mapping[str, Any]: """Get the identifying parameters.""" return {**{'hardware': self.hardware}}
Get the identifying parameters.
on_text
"""Do nothing.""" pass
def on_text(self, text: str, **kwargs: Any) ->None: """Do nothing.""" pass
Do nothing.
test_add_embeddings
""" Test add_embeddings, which accepts pre-built embeddings instead of using inference for the texts. This allows you to separate the embeddings text and the page_content for better proximity between user's question and embedded text. For example, your embedding text can be a q...
def test_add_embeddings(self, elasticsearch_connection: dict, index_name: str ) ->None: """ Test add_embeddings, which accepts pre-built embeddings instead of using inference for the texts. This allows you to separate the embeddings text and the page_content for better proximit...
Test add_embeddings, which accepts pre-built embeddings instead of using inference for the texts. This allows you to separate the embeddings text and the page_content for better proximity between user's question and embedded text. For example, your embedding text can be a question, whereas page_content is the answer...
get_reduce_chain
"""For backwards compatibility.""" if 'combine_document_chain' in values: if 'reduce_documents_chain' in values: raise ValueError( 'Both `reduce_documents_chain` and `combine_document_chain` cannot be provided at the same time. `combine_document_chain` is deprecated, please only provide `reduce_...
@root_validator(pre=True) def get_reduce_chain(cls, values: Dict) ->Dict: """For backwards compatibility.""" if 'combine_document_chain' in values: if 'reduce_documents_chain' in values: raise ValueError( 'Both `reduce_documents_chain` and `combine_document_chain` cannot be p...
For backwards compatibility.
bind
""" Bind arguments to a Runnable, returning a new Runnable. """ return RunnableBinding(bound=self, kwargs=kwargs, config={})
def bind(self, **kwargs: Any) ->Runnable[Input, Output]: """ Bind arguments to a Runnable, returning a new Runnable. """ return RunnableBinding(bound=self, kwargs=kwargs, config={})
Bind arguments to a Runnable, returning a new Runnable.
multi_modal_rag_chain
""" Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process. """ model = ChatOllama(model='bakllava', temperature=0) chain = {'context': retriever | RunnableLambda(get_resized_images),...
def multi_modal_rag_chain(retriever): """ Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process. """ model = ChatOllama(model='bakllava', temperature=0) chain = {'context...
Multi-modal RAG chain, :param retriever: A function that retrieves the necessary context for the model. :return: A chain of functions representing the multi-modal RAG process.
parse
"""Parse the output of an LLM call.""" result = {} for output_key, expected_format in self.output_key_to_format.items(): specific_regex = self.regex_pattern.format(re.escape(expected_format)) matches = re.findall(specific_regex, text) if not matches: raise ValueError( f'No match found fo...
def parse(self, text: str) ->Dict[str, str]: """Parse the output of an LLM call.""" result = {} for output_key, expected_format in self.output_key_to_format.items(): specific_regex = self.regex_pattern.format(re.escape(expected_format)) matches = re.findall(specific_regex, text) if n...
Parse the output of an LLM call.
lazy_load
"""Lazy load Documents from table.""" from pyairtable import Table table = Table(self.api_token, self.base_id, self.table_id) records = table.all() for record in records: yield Document(page_content=str(record), metadata={'source': self. base_id + '_' + self.table_id, 'base_id': self.base_id, 'table_id': ...
def lazy_load(self) ->Iterator[Document]: """Lazy load Documents from table.""" from pyairtable import Table table = Table(self.api_token, self.base_id, self.table_id) records = table.all() for record in records: yield Document(page_content=str(record), metadata={'source': self. ...
Lazy load Documents from table.
description
return (base_description + '\n\n' + self.file_description).strip()
@property def description(self) ->str: return (base_description + '\n\n' + self.file_description).strip()
null
_add_vectors
"""Add vectors to Supabase table.""" rows: List[Dict[str, Any]] = [{'id': ids[idx], 'content': documents[idx]. page_content, 'embedding': embedding, 'metadata': documents[idx]. metadata} for idx, embedding in enumerate(vectors)] id_list: List[str] = [] for i in range(0, len(rows), chunk_size): chunk = rows[...
@staticmethod def _add_vectors(client: supabase.client.Client, table_name: str, vectors: List[List[float]], documents: List[Document], ids: List[str], chunk_size: int) ->List[str]: """Add vectors to Supabase table.""" rows: List[Dict[str, Any]] = [{'id': ids[idx], 'content': documents[idx ].page...
Add vectors to Supabase table.
embed_query
"""Call out to Cohere's embedding endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self.embed_documents([text])[0]
def embed_query(self, text: str) ->List[float]: """Call out to Cohere's embedding endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self.embed_documents([text])[0]
Call out to Cohere's embedding endpoint. Args: text: The text to embed. Returns: Embeddings for the text.
test_init
mock_session_pool.return_value = MagicMock() nebula_graph = NebulaGraph(self.space, self.username, self.password, self. address, self.port, self.session_pool_size) self.assertEqual(nebula_graph.space, self.space) self.assertEqual(nebula_graph.username, self.username) self.assertEqual(nebula_graph.password, self.pas...
@patch('nebula3.gclient.net.SessionPool.SessionPool') def test_init(self, mock_session_pool: Any) ->None: mock_session_pool.return_value = MagicMock() nebula_graph = NebulaGraph(self.space, self.username, self.password, self.address, self.port, self.session_pool_size) self.assertEqual(nebula_graph.s...
null
__init__
self.generator = stream_generate_with_retry(_llm, **_kwargs)
def __init__(self, _llm: Tongyi, **_kwargs: Any): self.generator = stream_generate_with_retry(_llm, **_kwargs)
null
wrap
async def wrapped_f(*args: Any, **kwargs: Any) ->Callable: async for _ in async_retrying: return await func(*args, **kwargs) raise AssertionError('this is unreachable') return wrapped_f
def wrap(func: Callable) ->Callable: async def wrapped_f(*args: Any, **kwargs: Any) ->Callable: async for _ in async_retrying: return await func(*args, **kwargs) raise AssertionError('this is unreachable') return wrapped_f
null
max_marginal_relevance_search_with_score_by_vector
"""Return docs selected using the maximal marginal relevance with score to embedding vector. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: embedding: Embedding to look up documents similar to. ...
def max_marginal_relevance_search_with_score_by_vector(self, embedding: List[float], k: int=4, fetch_k: int=20, lambda_mult: float=0.5, filter: Optional[Dict[str, str]]=None, **kwargs: Any) ->List[Tuple[Document, float] ]: """Return docs selected using the maximal marginal relevance with score ...
Return docs selected using the maximal marginal relevance with score to embedding vector. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: embedding: Embedding to look up documents similar to. k (int): Number of Documents to return. Defaults to...
extract_paths
""" Args: query: cypher query """ paths = [] idx = 0 while (matched := self.path_pattern.findall(query[idx:])): matched = matched[0] matched = [m for i, m in enumerate(matched) if i not in [1, len(matched ) - 1]] path = ''.join(matched) idx = query.find(path) + len(pa...
def extract_paths(self, query: str) ->'List[str]': """ Args: query: cypher query """ paths = [] idx = 0 while (matched := self.path_pattern.findall(query[idx:])): matched = matched[0] matched = [m for i, m in enumerate(matched) if i not in [1, len( ...
Args: query: cypher query
test_dependency_string_invalids
with pytest.raises(ValueError): parse_dependency_string( 'git+https://github.com/efriis/myrepo.git#subdirectory=src@branch', None, None, None)
def test_dependency_string_invalids() ->None: with pytest.raises(ValueError): parse_dependency_string( 'git+https://github.com/efriis/myrepo.git#subdirectory=src@branch', None, None, None)
null
test_pandas_output_parser_row_first
expected_output = {'1': pd.Series({'chicken': 2, 'veggies': 4, 'steak': 8})} actual_output = parser.parse_folder('row:1') assert actual_output['1'].equals(expected_output['1'])
def test_pandas_output_parser_row_first() ->None: expected_output = {'1': pd.Series({'chicken': 2, 'veggies': 4, 'steak': 8}) } actual_output = parser.parse_folder('row:1') assert actual_output['1'].equals(expected_output['1'])
null
test_check_package_version_fail
with pytest.raises(ValueError): check_package_version('PyYAML', lt_version='5.4.1')
def test_check_package_version_fail() ->None: with pytest.raises(ValueError): check_package_version('PyYAML', lt_version='5.4.1')
null
lazy_load
""" Get pages from OneNote notebooks. Returns: A list of Documents with attributes: - page_content - metadata - title """ self._auth() try: from bs4 import BeautifulSoup except ImportError: raise ImportError( 'beaut...
def lazy_load(self) ->Iterator[Document]: """ Get pages from OneNote notebooks. Returns: A list of Documents with attributes: - page_content - metadata - title """ self._auth() try: from bs4 import BeautifulSoup...
Get pages from OneNote notebooks. Returns: A list of Documents with attributes: - page_content - metadata - title
scrape_page
from urllib.parse import urljoin from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'lxml') anchors = soup.find_all('a') if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get('href', '')) for anchor in anchors] else: links = [anchor.get('href', '') for anchor in anchors] ...
@staticmethod def scrape_page(page: Any, html_content: str, absolute_urls: bool) ->str: from urllib.parse import urljoin from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'lxml') anchors = soup.find_all('a') if absolute_urls: base_url = page.url links = [urljoin(base_u...
null
test_hippo
docsearch = _hippo_from_texts() output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo')]
def test_hippo() ->None: docsearch = _hippo_from_texts() output = docsearch.similarity_search('foo', k=1) assert output == [Document(page_content='foo')]
null
validate_environment
values['baichuan_api_base'] = get_from_dict_or_env(values, 'baichuan_api_base', 'BAICHUAN_API_BASE', DEFAULT_API_BASE) values['baichuan_api_key'] = convert_to_secret_str(get_from_dict_or_env( values, 'baichuan_api_key', 'BAICHUAN_API_KEY')) values['baichuan_secret_key'] = convert_to_secret_str(get_from_dict_or_...
@root_validator() def validate_environment(cls, values: Dict) ->Dict: values['baichuan_api_base'] = get_from_dict_or_env(values, 'baichuan_api_base', 'BAICHUAN_API_BASE', DEFAULT_API_BASE) values['baichuan_api_key'] = convert_to_secret_str(get_from_dict_or_env (values, 'baichuan_api_key', 'BAICH...
null
embed_query
"""Call out to LocalAI's embedding endpoint for embedding query text. Args: text: The text to embed. Returns: Embedding for the text. """ embedding = self._embedding_func(text, engine=self.deployment) return embedding
def embed_query(self, text: str) ->List[float]: """Call out to LocalAI's embedding endpoint for embedding query text. Args: text: The text to embed. Returns: Embedding for the text. """ embedding = self._embedding_func(text, engine=self.deployment) return em...
Call out to LocalAI's embedding endpoint for embedding query text. Args: text: The text to embed. Returns: Embedding for the text.
read_file
""" Read a file from this agent's branch, defined by self.active_branch, which supports PR branches. Parameters: file_path(str): the file path Returns: str: The file decoded as a string, or an error message if not found """ try: file = self.github_repo...
def read_file(self, file_path: str) ->str: """ Read a file from this agent's branch, defined by self.active_branch, which supports PR branches. Parameters: file_path(str): the file path Returns: str: The file decoded as a string, or an error message if not fou...
Read a file from this agent's branch, defined by self.active_branch, which supports PR branches. Parameters: file_path(str): the file path Returns: str: The file decoded as a string, or an error message if not found
evaluation_name
return 'COT Contextual Accuracy'
@property def evaluation_name(self) ->str: return 'COT Contextual Accuracy'
null
_get_llm
return AzureOpenAI(deployment_name=DEPLOYMENT_NAME, openai_api_version= OPENAI_API_VERSION, openai_api_base=OPENAI_API_BASE, openai_api_key= OPENAI_API_KEY, **kwargs)
def _get_llm(**kwargs: Any) ->AzureOpenAI: return AzureOpenAI(deployment_name=DEPLOYMENT_NAME, openai_api_version= OPENAI_API_VERSION, openai_api_base=OPENAI_API_BASE, openai_api_key =OPENAI_API_KEY, **kwargs)
null
parse_result
result = super().parse_result(result) return getattr(result, self.attr_name)
def parse_result(self, result: List[Generation], *, partial: bool=False) ->Any: result = super().parse_result(result) return getattr(result, self.attr_name)
null
test_ids_backwards_compatibility
"""Test that ids are backwards compatible.""" db = DeepLake(dataset_path='mem://test_path', embedding_function= FakeEmbeddings(), tensor_params=[{'name': 'ids', 'htype': 'text'}, { 'name': 'text', 'htype': 'text'}, {'name': 'embedding', 'htype': 'embedding'}, {'name': 'metadata', 'htype': 'json'}]) db.vecto...
def test_ids_backwards_compatibility() ->None: """Test that ids are backwards compatible.""" db = DeepLake(dataset_path='mem://test_path', embedding_function= FakeEmbeddings(), tensor_params=[{'name': 'ids', 'htype': 'text'}, {'name': 'text', 'htype': 'text'}, {'name': 'embedding', 'htype': ...
Test that ids are backwards compatible.
_get_default_llm_chain
from langchain.chains.llm import LLMChain return LLMChain(llm=OpenAI(), prompt=prompt)
def _get_default_llm_chain(prompt: BasePromptTemplate) ->Any: from langchain.chains.llm import LLMChain return LLMChain(llm=OpenAI(), prompt=prompt)
null
_add_vectors
"""Add vectors to the Xata database.""" rows: List[Dict[str, Any]] = [] for idx, embedding in enumerate(vectors): row = {'content': documents[idx].page_content, 'embedding': embedding} if ids: row['id'] = ids[idx] for key, val in documents[idx].metadata.items(): if key not in ['id', 'content...
def _add_vectors(self, vectors: List[List[float]], documents: List[Document ], ids: Optional[List[str]]=None) ->List[str]: """Add vectors to the Xata database.""" rows: List[Dict[str, Any]] = [] for idx, embedding in enumerate(vectors): row = {'content': documents[idx].page_content, 'embedding':...
Add vectors to the Xata database.
_resolve
"""Improve upon the best idea as chosen in critique step & return it.""" llm = self.resolver_llm if self.resolver_llm else self.llm prompt = self.resolve_prompt().format_prompt(**self.history. resolve_prompt_inputs()) callbacks = run_manager.handlers if run_manager else None if llm: resolution = self._get_text_...
def _resolve(self, stop: Optional[List[str]]=None, run_manager: Optional[ CallbackManagerForChainRun]=None) ->str: """Improve upon the best idea as chosen in critique step & return it.""" llm = self.resolver_llm if self.resolver_llm else self.llm prompt = self.resolve_prompt().format_prompt(**self.histo...
Improve upon the best idea as chosen in critique step & return it.
set_verbose
"""Set a new value for the `verbose` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing verbose from langchain root module is no longer supported' ) langchain.verbose = value except ImportError: ...
def set_verbose(value: bool) ->None: """Set a new value for the `verbose` global setting.""" try: import langchain with warnings.catch_warnings(): warnings.filterwarnings('ignore', message= 'Importing verbose from langchain root module is no longer supported' ...
Set a new value for the `verbose` global setting.
parse_partial_json
"""Parse a JSON string that may be missing closing braces. Args: s: The JSON string to parse. strict: Whether to use strict parsing. Defaults to False. Returns: The parsed JSON object as a Python dictionary. """ try: return json.loads(s, strict=strict) except json.JSONDecodeErr...
def parse_partial_json(s: str, *, strict: bool=False) ->Any: """Parse a JSON string that may be missing closing braces. Args: s: The JSON string to parse. strict: Whether to use strict parsing. Defaults to False. Returns: The parsed JSON object as a Python dictionary. """ t...
Parse a JSON string that may be missing closing braces. Args: s: The JSON string to parse. strict: Whether to use strict parsing. Defaults to False. Returns: The parsed JSON object as a Python dictionary.
on_retriever_end
"""Run when Retriever ends running."""
def on_retriever_end(self, documents: Sequence[Document], *, run_id: UUID, parent_run_id: Optional[UUID]=None, **kwargs: Any) ->Any: """Run when Retriever ends running."""
Run when Retriever ends running.
test_search
"""Test for Searching issues on JIRA""" jql = 'project = TP' jira = JiraAPIWrapper() output = jira.run('jql', jql) assert 'issues' in output
def test_search() ->None: """Test for Searching issues on JIRA""" jql = 'project = TP' jira = JiraAPIWrapper() output = jira.run('jql', jql) assert 'issues' in output
Test for Searching issues on JIRA
test_api_key_masked_when_passed_from_env
"""Test initialization with an API key provided via an env variable""" monkeypatch.setenv('MINIMAX_API_KEY', 'secret-api-key') monkeypatch.setenv('MINIMAX_GROUP_ID', 'group_id') llm = Minimax() print(llm.minimax_api_key, end='') captured = capsys.readouterr() assert captured.out == '**********'
def test_api_key_masked_when_passed_from_env(monkeypatch: MonkeyPatch, capsys: CaptureFixture) ->None: """Test initialization with an API key provided via an env variable""" monkeypatch.setenv('MINIMAX_API_KEY', 'secret-api-key') monkeypatch.setenv('MINIMAX_GROUP_ID', 'group_id') llm = Minimax() ...
Test initialization with an API key provided via an env variable
on_chain_error
"""Run when chain errors.""" self.metrics['step'] += 1 self.metrics['errors'] += 1
def on_chain_error(self, error: BaseException, **kwargs: Any) ->None: """Run when chain errors.""" self.metrics['step'] += 1 self.metrics['errors'] += 1
Run when chain errors.
test_azure_openai_embedding_with_empty_string
"""Test openai embeddings with empty string.""" import openai document = ['', 'abc'] embedding = _get_embeddings() 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]['embed...
@pytest.mark.skip(reason='Unblock scheduled testing. TODO: fix.') def test_azure_openai_embedding_with_empty_string() ->None: """Test openai embeddings with empty string.""" import openai document = ['', 'abc'] embedding = _get_embeddings() output = embedding.embed_documents(document) assert len...
Test openai embeddings with empty string.
test_clickhouse_with_metadatas
"""Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] config = ClickhouseSettings() config.table = 'test_clickhouse_with_metadatas' docsearch = Clickhouse.from_texts(texts=texts, embedding=FakeEmbeddings(), config=config, metadatas=met...
def test_clickhouse_with_metadatas() ->None: """Test end to end construction and search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': str(i)} for i in range(len(texts))] config = ClickhouseSettings() config.table = 'test_clickhouse_with_metadatas' docsearch = Clickhouse.from_texts(text...
Test end to end construction and search.
_resolve_prompt
expected_input_vars = {'input', 'output', 'criteria', 'reference'} prompt_ = prompt or PROMPT_WITH_REFERENCES if expected_input_vars != set(prompt_.input_variables): raise ValueError( f'Input variables should be {expected_input_vars}, but got {prompt_.input_variables}' ) return prompt_
@classmethod def _resolve_prompt(cls, prompt: Optional[BasePromptTemplate]=None ) ->BasePromptTemplate: expected_input_vars = {'input', 'output', 'criteria', 'reference'} prompt_ = prompt or PROMPT_WITH_REFERENCES if expected_input_vars != set(prompt_.input_variables): raise ValueError( ...
null
__init__
""" Initialize the transformer. This checks if the BeautifulSoup4 package is installed. If not, it raises an ImportError. """ try: import bs4 except ImportError: raise ImportError( 'BeautifulSoup4 is required for BeautifulSoupTransformer. Please install it with `pip inst...
def __init__(self) ->None: """ Initialize the transformer. This checks if the BeautifulSoup4 package is installed. If not, it raises an ImportError. """ try: import bs4 except ImportError: raise ImportError( 'BeautifulSoup4 is required for Beautif...
Initialize the transformer. This checks if the BeautifulSoup4 package is installed. If not, it raises an ImportError.
max_tokens_for_prompt
"""Calculate the maximum number of tokens possible to generate for a prompt. Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. Example: .. code-block:: python max_tokens = opena...
def max_tokens_for_prompt(self, prompt: str) ->int: """Calculate the maximum number of tokens possible to generate for a prompt. Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. Example: .....
Calculate the maximum number of tokens possible to generate for a prompt. Args: prompt: The prompt to pass into the model. Returns: The maximum number of tokens to generate for a prompt. Example: .. code-block:: python max_tokens = openai.max_token_for_prompt("Tell me a joke.")
test_sqlitevss_add_extra
"""Test end to end construction and MRR search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _sqlite_vss_from_texts(metadatas=metadatas) docsearch.add_texts(texts, metadatas) output = docsearch.similarity_search('foo', k=10) assert len(output) == 6
@pytest.mark.requires('sqlite-vss') def test_sqlitevss_add_extra() ->None: """Test end to end construction and MRR search.""" texts = ['foo', 'bar', 'baz'] metadatas = [{'page': i} for i in range(len(texts))] docsearch = _sqlite_vss_from_texts(metadatas=metadatas) docsearch.add_texts(texts, metadata...
Test end to end construction and MRR search.
test_elasticsearch_with_user_agent
"""Test to make sure the user-agent is set correctly.""" texts = ['foo', 'bob', 'baz'] ElasticsearchStore.from_texts(texts, FakeEmbeddings(), es_connection= es_client, index_name=index_name) user_agent = es_client.transport.requests[0]['headers']['User-Agent'] pattern = '^langchain-py-vs/\\d+\\.\\d+\\.\\d+$' match ...
def test_elasticsearch_with_user_agent(self, es_client: Any, index_name: str ) ->None: """Test to make sure the user-agent is set correctly.""" texts = ['foo', 'bob', 'baz'] ElasticsearchStore.from_texts(texts, FakeEmbeddings(), es_connection= es_client, index_name=index_name) user_agent = e...
Test to make sure the user-agent is set correctly.
test_invalid_api_key_error_handling
"""Test error handling with an invalid API key.""" with pytest.raises(GoogleGenerativeAIError): GoogleGenerativeAIEmbeddings(model=_MODEL, google_api_key='invalid_key' ).embed_query('Hello world')
def test_invalid_api_key_error_handling() ->None: """Test error handling with an invalid API key.""" with pytest.raises(GoogleGenerativeAIError): GoogleGenerativeAIEmbeddings(model=_MODEL, google_api_key='invalid_key' ).embed_query('Hello world')
Test error handling with an invalid API key.
embed_query
"""Embed a query using EdenAI. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._generate_embeddings([text])[0]
def embed_query(self, text: str) ->List[float]: """Embed a query using EdenAI. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._generate_embeddings([text])[0]
Embed a query using EdenAI. Args: text: The text to embed. Returns: Embeddings for the text.
main
print('Hello World!') return 0
def main() ->int: print('Hello World!') return 0
null
handle_data
"""Hook when handling data.""" stripped_data = data.strip() if self.depth == 0 and stripped_data not in (',', ''): self.success = False if stripped_data: self.data = stripped_data
def handle_data(self, data: str) ->None: """Hook when handling data.""" stripped_data = data.strip() if self.depth == 0 and stripped_data not in (',', ''): self.success = False if stripped_data: self.data = stripped_data
Hook when handling data.
test_paginated_texts
documents = ['foo bar', 'foo baz', 'bar foo', 'baz foo', 'bar bar', 'foo foo', 'baz baz', 'baz bar'] model = VertexAIEmbeddings() output = model.embed_documents(documents) assert len(output) == 8 assert len(output[0]) == 768 assert model.model_name == model.client._model_id
def test_paginated_texts() ->None: documents = ['foo bar', 'foo baz', 'bar foo', 'baz foo', 'bar bar', 'foo foo', 'baz baz', 'baz bar'] model = VertexAIEmbeddings() output = model.embed_documents(documents) assert len(output) == 8 assert len(output[0]) == 768 assert model.model_name == m...
null
_identifying_params
return self._default_params
@property def _identifying_params(self) ->Dict[str, Any]: return self._default_params
null
test_decorated_function_schema_equivalent
"""Test that a BaseTool without a schema meets expectations.""" @tool def structured_tool_input(arg1: int, arg2: bool, arg3: Optional[dict]=None ) ->str: """Return the arguments directly.""" return f'{arg1} {arg2} {arg3}' assert isinstance(structured_tool_input, BaseTool) assert structured_tool_input.args_s...
def test_decorated_function_schema_equivalent() ->None: """Test that a BaseTool without a schema meets expectations.""" @tool def structured_tool_input(arg1: int, arg2: bool, arg3: Optional[dict]=None ) ->str: """Return the arguments directly.""" return f'{arg1} {arg2} {arg3}' a...
Test that a BaseTool without a schema meets expectations.
on_llm_start
self._reset_llm_token_stream()
def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str]) ->None: self._reset_llm_token_stream()
null
test_default_no_scorer_specified
_, PROMPT = setup() chain_llm = FakeListChatModel(responses=['hey', '100']) chain = pick_best_chain.PickBest.from_llm(llm=chain_llm, prompt=PROMPT, feature_embedder=pick_best_chain.PickBestFeatureEmbedder(auto_embed= False, model=MockEncoder())) response = chain.run(User=rl_chain.BasedOn('Context'), action=rl_c...
@pytest.mark.requires('vowpal_wabbit_next', 'sentence_transformers') def test_default_no_scorer_specified() ->None: _, PROMPT = setup() chain_llm = FakeListChatModel(responses=['hey', '100']) chain = pick_best_chain.PickBest.from_llm(llm=chain_llm, prompt=PROMPT, feature_embedder=pick_best_chain.Pic...
null
from_llm_and_api_docs
"""Load chain from just an LLM and the api docs.""" get_request_chain = LLMChain(llm=llm, prompt=api_url_prompt) requests_wrapper = TextRequestsWrapper(headers=headers) get_answer_chain = LLMChain(llm=llm, prompt=api_response_prompt) return cls(api_request_chain=get_request_chain, api_answer_chain= get_answer_chain...
@classmethod def from_llm_and_api_docs(cls, llm: BaseLanguageModel, api_docs: str, headers: Optional[dict]=None, api_url_prompt: BasePromptTemplate= API_URL_PROMPT, api_response_prompt: BasePromptTemplate= API_RESPONSE_PROMPT, limit_to_domains: Optional[Sequence[str]]=tuple(), **kwargs: Any) ->APIChain:...
Load chain from just an LLM and the api docs.
__init__
"""Initialize with a list of loaders""" self.loaders = loaders
def __init__(self, loaders: List): """Initialize with a list of loaders""" self.loaders = loaders
Initialize with a list of loaders
save_deanonymizer_mapping
"""Save the deanonymizer mapping to a JSON or YAML file. Args: file_path: Path to file to save the mapping to. Example: .. code-block:: python anonymizer.save_deanonymizer_mapping(file_path="path/mapping.json") """ save_path = Path(file_path) if save_path.suffi...
def save_deanonymizer_mapping(self, file_path: Union[Path, str]) ->None: """Save the deanonymizer mapping to a JSON or YAML file. Args: file_path: Path to file to save the mapping to. Example: .. code-block:: python anonymizer.save_deanonymizer_mapping(file_path="p...
Save the deanonymizer mapping to a JSON or YAML file. Args: file_path: Path to file to save the mapping to. Example: .. code-block:: python anonymizer.save_deanonymizer_mapping(file_path="path/mapping.json")
__init__
"""Initialize with blackboard course url. The BbRouter cookie is required for most blackboard courses. Args: blackboard_course_url: Blackboard course url. bbrouter: BbRouter cookie. load_all_recursively: If True, load all documents recursively. basic_aut...
def __init__(self, blackboard_course_url: str, bbrouter: str, load_all_recursively: bool=True, basic_auth: Optional[Tuple[str, str]]= None, cookies: Optional[dict]=None, continue_on_failure: bool=False): """Initialize with blackboard course url. The BbRouter cookie is required for most blackboard c...
Initialize with blackboard course url. The BbRouter cookie is required for most blackboard courses. Args: blackboard_course_url: Blackboard course url. bbrouter: BbRouter cookie. load_all_recursively: If True, load all documents recursively. basic_auth: Basic auth credentials. cookies: Cookies. ...
_get_document
"""Fetch content from page and return Document.""" page_content_raw = soup.find(self.content_selector) if not page_content_raw: return None content = page_content_raw.get_text(separator='\n').strip() title_if_exists = page_content_raw.find('h1') title = title_if_exists.text if title_if_exists else '' metadata = {'s...
def _get_document(self, soup: Any, custom_url: Optional[str]=None) ->Optional[ Document]: """Fetch content from page and return Document.""" page_content_raw = soup.find(self.content_selector) if not page_content_raw: return None content = page_content_raw.get_text(separator='\n').strip() ...
Fetch content from page and return Document.
get_index_name
"""Returns the index name Returns: Returns the index name """ return self._index_name
def get_index_name(self) ->str: """Returns the index name Returns: Returns the index name """ return self._index_name
Returns the index name Returns: Returns the index name
_convert_one_message_to_text
content = cast(str, message.content) if isinstance(message, ChatMessage): message_text = f'\n\n{message.role.capitalize()}: {content}' elif isinstance(message, HumanMessage): message_text = f'{human_prompt} {content}' elif isinstance(message, AIMessage): message_text = f'{ai_prompt} {content}' elif isinstan...
def _convert_one_message_to_text(message: BaseMessage, human_prompt: str, ai_prompt: str) ->str: content = cast(str, message.content) if isinstance(message, ChatMessage): message_text = f'\n\n{message.role.capitalize()}: {content}' elif isinstance(message, HumanMessage): message_text = f...
null
get_schema
"""Returns the schema of the HugeGraph database""" return self.schema
@property def get_schema(self) ->str: """Returns the schema of the HugeGraph database""" return self.schema
Returns the schema of the HugeGraph database
elapsed
"""Get the elapsed time of a run. Args: run: any object with a start_time and end_time attribute. Returns: A string with the elapsed time in seconds or milliseconds if time is less than a second. """ elapsed_time = run.end_time - run.start_time milliseconds = elapsed_time.tota...
def elapsed(run: Any) ->str: """Get the elapsed time of a run. Args: run: any object with a start_time and end_time attribute. Returns: A string with the elapsed time in seconds or milliseconds if time is less than a second. """ elapsed_time = run.end_time - run.start_...
Get the elapsed time of a run. Args: run: any object with a start_time and end_time attribute. Returns: A string with the elapsed time in seconds or milliseconds if time is less than a second.
mock_confluence
with patch('atlassian.Confluence') as mock_confluence: yield mock_confluence
@pytest.fixture def mock_confluence(): with patch('atlassian.Confluence') as mock_confluence: yield mock_confluence
null
__init__
"""Initialize with Dingo client.""" try: import dingodb except ImportError: raise ImportError( 'Could not import dingo python package. Please install it with `pip install dingodb.' ) host = host if host is not None else ['172.20.31.10:13000'] if client is not None: dingo_client = client else...
def __init__(self, embedding: Embeddings, text_key: str, *, client: Any= None, index_name: Optional[str]=None, dimension: int=1024, host: Optional[List[str]]=None, user: str='root', password: str='123123', self_id: bool=False): """Initialize with Dingo client.""" try: import dingodb exce...
Initialize with Dingo client.
_import_bibtex
from langchain_community.utilities.bibtex import BibtexparserWrapper return BibtexparserWrapper
def _import_bibtex() ->Any: from langchain_community.utilities.bibtex import BibtexparserWrapper return BibtexparserWrapper
null
requires_input
return False
@property def requires_input(self) ->bool: return False
null
get_lc_namespace
"""Get the namespace of the langchain object.""" return ['langchain', 'llms', 'bedrock']
@classmethod def get_lc_namespace(cls) ->List[str]: """Get the namespace of the langchain object.""" return ['langchain', 'llms', 'bedrock']
Get the namespace of the langchain object.
test_google_documentai_warehoure_retriever
"""In order to run this test, you should provide a project_id and user_ldap. Example: export USER_LDAP=... export PROJECT_NUMBER=... """ project_number = os.environ['PROJECT_NUMBER'] user_ldap = os.environ['USER_LDAP'] docai_wh_retriever = GoogleDocumentAIWarehouseRetriever(project_number= project_...
def test_google_documentai_warehoure_retriever() ->None: """In order to run this test, you should provide a project_id and user_ldap. Example: export USER_LDAP=... export PROJECT_NUMBER=... """ project_number = os.environ['PROJECT_NUMBER'] user_ldap = os.environ['USER_LDAP'] docai_wh_re...
In order to run this test, you should provide a project_id and user_ldap. Example: export USER_LDAP=... export PROJECT_NUMBER=...
test_criteria_eval_chain
chain = CriteriaEvalChain.from_llm(llm=FakeLLM(queries={'text': """The meaning of life Y"""}, sequential_responses=True), criteria={ 'my criterion': 'my criterion description'}) with pytest.warns(UserWarning, match=chain._skip_reference_warning): result = chain.evaluate_strings(prediction='my prediction', r...
def test_criteria_eval_chain() ->None: chain = CriteriaEvalChain.from_llm(llm=FakeLLM(queries={'text': 'The meaning of life\nY'}, sequential_responses=True), criteria={ 'my criterion': 'my criterion description'}) with pytest.warns(UserWarning, match=chain._skip_reference_warning): resul...
null
extract_functions_classes
raise NotImplementedError()
@abstractmethod def extract_functions_classes(self) ->List[str]: raise NotImplementedError()
null
_get_session_pool
assert all([self.username, self.password, self.address, self.port, self.space] ), 'Please provide all of the following parameters: username, password, address, port, space' from nebula3.Config import SessionPoolConfig from nebula3.Exception import AuthFailedException, InValidHostname from nebula3.gclient.net.Sessio...
def _get_session_pool(self) ->Any: assert all([self.username, self.password, self.address, self.port, self .space] ), 'Please provide all of the following parameters: username, password, address, port, space' from nebula3.Config import SessionPoolConfig from nebula3.Exception import AuthFail...
null
run
"""Run the API.""" if mode == 'get_task': output = self.get_task(query) elif mode == 'get_task_attribute': output = self.get_task_attribute(query) elif mode == 'get_teams': output = self.get_authorized_teams() elif mode == 'create_task': output = self.create_task(query) elif mode == 'create_list': o...
def run(self, mode: str, query: str) ->str: """Run the API.""" if mode == 'get_task': output = self.get_task(query) elif mode == 'get_task_attribute': output = self.get_task_attribute(query) elif mode == 'get_teams': output = self.get_authorized_teams() elif mode == 'create_t...
Run the API.
_get_root_referenced_parameter
"""Get the root reference or err.""" from openapi_pydantic import Reference parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) return parameter
def _get_root_referenced_parameter(self, ref: Reference) ->Parameter: """Get the root reference or err.""" from openapi_pydantic import Reference parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) retu...
Get the root reference or err.