id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
54
121
6cc2d514820a-10
"""Run when chain ends running.""" self.metrics["step"] += 1 self.metrics["chain_ends"] += 1 self.metrics["ends"] += 1 chain_ends = self.metrics["chain_ends"] resp: Dict[str, Any] = {} chain_output = ",".join([f"{k}={v}" for k, v in outputs.items()]) resp.update({...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-11
self.records["on_tool_start_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"tool_start_{tool_starts}") [docs] def on_tool_end(self, output: str, **kwargs: Any) -> None: """Run when tool ends running.""" self.metrics["step"] += 1 self...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-12
self.records["on_text_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"on_text_{text_ctr}") [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Run when agent ends running.""" self.metrics["step"] += 1 sel...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-13
self.mlflg.metrics(self.metrics, step=self.metrics["step"]) self.records["on_agent_action_records"].append(resp) self.records["action_records"].append(resp) self.mlflg.jsonf(resp, f"agent_action_{tool_starts}") def _create_session_analysis_df(self) -> Any: """Create a dataframe with ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-14
[ "step", "text", "token_usage_total_tokens", "token_usage_prompt_tokens", "token_usage_completion_tokens", ] + complexity_metrics_columns + visualizations_columns ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
6cc2d514820a-15
try: langchain_asset.save(langchain_asset_path) self.mlflg.artifact(langchain_asset_path) except ValueError: try: langchain_asset.save_agent(langchain_asset_path) self.mlflg.artifact(langchain_ass...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/mlflow_callback.html
44b25e5f9279-0
Source code for langchain.callbacks.argilla_callback import os import warnings from typing import Any, Dict, List, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from langchain.schema import AgentAction, AgentFinish, LLMResult [docs]class ArgillaCallbackHandler(BaseCallbackHandler): """Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-1
>>> argilla_callback = ArgillaCallbackHandler( ... dataset_name="my-dataset", ... workspace_name="my-workspace", ... api_url="http://localhost:6900", ... api_key="argilla.apikey", ... ) >>> llm = OpenAI( ... temperature=0, ... callb...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-2
`FeedbackDataset` lives in. Defaults to `None`, which means that either `ARGILLA_API_URL` environment variable or the default http://localhost:6900 will be used. api_key: API Key to connect to the Argilla Server. Defaults to `None`, which means that either `AR...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-3
" set, it will default to `argilla.apikey`." ), ) # Connect to Argilla with the provided credentials, if applicable try: rg.init( api_key=api_key, api_url=api_url, ) except Exception as e: raise Conne...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-4
" If the problem persists please report it to" " https://github.com/argilla-io/argilla/issues with the label" " `langchain`." ) from e supported_fields = ["prompt", "response"] if supported_fields != [field.name for field in self.dataset.fields]: r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-5
[docs] def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Do nothing when a new token is generated.""" pass [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Log records to Argilla when an LLM ends.""" # Do nothing if there's a parent_run_id...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-6
we don't log the same input prompt twice, once when the LLM starts and once when the chain starts. """ if "input" in inputs: self.prompts.update( { str(kwargs["parent_run_id"] or kwargs["run_id"]): ( inputs["input"] ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-7
self.dataset.add_records( records=[ { "fields": { "prompt": " ".join(prompts), # type: ignore "response": chain_output_val.strip(), }, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
44b25e5f9279-8
) -> None: """Do nothing when tool outputs an error.""" pass [docs] def on_text(self, text: str, **kwargs: Any) -> None: """Do nothing""" pass [docs] def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: """Do nothing""" pass
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/argilla_callback.html
0e3d28e4f822-0
Source code for langchain.callbacks.comet_ml_callback import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence, Union import langchain from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.utils import ( BaseMetad...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-1
"automated_readability_index": textstat.automated_readability_index(text), "dale_chall_readability_score": textstat.dale_chall_readability_score(text), "difficult_words": textstat.difficult_words(text), "linsear_write_formula": textstat.linsear_write_formula(text), "gunning_fog": textsta...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-2
stream_logs (bool): Whether to stream callback actions to Comet This handler will utilize the associated callback method and formats the input of each callback function with metadata regarding the state of LLM run, and adds the response to the list of records for both the {method}_records and action. It...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-3
"based on updates to `langchain`. Please report any issues to " "https://github.com/comet-ml/issue-tracking/issues with the tag " "`langchain`." ) self.comet_ml.LOGGER.warning(warning) self.callback_columns: list = [] self.action_records: list = [] self.co...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-4
self.llm_streams += 1 resp = self._init_resp() resp.update({"action": "on_llm_new_token", "token": token}) resp.update(self.get_custom_callback_meta()) self.action_records.append(resp) [docs] def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: """Run when LLM end...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-5
[docs] def on_llm_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: """Run when LLM errors.""" self.step += 1 self.errors += 1 [docs] def on_chain_start( self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any ) -> Non...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-6
if isinstance(chain_output_val, str): output_resp = deepcopy(resp) if self.stream_logs: self._log_stream(chain_output_val, resp, self.step) output_resp.update({chain_output_key: chain_output_val}) self.action_records.append(output_resp)...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-7
resp.update(self.get_custom_callback_meta()) if self.stream_logs: self._log_stream(output, resp, self.step) resp.update({"output": output}) self.action_records.append(resp) [docs] def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> N...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-8
"""Run on agent action.""" self.step += 1 self.tool_starts += 1 self.starts += 1 tool = action.tool tool_input = str(action.tool_input) log = action.log resp = self._init_resp() resp.update({"action": "on_agent_action", "log": log, "tool": tool}) r...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-9
return resp [docs] def flush_tracker( self, langchain_asset: Any = None, task_type: Optional[str] = "inference", workspace: Optional[str] = None, project_name: Optional[str] = "comet-langchain-demo", tags: Optional[Sequence] = None, name: Optional[str] = None, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-10
self.experiment.log_text(prompt, metadata=metadata, step=step) def _log_model(self, langchain_asset: Any) -> None: model_parameters = self._get_llm_parameters(langchain_asset) self.experiment.log_parameters(model_parameters, prefix="model") langchain_asset_path = Path(self.temp_dir.name, "mo...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-11
# Log the langchain low-level records as a JSON file directly self.experiment.log_asset_data( self.action_records, "langchain-action_records.json", metadata=metadata ) except Exception: self.comet_ml.LOGGER.warning( "Failed to log session data ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-12
) self.experiment.log_asset_data( html, name=f"langchain-viz-{visualization}-{idx}.html", metadata={"prompt": prompt}, step=idx, ) except Exception as e: ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
0e3d28e4f822-13
self.reset_callback_meta() self.temp_dir = tempfile.TemporaryDirectory() def _create_session_analysis_dataframe(self, langchain_asset: Any = None) -> dict: pd = import_pandas() llm_parameters = self._get_llm_parameters(langchain_asset) num_generations_per_prompt = llm_parameters.get(...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/comet_ml_callback.html
49dfeee28dca-0
Source code for langchain.callbacks.streamlit from __future__ import annotations from typing import TYPE_CHECKING, Optional from langchain.callbacks.base import BaseCallbackHandler from langchain.callbacks.streamlit.streamlit_callback_handler import ( LLMThoughtLabeler as LLMThoughtLabeler, ) from langchain.callbac...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
49dfeee28dca-1
If True, LLM thought expanders will be collapsed when completed. Defaults to True. thought_labeler An optional custom LLMThoughtLabeler instance. If unspecified, the handler will use the default thought labeling logic. Defaults to None. Returns ------- A new StreamlitCallbackHand...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit.html
081c917dc5f2-0
Source code for langchain.callbacks.streamlit.streamlit_callback_handler """Callback Handler that prints to streamlit.""" from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Union from langchain.callbacks.base import BaseCallbackHandler from ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-1
"""Return the markdown label for a new LLMThought that doesn't have an associated tool yet. """ return f"{THINKING_EMOJI} **Thinking...**" [docs] def get_tool_label(self, tool: ToolRecord, is_complete: bool) -> str: """Return the label for an LLMThought that has an associated ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-2
""" return f"{CHECKMARK_EMOJI} **Complete!**" class LLMThought: def __init__( self, parent_container: DeltaGenerator, labeler: LLMThoughtLabeler, expanded: bool, collapse_on_complete: bool, ): self._container = MutableExpander( parent_container...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-3
self._llm_token_writer_idx = self._container.markdown( self._llm_token_stream, index=self._llm_token_writer_idx ) def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: # `response` is the concatenation of all the tokens received by the LLM. # If we're receiving stream...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-4
def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._container.markdown("**Tool encountered an error...**") self._container.exception(error) def on_agent_action( self, action: AgentAction, color: Optional[str] = None, **kwargs: Any ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-5
*, max_thought_containers: int = 4, expand_new_thoughts: bool = True, collapse_completed_thoughts: bool = True, thought_labeler: Optional[LLMThoughtLabeler] = None, ): """Create a StreamlitCallbackHandler instance. Parameters ---------- parent_containe...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-6
self._collapse_completed_thoughts = collapse_completed_thoughts self._thought_labeler = thought_labeler or LLMThoughtLabeler() def _require_current_thought(self) -> LLMThought: """Return our current LLMThought. Raise an error if we have no current thought. """ if self._curren...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-7
self._current_thought = None def _prune_old_thought_containers(self) -> None: """If we have too many thoughts onscreen, move older thoughts to the 'history container.' """ while ( self._num_thought_containers > self._max_thought_containers and len(self._comple...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-8
) self._current_thought.on_llm_start(serialized, prompts) # We don't prune_old_thought_containers here, because our container won't # be visible until it has a child. def on_llm_new_token(self, token: str, **kwargs: Any) -> None: self._require_current_thought().on_llm_new_token(token...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
081c917dc5f2-9
) self._complete_current_thought() def on_tool_error( self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any ) -> None: self._require_current_thought().on_tool_error(error, **kwargs) self._prune_old_thought_containers() def on_text( self, text: str, ...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/streamlit/streamlit_callback_handler.html
50a8cc43f1f5-0
Source code for langchain.retrievers.zep from __future__ import annotations from typing import TYPE_CHECKING, Dict, List, Optional from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from zep_python import MemorySearchResult [docs]class ZepRetriever(BaseRetriever): """A Retriever implementati...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
50a8cc43f1f5-1
) for r in results if r.message ] [docs] def get_relevant_documents( self, query: str, metadata: Optional[Dict] = None ) -> List[Document]: from zep_python import MemorySearchPayload payload: MemorySearchPayload = MemorySearchPayload( text=query...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zep.html
d37c2f8845b4-0
Source code for langchain.retrievers.chatgpt_plugin_retriever from __future__ import annotations from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class ChatGPTPluginRetriever(BaseRetriever, BaseModel): url: str...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
d37c2f8845b4-1
) as response: res = await response.json() results = res["results"][0]["results"] docs = [] for d in results: content = d.pop("text") metadata = d.pop("metadata", d) if metadata.get("source_id"): metadata["source"] = metadata.po...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chatgpt_plugin_retriever.html
798a81eca712-0
Source code for langchain.retrievers.databerry from typing import List, Optional import aiohttp import requests from langchain.schema import BaseRetriever, Document [docs]class DataberryRetriever(BaseRetriever): """Retriever that uses the Databerry API.""" datastore_url: str top_k: Optional[int] api_key...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
798a81eca712-1
self.datastore_url, json={ "query": query, **({"topK": self.top_k} if self.top_k is not None else {}), }, headers={ "Content-Type": "application/json", **( {"Authorizat...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/databerry.html
69576b9724ba-0
Source code for langchain.retrievers.time_weighted_retriever """Retriever that combines embedding similarity with recency in retrieving values.""" import datetime from copy import deepcopy from typing import Any, Dict, List, Optional, Tuple from pydantic import BaseModel, Field from langchain.schema import BaseRetrieve...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
69576b9724ba-1
""" class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def _get_combined_score( self, document: Document, vector_relevance: Optional[float], current_time: datetime.datetime, ) -> float: """Return the combined sco...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
69576b9724ba-2
for doc in self.memory_stream[-self.k :] } # If a doc is considered salient, update the salience score docs_and_scores.update(self.get_salient_docs(query)) rescored_docs = [ (doc, self._get_combined_score(doc, relevance, current_time)) for doc, relevance in docs_a...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
69576b9724ba-3
doc.metadata["buffer_idx"] = len(self.memory_stream) + i self.memory_stream.extend(dup_docs) return self.vectorstore.add_documents(dup_docs, **kwargs) [docs] async def aadd_documents( self, documents: List[Document], **kwargs: Any ) -> List[str]: """Add documents to vectorstore.""...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/time_weighted_retriever.html
488c4e327251-0
Source code for langchain.retrievers.tfidf """TF-IDF Retriever. Largely based on https://github.com/asvskartheek/Text-Retrieval/blob/master/TF-IDF%20Search%20Engine%20(SKLEARN).ipynb""" from __future__ import annotations from typing import Any, Dict, Iterable, List, Optional from pydantic import BaseModel from langchai...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
488c4e327251-1
return cls(vectorizer=vectorizer, docs=docs, tfidf_array=tfidf_array, **kwargs) [docs] @classmethod def from_documents( cls, documents: Iterable[Document], *, tfidf_params: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> TFIDFRetriever: texts, metadatas = ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/tfidf.html
129763b8fd6d-0
Source code for langchain.retrievers.milvus """Milvus Retriever""" import warnings from typing import Any, Dict, List, Optional from langchain.embeddings.base import Embeddings from langchain.schema import BaseRetriever, Document from langchain.vectorstores.milvus import Milvus # TODO: Update to MilvusClient + Hybrid S...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html
129763b8fd6d-1
raise NotImplementedError def MilvusRetreiver(*args: Any, **kwargs: Any) -> MilvusRetriever: """Deprecated MilvusRetreiver. Please use MilvusRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: MilvusRetriever """ warnings.warn( "MilvusRetreiver will be...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/milvus.html
bd13a981659d-0
Source code for langchain.retrievers.arxiv from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.arxiv import ArxivAPIWrapper [docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper): """ It is effectively a wrapper for ArxivAPIWrapper. It wraps load() to ge...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html
cb932f461fbf-0
Source code for langchain.retrievers.docarray from enum import Enum from typing import Any, Dict, List, Optional, Union import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings from langchain.schema import BaseRetriever, Document from langchain.vectorstores.utils import maximal...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html
cb932f461fbf-1
"""Configuration for this pydantic object.""" arbitrary_types_allowed = True [docs] def get_relevant_documents(self, query: str) -> List[Document]: """Get documents relevant for a query. Args: query: string to find relevant documents for Returns: List of releva...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html
cb932f461fbf-2
if self.filters: query = ( self.index.build_query() # get empty query object .find( query=query_emb, search_field=search_field ) # add vector similarity search .filter(**filter_args) # add filter search .b...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html
cb932f461fbf-3
else getattr(doc, self.search_field) for doc in docs ], k=self.top_k, ) results = [self._docarray_to_langchain_doc(docs[idx]) for idx in mmr_selected] return results def _docarray_to_langchain_doc(self, doc: Union[Dict[str, Any], Any]) -> Document: ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/docarray.html
8b809e712593-0
Source code for langchain.retrievers.weaviate_hybrid_search """Wrapper around weaviate vector database.""" from __future__ import annotations from typing import Any, Dict, List, Optional from uuid import uuid4 from pydantic import Extra from langchain.docstore.document import Document from langchain.schema import BaseR...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
8b809e712593-1
"properties": [{"name": self._text_key, "dataType": ["text"]}], "vectorizer": "text2vec-openai", } if not self._client.schema.exists(self._index_name): self._client.schema.create_class(class_obj) [docs] class Config: """Configuration for this pydantic object.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
8b809e712593-2
if where_filter: query_obj = query_obj.with_where(where_filter) result = query_obj.with_hybrid(query, alpha=self.alpha).with_limit(self.k).do() if "errors" in result: raise ValueError(f"Error during query: {result['errors']}") docs = [] for res in result["data"]["...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html
f97ea17bf25a-0
Source code for langchain.retrievers.kendra import re from typing import Any, Dict, List, Literal, Optional from pydantic import BaseModel, Extra from langchain.docstore.document import Document from langchain.schema import BaseRetriever def clean_excerpt(excerpt: str) -> str: if not excerpt: return excerpt...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
f97ea17bf25a-1
def get_attribute_value(self) -> str: if not self.AdditionalAttributes: return "" if not self.AdditionalAttributes[0]: return "" else: return self.AdditionalAttributes[0].get_value_text() def get_excerpt(self) -> str: if ( self.Addition...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
f97ea17bf25a-2
Key: str Value: DocumentAttributeValue class RetrieveResultItem(BaseModel, extra=Extra.allow): Content: Optional[str] DocumentAttributes: Optional[List[DocumentAttribute]] = [] DocumentId: Optional[str] DocumentTitle: Optional[str] DocumentURI: Optional[str] Id: Optional[str] def get_exc...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
f97ea17bf25a-3
or ~/.aws/config files, which has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. top_k: No of results to return attribute_filter: Additional filtering of results bas...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
f97ea17bf25a-4
"Please install it with `pip install boto3`." ) except Exception as e: raise ValueError( "Could not load credentials to authenticate with AWS client. " "Please check that credentials in the specified " "profile name are valid." ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
f97ea17bf25a-5
"""Run search on Kendra index and get top k documents Example: .. code-block:: python docs = retriever.get_relevant_documents('This is my query') """ docs = self._kendra_query(query, self.top_k, self.attribute_filter) return docs [docs] async def aget_relevant_docu...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/kendra.html
e06e5440ee3c-0
Source code for langchain.retrievers.vespa_retriever """Wrapper for retrieving documents from Vespa.""" from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Sequence, Union from langchain.schema import BaseRetriever, Document if TYPE_CHECKING: from ves...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
e06e5440ee3c-1
docs.append(Document(page_content=page_content, metadata=metadata)) return docs [docs] def get_relevant_documents(self, query: str) -> List[Document]: body = self._query_body.copy() body["query"] = query return self._query(body) [docs] async def aget_relevant_documents(self, query:...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
e06e5440ee3c-2
document metadata. Defaults to empty tuple (). sources (Sequence[str] or "*" or None): Sources to retrieve from. Defaults to None. _filter (Optional[str]): Document filter condition expressed in YQL. Defaults to None. yql (Optional[str]): Full YQL quer...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/vespa_retriever.html
6b265ab5c2bf-0
Source code for langchain.retrievers.knn """KNN Retriever. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb""" from __future__ import annotations import concurrent.futures from typing import Any, List, Optional import numpy as np from pydantic import BaseModel from langchain.embedding...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html
6b265ab5c2bf-1
query_embeds = np.array(self.embeddings.embed_query(query)) # calc L2 norm index_embeds = self.index / np.sqrt((self.index**2).sum(1, keepdims=True)) query_embeds = query_embeds / np.sqrt((query_embeds**2).sum()) similarities = index_embeds.dot(query_embeds) sorted_ix = np.argsor...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/knn.html
a1924ce4a9bf-0
Source code for langchain.retrievers.llama_index from typing import Any, Dict, List, cast from pydantic import BaseModel, Field from langchain.schema import BaseRetriever, Document [docs]class LlamaIndexRetriever(BaseRetriever, BaseModel): """Question-answering with sources over an LlamaIndex data structure.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html
a1924ce4a9bf-1
graph: Any query_configs: List[Dict] = Field(default_factory=list) [docs] def get_relevant_documents(self, query: str) -> List[Document]: """Get documents relevant for a query.""" try: from llama_index.composability.graph import ( QUERY_CONFIG_TYPE, Com...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/llama_index.html
7e7ae4388417-0
Source code for langchain.retrievers.azure_cognitive_search """Retriever wrapper for Azure Cognitive Search.""" from __future__ import annotations import json from typing import Dict, List, Optional import aiohttp import requests from pydantic import BaseModel, Extra, root_validator from langchain.schema import BaseRet...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
7e7ae4388417-1
) values["api_key"] = get_from_dict_or_env( values, "api_key", "AZURE_COGNITIVE_SEARCH_API_KEY" ) return values def _build_search_url(self, query: str) -> str: base_url = f"https://{self.service_name}.search.windows.net/" endpoint_path = f"indexes/{self.index_name...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
7e7ae4388417-2
search_results = self._search(query) return [ Document(page_content=result.pop(self.content_key), metadata=result) for result in search_results ] [docs] async def aget_relevant_documents(self, query: str) -> List[Document]: search_results = await self._asearch(query) ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/azure_cognitive_search.html
53acd95d0c09-0
Source code for langchain.retrievers.contextual_compression """Retriever that wraps a base retriever and filters the results.""" from typing import List from pydantic import BaseModel, Extra from langchain.retrievers.document_compressors.base import ( BaseDocumentCompressor, ) from langchain.schema import BaseRetri...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
53acd95d0c09-1
compressed_docs = await self.base_compressor.acompress_documents( docs, query ) return list(compressed_docs) else: return []
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/contextual_compression.html
557bcb2e522a-0
Source code for langchain.retrievers.elastic_search_bm25 """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from typing import Any, Iterable, List from langchain.docstore.document import Document from langchain.schema import BaseRetriever [docs]class ElasticSearchBM25Retr...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
557bcb2e522a-1
self.index_name = index_name [docs] @classmethod def create( cls, elasticsearch_url: str, index_name: str, k1: float = 2.0, b: float = 0.75 ) -> ElasticSearchBM25Retriever: from elasticsearch import Elasticsearch # Create an Elasticsearch client instance es = Elasticsearch(ela...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
557bcb2e522a-2
raise ValueError( "Could not import elasticsearch python package. " "Please install it with `pip install elasticsearch`." ) requests = [] ids = [] for i, text in enumerate(texts): _id = str(uuid.uuid4()) request = { ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/elastic_search_bm25.html
0cb27424848f-0
Source code for langchain.retrievers.svm """SMV Retriever. Largely based on https://github.com/karpathy/randomfun/blob/master/knn_vs_svm.ipynb""" from __future__ import annotations import concurrent.futures from typing import Any, List, Optional import numpy as np from pydantic import BaseModel from langchain.embedding...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
0cb27424848f-1
query_embeds = np.array(self.embeddings.embed_query(query)) x = np.concatenate([query_embeds[None, ...], self.index]) y = np.zeros(x.shape[0]) y[0] = 1 clf = svm.LinearSVC( class_weight="balanced", verbose=False, max_iter=10000, tol=1e-6, C=0.1 ) clf.fit(x, y)...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/svm.html
7c5c7d771277-0
Source code for langchain.retrievers.pinecone_hybrid_search """Taken from: https://docs.pinecone.io/docs/hybrid-search""" import hashlib from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.schema import BaseRe...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
7c5c7d771277-1
for i in _iterator: # find end of batch i_end = min(i + batch_size, len(contexts)) # extract batch context_batch = contexts[i:i_end] batch_ids = ids[i:i_end] metadata_batch = ( metadatas[i:i_end] if metadatas else [{} for _ in context_batch] ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
7c5c7d771277-2
arbitrary_types_allowed = True [docs] def add_texts( self, texts: List[str], ids: Optional[List[str]] = None, metadatas: Optional[List[dict]] = None, ) -> None: create_index( texts, self.index, self.embeddings, self.sparse_en...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
7c5c7d771277-3
top_k=self.top_k, include_metadata=True, ) final_result = [] for res in result["matches"]: context = res["metadata"].pop("context") final_result.append( Document(page_content=context, metadata=res["metadata"]) ) # return sea...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pinecone_hybrid_search.html
0db63f20f3f0-0
Source code for langchain.retrievers.merger_retriever from typing import List from langchain.schema import BaseRetriever, Document [docs]class MergerRetriever(BaseRetriever): """ This class merges the results of multiple retrievers. Args: retrievers: A list of retrievers to merge. """ def __...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html
0db63f20f3f0-1
Returns: A list of merged documents. """ # Get the results of all retrievers. retriever_docs = [ retriever.get_relevant_documents(query) for retriever in self.retrievers ] # Merge the results of the retrievers. merged_documents = [] max_doc...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/merger_retriever.html
592182c4a717-0
Source code for langchain.retrievers.wikipedia from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaRetriever(BaseRetriever, WikipediaAPIWrapper): """ It is effectively a wrapper for WikipediaAPIWrapper. ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/wikipedia.html
5b5249fc3718-0
Source code for langchain.retrievers.metal from typing import Any, List, Optional from langchain.schema import BaseRetriever, Document [docs]class MetalRetriever(BaseRetriever): """Retriever that uses the Metal API.""" def __init__(self, client: Any, params: Optional[dict] = None): from metal_sdk.metal ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html
e9064c86de22-0
Source code for langchain.retrievers.pupmed from typing import List from langchain.schema import BaseRetriever, Document from langchain.utilities.pupmed import PubMedAPIWrapper [docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper): """ It is effectively a wrapper for PubMedAPIWrapper. It wraps load()...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/pupmed.html
3b6cef46ca82-0
Source code for langchain.retrievers.remote_retriever from typing import List, Optional import aiohttp import requests from pydantic import BaseModel from langchain.schema import BaseRetriever, Document [docs]class RemoteLangChainRetriever(BaseRetriever, BaseModel): url: str headers: Optional[dict] = None i...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/remote_retriever.html
afce1c8babc6-0
Source code for langchain.retrievers.zilliz """Zilliz Retriever""" import warnings from typing import Any, Dict, List, Optional from langchain.embeddings.base import Embeddings from langchain.schema import BaseRetriever, Document from langchain.vectorstores.zilliz import Zilliz # TODO: Update to ZillizClient + Hybrid S...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html
afce1c8babc6-1
raise NotImplementedError def ZillizRetreiver(*args: Any, **kwargs: Any) -> ZillizRetriever: """ Deprecated ZillizRetreiver. Please use ZillizRetriever ('i' before 'e') instead. Args: *args: **kwargs: Returns: ZillizRetriever """ warnings.warn( "ZillizRetreiver wi...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/zilliz.html
b0635f6496b6-0
Source code for langchain.retrievers.self_query.base """Retriever that generates and executes structured queries over its own data source.""" from typing import Any, Dict, List, Optional, Type, cast from pydantic import BaseModel, Field, root_validator from langchain import LLMChain from langchain.base_language import ...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
b0635f6496b6-1
if vectorstore_cls not in BUILTIN_TRANSLATORS: raise ValueError( f"Self query retriever with Vector Store type {vectorstore_cls}" f" not supported." ) if isinstance(vectorstore, Qdrant): return QdrantTranslator(metadata_key=vectorstore.metadata_payload_key) elif i...
https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html