[docs]defclean_excerpt(excerpt:str)->str:"""Clean an excerpt from Kendra. Args: excerpt: The excerpt to clean. Returns: The cleaned excerpt. """ifnotexcerpt:returnexcerptres=re.sub(r"\s+"," ",excerpt).replace("...","")returnres
[docs]defcombined_text(item:"ResultItem")->str:"""Combine a ResultItem title and excerpt into a single string. Args: item: the ResultItem of a Kendra search. Returns: A combined text of the title and excerpt of the given item. """text=""title=item.get_title()iftitle:text+=f"Document Title: {title}\n"excerpt=clean_excerpt(item.get_excerpt())ifexcerpt:text+=f"Document Excerpt: \n{excerpt}\n"returntext
DocumentAttributeValueType=Union[str,int,List[str],None]"""Possible types of a DocumentAttributeValue.Dates are also represented as str."""# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classHighlight(BaseModel,extra="allow"):# type: ignore[call-arg]"""Information that highlights the keywords in the excerpt."""BeginOffset:int"""The zero-based location in the excerpt where the highlight starts."""EndOffset:int"""The zero-based location in the excerpt where the highlight ends."""TopAnswer:Optional[bool]"""Indicates whether the result is the best one."""Type:Optional[str]"""The highlight type: STANDARD or THESAURUS_SYNONYM."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classTextWithHighLights(BaseModel,extra="allow"):# type: ignore[call-arg]"""Text with highlights."""Text:str"""The text."""Highlights:Optional[Any]"""The highlights."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classAdditionalResultAttributeValue(# type: ignore[call-arg]BaseModel,extra="allow"):"""Value of an additional result attribute."""TextWithHighlightsValue:TextWithHighLights"""The text with highlights value."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classAdditionalResultAttribute(BaseModel,extra="allow"):# type: ignore[call-arg]"""Additional result attribute."""Key:str"""The key of the attribute."""ValueType:Literal["TEXT_WITH_HIGHLIGHTS_VALUE"]"""The type of the value."""Value:AdditionalResultAttributeValue"""The value of the attribute."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classDocumentAttributeValue(BaseModel,extra="allow"):# type: ignore[call-arg]"""Value of a document attribute."""DateValue:Optional[str]=None"""The date expressed as an ISO 8601 string."""LongValue:Optional[int]=None"""The long value."""StringListValue:Optional[List[str]]=None"""The string list value."""StringValue:Optional[str]=None"""The string value."""@propertydefvalue(self)->DocumentAttributeValueType:"""The only defined document attribute value or None. According to Amazon Kendra, you can only provide one value for a document attribute. """ifself.DateValue:returnself.DateValueifself.LongValue:returnself.LongValueifself.StringListValue:returnself.StringListValueifself.StringValue:returnself.StringValuereturnNone
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classDocumentAttribute(BaseModel,extra="allow"):# type: ignore[call-arg]"""Document attribute."""Key:str"""The key of the attribute."""Value:DocumentAttributeValue"""The value of the attribute."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classResultItem(BaseModel,ABC,extra="allow"):# type: ignore[call-arg]"""Base class of a result item."""Id:Optional[str]"""The ID of the relevant result item."""DocumentId:Optional[str]"""The document ID."""DocumentURI:Optional[str]"""The document URI."""DocumentAttributes:Optional[List[DocumentAttribute]]=[]"""The document attributes."""ScoreAttributes:Optional[dict]"""The kendra score confidence"""
[docs]defto_doc(self,page_content_formatter:Callable[["ResultItem"],str]=combined_text)->Document:"""Converts this item to a Document."""page_content=page_content_formatter(self)metadata=self.get_additional_metadata()metadata.update({"result_id":self.Id,"document_id":self.DocumentId,"source":self.DocumentURI,"title":self.get_title(),"excerpt":self.get_excerpt(),"document_attributes":self.get_document_attributes_dict(),"score":self.get_score_attribute(),})returnDocument(page_content=page_content,metadata=metadata)
[docs]classQueryResultItem(ResultItem):"""Query API result item."""DocumentTitle:TextWithHighLights"""The document title."""FeedbackToken:Optional[str]"""Identifies a particular result from a particular query."""Format:Optional[str]""" If the Type is ANSWER, then format is either: * TABLE: a table excerpt is returned in TableExcerpt; * TEXT: a text excerpt is returned in DocumentExcerpt. """Type:Optional[str]"""Type of result: DOCUMENT or QUESTION_ANSWER or ANSWER"""AdditionalAttributes:Optional[List[AdditionalResultAttribute]]=[]"""One or more additional attributes associated with the result."""DocumentExcerpt:Optional[TextWithHighLights]"""Excerpt of the document text."""
[docs]classRetrieveResultItem(ResultItem):"""Retrieve API result item."""DocumentTitle:Optional[str]"""The document title."""Content:Optional[str]"""The content of the item."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classQueryResult(BaseModel,extra="allow"):# type: ignore[call-arg]"""`Amazon Kendra Query API` search result. It is composed of: * Relevant suggested answers: either a text excerpt or table excerpt. * Matching FAQs or questions-answer from your FAQ file. * Documents including an excerpt of each document with its title. """ResultItems:List[QueryResultItem]"""The result items."""
# Unexpected keyword argument "extra" for "__init_subclass__" of "object"
[docs]classRetrieveResult(BaseModel,extra="allow"):# type: ignore[call-arg]"""`Amazon Kendra Retrieve API` search result. It is composed of: * relevant passages or text excerpts given an input query. """QueryId:str"""The ID of the query."""ResultItems:List[RetrieveResultItem]"""The result items."""
[docs]@deprecated(since="0.3.16",removal="1.0",alternative_import="langchain_aws.AmazonKendraRetriever",)classAmazonKendraRetriever(BaseRetriever):"""`Amazon Kendra Index` retriever. Args: index_id: Kendra index id region_name: The aws region e.g., `us-west-2`. Fallsback to AWS_DEFAULT_REGION env variable or region specified in ~/.aws/config. credentials_profile_name: The name of the profile in the ~/.aws/credentials 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 based on metadata See: https://docs.aws.amazon.com/kendra/latest/APIReference document_relevance_override_configurations: Overrides relevance tuning configurations of fields/attributes set at the index level See: https://docs.aws.amazon.com/kendra/latest/APIReference page_content_formatter: generates the Document page_content allowing access to all result item attributes. By default, it uses the item's title and excerpt. client: boto3 client for Kendra user_context: Provides information about the user context See: https://docs.aws.amazon.com/kendra/latest/APIReference Example: .. code-block:: python retriever = AmazonKendraRetriever( index_id="c0806df7-e76b-4bce-9b5c-d5582f6b1a03" ) """index_id:strregion_name:Optional[str]=Nonecredentials_profile_name:Optional[str]=Nonetop_k:int=3attribute_filter:Optional[Dict]=Nonedocument_relevance_override_configurations:Optional[List[Dict]]=Nonepage_content_formatter:Callable[[ResultItem],str]=combined_textclient:Anyuser_context:Optional[Dict]=Nonemin_score_confidence:Annotated[Optional[float],Field(ge=0.0,le=1.0)]
[docs]@validator("top_k")defvalidate_top_k(cls,value:int)->int:ifvalue<0:raiseValueError(f"top_k ({value}) cannot be negative.")returnvalue
@model_validator(mode="before")@classmethoddefcreate_client(cls,values:Dict[str,Any])->Any:top_k=values.get("top_k")iftop_kisnotNoneandtop_k<0:raiseValueError(f"top_k ({top_k}) cannot be negative.")ifvalues.get("client")isnotNone:returnvaluestry:importboto3ifvalues.get("credentials_profile_name"):session=boto3.Session(profile_name=values["credentials_profile_name"])else:# use default credentialssession=boto3.Session()client_params={}ifvalues.get("region_name"):client_params["region_name"]=values["region_name"]values["client"]=session.client("kendra",**client_params)returnvaluesexceptImportError:raiseImportError("Could not import boto3 python package. ""Please install it with `pip install boto3`.")exceptExceptionase:raiseValueError("Could not load credentials to authenticate with AWS client. ""Please check that credentials in the specified ""profile name are valid.")fromedef_kendra_query(self,query:str)->Sequence[ResultItem]:kendra_kwargs={"IndexId":self.index_id,# truncate the query to ensure that# there is no validation exception from Kendra."QueryText":query.strip()[0:999],"PageSize":self.top_k,}ifself.attribute_filterisnotNone:kendra_kwargs["AttributeFilter"]=self.attribute_filterifself.document_relevance_override_configurationsisnotNone:kendra_kwargs["DocumentRelevanceOverrideConfigurations"]=(self.document_relevance_override_configurations)ifself.user_contextisnotNone:kendra_kwargs["UserContext"]=self.user_contextresponse=self.client.retrieve(**kendra_kwargs)r_result=RetrieveResult.parse_obj(response)ifr_result.ResultItems:returnr_result.ResultItems# Retrieve API returned 0 results, fall back to Query APIresponse=self.client.query(**kendra_kwargs)q_result=QueryResult.parse_obj(response)returnq_result.ResultItemsdef_get_top_k_docs(self,result_items:Sequence[ResultItem])->List[Document]:top_docs=[item.to_doc(self.page_content_formatter)foriteminresult_items[:self.top_k]]returntop_docsdef_filter_by_score_confidence(self,docs:List[Document])->List[Document]:""" Filter out the records that have a score confidence greater than the required threshold. """ifnotself.min_score_confidence:returndocsfiltered_docs=[itemforitemindocsif(item.metadata.get("score")isnotNoneandisinstance(item.metadata["score"],str)andKENDRA_CONFIDENCE_MAPPING.get(item.metadata["score"],0.0)>=self.min_score_confidence)]returnfiltered_docsdef_get_relevant_documents(self,query:str,*,run_manager:CallbackManagerForRetrieverRun,)->List[Document]:"""Run search on Kendra index and get top k documents Example: .. code-block:: python docs = retriever.invoke('This is my query') """result_items=self._kendra_query(query)top_k_docs=self._get_top_k_docs(result_items)returnself._filter_by_score_confidence(top_k_docs)