llama-index

Форк
0
1
"""LlamaIndex Tool classes."""
2

3
from typing import Any, Dict, List
4

5
from llama_index.legacy.bridge.langchain import BaseTool
6
from llama_index.legacy.bridge.pydantic import BaseModel, Field
7
from llama_index.legacy.core.base_query_engine import BaseQueryEngine
8
from llama_index.legacy.core.response.schema import RESPONSE_TYPE
9
from llama_index.legacy.schema import TextNode
10

11

12
def _get_response_with_sources(response: RESPONSE_TYPE) -> str:
13
    """Return a response with source node info."""
14
    source_data: List[Dict[str, Any]] = []
15
    for source_node in response.source_nodes:
16
        metadata = {}
17
        if isinstance(source_node.node, TextNode):
18
            start = source_node.node.start_char_idx
19
            end = source_node.node.end_char_idx
20
            if start is not None and end is not None:
21
                metadata.update({"start_char_idx": start, "end_char_idx": end})
22

23
        source_data.append(metadata)
24
        source_data[-1]["ref_doc_id"] = source_node.node.ref_doc_id
25
        source_data[-1]["score"] = source_node.score
26
    return str({"answer": str(response), "sources": source_data})
27

28

29
class IndexToolConfig(BaseModel):
30
    """Configuration for LlamaIndex index tool."""
31

32
    query_engine: BaseQueryEngine
33
    name: str
34
    description: str
35
    tool_kwargs: Dict = Field(default_factory=dict)
36

37
    class Config:
38
        """Configuration for this pydantic object."""
39

40
        arbitrary_types_allowed = True
41

42

43
class LlamaIndexTool(BaseTool):
44
    """Tool for querying a LlamaIndex."""
45

46
    # NOTE: name/description still needs to be set
47
    query_engine: BaseQueryEngine
48
    return_sources: bool = False
49

50
    @classmethod
51
    def from_tool_config(cls, tool_config: IndexToolConfig) -> "LlamaIndexTool":
52
        """Create a tool from a tool config."""
53
        return_sources = tool_config.tool_kwargs.pop("return_sources", False)
54
        return cls(
55
            query_engine=tool_config.query_engine,
56
            name=tool_config.name,
57
            description=tool_config.description,
58
            return_sources=return_sources,
59
            **tool_config.tool_kwargs,
60
        )
61

62
    def _run(self, input: str) -> str:
63
        response = self.query_engine.query(input)
64
        if self.return_sources:
65
            return _get_response_with_sources(response)
66
        return str(response)
67

68
    async def _arun(self, input: str) -> str:
69
        response = await self.query_engine.aquery(input)
70
        if self.return_sources:
71
            return _get_response_with_sources(response)
72
        return str(response)
73

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.