|
| 1 | +# GitHub: https://github.com/naotaka1128/llm_app_codes/chapter_010/tools/fetch_qa_content.py |
| 2 | + |
| 3 | +from os import getenv |
| 4 | + |
| 5 | +from langchain_community.vectorstores.azuresearch import AzureSearch |
| 6 | +from langchain_core.pydantic_v1 import BaseModel, Field |
| 7 | +from langchain_core.tools import tool |
| 8 | +from langchain_openai import AzureOpenAIEmbeddings |
| 9 | + |
| 10 | + |
| 11 | +class FetchContentInput(BaseModel): |
| 12 | + """型を指定するためのクラス""" |
| 13 | + |
| 14 | + query: str = Field() |
| 15 | + |
| 16 | + |
| 17 | +def get_embeddings(): |
| 18 | + return AzureOpenAIEmbeddings( |
| 19 | + api_key=getenv("AZURE_OPENAI_API_KEY"), |
| 20 | + api_version=getenv("AZURE_OPENAI_API_VERSION"), |
| 21 | + azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), |
| 22 | + azure_deployment=getenv("AZURE_OPENAI_MODEL_EMBEDDING"), |
| 23 | + ) |
| 24 | + |
| 25 | + |
| 26 | +def create_azure_search(index_name: str) -> AzureSearch: |
| 27 | + return AzureSearch( |
| 28 | + azure_search_endpoint=getenv("AZURE_AI_SEARCH_ENDPOINT"), |
| 29 | + azure_search_key=getenv("AZURE_AI_SEARCH_API_KEY"), |
| 30 | + index_name=index_name, |
| 31 | + embedding_function=get_embeddings().embed_query, |
| 32 | + additional_search_client_options={"retry_total": 4}, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +@tool(args_schema=FetchContentInput) |
| 37 | +def fetch_contoso_rules(query): |
| 38 | + """ |
| 39 | + Contoso 社の就業規則情報から、関連するコンテンツを見つけるツールです。 |
| 40 | + Contoso 社に関する具体的な知識を得るのに役立ちます。 |
| 41 | +
|
| 42 | + このツールは `similarity`(類似度)と `content`(コンテンツ)を返します。 |
| 43 | + - 'similarity'は、回答が質問にどの程度関連しているかを示します。 |
| 44 | + 値が高いほど、質問との関連性が高いことを意味します。 |
| 45 | + 'similarity'値が0.5未満のドキュメントは返されません。 |
| 46 | + - 'content'は、質問に対する回答のテキストを提供します。 |
| 47 | + 通常、よくある質問とその対応する回答で構成されています。 |
| 48 | +
|
| 49 | + 空のリストが返された場合、ユーザーの質問に対する回答が見つからなかったことを意味します。 |
| 50 | + その場合、ユーザーに質問内容を明確にしてもらうのが良いでしょう。 |
| 51 | +
|
| 52 | + Returns |
| 53 | + ------- |
| 54 | + List[Dict[str, Any]]: |
| 55 | + - page_content |
| 56 | + - similarity: float |
| 57 | + - content: str |
| 58 | + """ |
| 59 | + db = create_azure_search("contoso_rules") |
| 60 | + docs = db.similarity_search_with_relevance_scores( |
| 61 | + query=query, |
| 62 | + k=3, |
| 63 | + score_threshold=0.5, |
| 64 | + ) |
| 65 | + return [ |
| 66 | + { |
| 67 | + "similarity": similarity, |
| 68 | + "content": i.page_content, |
| 69 | + } |
| 70 | + for i, similarity in docs |
| 71 | + ] |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + import logging |
| 76 | + |
| 77 | + from dotenv import load_dotenv |
| 78 | + |
| 79 | + logging.basicConfig( |
| 80 | + format="[%(asctime)s] %(levelname)7s from %(name)s in %(pathname)s:%(lineno)d: " "%(message)s", |
| 81 | + level=logging.DEBUG, |
| 82 | + force=True, |
| 83 | + ) |
| 84 | + |
| 85 | + load_dotenv() |
| 86 | + docs = fetch_contoso_rules("ドレスコード") |
| 87 | + for doc in docs: |
| 88 | + print(doc) |
0 commit comments