Skip to content

Index

基础索引类。

BaseIndex #

Bases: Generic[IS], ABC

基础LlamaIndex。

Parameters:

Name Type Description Default
nodes List[Node]

要索引的节点列表

None
show_progress bool

是否显示tqdm进度条。默认为False。

False
service_context ServiceContext

服务上下文容器(包含LLM、嵌入等组件)。

None
Source code in llama_index/core/indices/base.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
class BaseIndex(Generic[IS], ABC):
    """基础LlamaIndex。

    Args:
        nodes (List[Node]): 要索引的节点列表
        show_progress (bool): 是否显示tqdm进度条。默认为False。
        service_context (ServiceContext): 服务上下文容器(包含LLM、嵌入等组件)。"""

    index_struct_cls: Type[IS]

    def __init__(
        self,
        nodes: Optional[Sequence[BaseNode]] = None,
        objects: Optional[Sequence[IndexNode]] = None,
        index_struct: Optional[IS] = None,
        storage_context: Optional[StorageContext] = None,
        callback_manager: Optional[CallbackManager] = None,
        transformations: Optional[List[TransformComponent]] = None,
        show_progress: bool = False,
        # deprecated
        service_context: Optional[ServiceContext] = None,
        **kwargs: Any,
    ) -> None:
        """使用参数进行初始化。"""
        if index_struct is None and nodes is None and objects is None:
            raise ValueError("One of nodes, objects, or index_struct must be provided.")
        if index_struct is not None and nodes is not None:
            raise ValueError("Only one of nodes or index_struct can be provided.")
        # This is to explicitly make sure that the old UX is not used
        if nodes is not None and len(nodes) >= 1 and not isinstance(nodes[0], BaseNode):
            if isinstance(nodes[0], Document):
                raise ValueError(
                    "The constructor now takes in a list of Node objects. "
                    "Since you are passing in a list of Document objects, "
                    "please use `from_documents` instead."
                )
            else:
                raise ValueError("nodes must be a list of Node objects.")

        self._storage_context = storage_context or StorageContext.from_defaults()
        # deprecated
        self._service_context = service_context

        self._docstore = self._storage_context.docstore
        self._show_progress = show_progress
        self._vector_store = self._storage_context.vector_store
        self._graph_store = self._storage_context.graph_store
        self._callback_manager = (
            callback_manager
            or callback_manager_from_settings_or_context(Settings, service_context)
        )

        objects = objects or []
        self._object_map = {obj.index_id: obj.obj for obj in objects}
        for obj in objects:
            obj.obj = None  # clear the object to avoid serialization issues

        with self._callback_manager.as_trace("index_construction"):
            if index_struct is None:
                nodes = nodes or []
                index_struct = self.build_index_from_nodes(
                    nodes + objects  # type: ignore
                )
            self._index_struct = index_struct
            self._storage_context.index_store.add_index_struct(self._index_struct)

        self._transformations = (
            transformations
            or transformations_from_settings_or_context(Settings, service_context)
        )

    @classmethod
    def from_documents(
        cls: Type[IndexType],
        documents: Sequence[Document],
        storage_context: Optional[StorageContext] = None,
        show_progress: bool = False,
        callback_manager: Optional[CallbackManager] = None,
        transformations: Optional[List[TransformComponent]] = None,
        # deprecated
        service_context: Optional[ServiceContext] = None,
        **kwargs: Any,
    ) -> IndexType:
        """从文档中创建索引。

Args:
    documents (Optional[Sequence[BaseDocument]]): 用于构建索引的文档列表。
"""
        storage_context = storage_context or StorageContext.from_defaults()
        docstore = storage_context.docstore
        callback_manager = (
            callback_manager
            or callback_manager_from_settings_or_context(Settings, service_context)
        )
        transformations = transformations or transformations_from_settings_or_context(
            Settings, service_context
        )

        with callback_manager.as_trace("index_construction"):
            for doc in documents:
                docstore.set_document_hash(doc.get_doc_id(), doc.hash)

            nodes = run_transformations(
                documents,  # type: ignore
                transformations,
                show_progress=show_progress,
                **kwargs,
            )

            return cls(
                nodes=nodes,
                storage_context=storage_context,
                callback_manager=callback_manager,
                show_progress=show_progress,
                transformations=transformations,
                service_context=service_context,
                **kwargs,
            )

    @property
    def index_struct(self) -> IS:
        """获取索引结构。"""
        return self._index_struct

    @property
    def index_id(self) -> str:
        """获取索引结构。"""
        return self._index_struct.index_id

    def set_index_id(self, index_id: str) -> None:
        """设置索引id。

注意:如果您决定手动在index_struct上设置index_id,您需要显式调用`add_index_struct`在`index_store`上更新索引存储。

Args:
    index_id(str):要设置的索引id。
"""
        # delete the old index struct
        old_id = self._index_struct.index_id
        self._storage_context.index_store.delete_index_struct(old_id)
        # add the new index struct
        self._index_struct.index_id = index_id
        self._storage_context.index_store.add_index_struct(self._index_struct)

    @property
    def docstore(self) -> BaseDocumentStore:
        """获取与索引对应的文档存储。"""
        return self._docstore

    @property
    def service_context(self) -> Optional[ServiceContext]:
        return self._service_context

    @property
    def storage_context(self) -> StorageContext:
        return self._storage_context

    @property
    def summary(self) -> str:
        return str(self._index_struct.summary)

    @summary.setter
    def summary(self, new_summary: str) -> None:
        self._index_struct.summary = new_summary
        self._storage_context.index_store.add_index_struct(self._index_struct)

    @abstractmethod
    def _build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IS:
        """从节点构建索引。"""

    def build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IS:
        """从节点构建索引。"""
        self._docstore.add_documents(nodes, allow_update=True)
        return self._build_index_from_nodes(nodes)

    @abstractmethod
    def _insert(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None:
        """索引结构中特定于索引的逻辑,用于插入节点。"""

    def insert_nodes(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None:
        """插入节点。"""
        for node in nodes:
            if isinstance(node, IndexNode):
                try:
                    node.dict()
                except ValueError:
                    self._object_map[node.index_id] = node.obj
                    node.obj = None

        with self._callback_manager.as_trace("insert_nodes"):
            self.docstore.add_documents(nodes, allow_update=True)
            self._insert(nodes, **insert_kwargs)
            self._storage_context.index_store.add_index_struct(self._index_struct)

    def insert(self, document: Document, **insert_kwargs: Any) -> None:
        """插入一个文档。"""
        with self._callback_manager.as_trace("insert"):
            nodes = run_transformations(
                [document],
                self._transformations,
                show_progress=self._show_progress,
            )

            self.insert_nodes(nodes, **insert_kwargs)
            self.docstore.set_document_hash(document.get_doc_id(), document.hash)

    @abstractmethod
    def _delete_node(self, node_id: str, **delete_kwargs: Any) -> None:
        """删除一个节点。"""

    def delete_nodes(
        self,
        node_ids: List[str],
        delete_from_docstore: bool = False,
        **delete_kwargs: Any,
    ) -> None:
        """从索引中删除节点列表。

Args:
    doc_ids(List[str]):要删除的节点的doc_ids列表
"""
        for node_id in node_ids:
            self._delete_node(node_id, **delete_kwargs)
            if delete_from_docstore:
                self.docstore.delete_document(node_id, raise_error=False)

        self._storage_context.index_store.add_index_struct(self._index_struct)

    def delete(self, doc_id: str, **delete_kwargs: Any) -> None:
        """从索引中删除文档。
与索引相关的所有节点将被删除。

Args:
    doc_id(str):已摄取文档的doc_id
"""
        logger.warning(
            "delete() is now deprecated, please refer to delete_ref_doc() to delete "
            "ingested documents+nodes or delete_nodes to delete a list of nodes."
        )
        self.delete_ref_doc(doc_id)

    def delete_ref_doc(
        self, ref_doc_id: str, delete_from_docstore: bool = False, **delete_kwargs: Any
    ) -> None:
        """使用ref_doc_id删除文档及其节点。"""
        ref_doc_info = self.docstore.get_ref_doc_info(ref_doc_id)
        if ref_doc_info is None:
            logger.warning(f"ref_doc_id {ref_doc_id} not found, nothing deleted.")
            return

        self.delete_nodes(
            ref_doc_info.node_ids,
            delete_from_docstore=False,
            **delete_kwargs,
        )

        if delete_from_docstore:
            self.docstore.delete_ref_doc(ref_doc_id, raise_error=False)

    def update(self, document: Document, **update_kwargs: Any) -> None:
        """更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Args:
    document (Union[BaseDocument, BaseIndex]): 要更新的文档
    insert_kwargs (Dict): 传递给插入操作的kwargs
    delete_kwargs (Dict): 传递给删除操作的kwargs
"""
        logger.warning(
            "update() is now deprecated, please refer to update_ref_doc() to update "
            "ingested documents+nodes."
        )
        self.update_ref_doc(document, **update_kwargs)

    def update_ref_doc(self, document: Document, **update_kwargs: Any) -> None:
        """更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Args:
    document (Union[BaseDocument, BaseIndex]): 要更新的文档
    insert_kwargs (Dict): 传递给插入操作的kwargs
    delete_kwargs (Dict): 传递给删除操作的kwargs
"""
        with self._callback_manager.as_trace("update"):
            self.delete_ref_doc(
                document.get_doc_id(),
                delete_from_docstore=True,
                **update_kwargs.pop("delete_kwargs", {}),
            )
            self.insert(document, **update_kwargs.pop("insert_kwargs", {}))

    def refresh(
        self, documents: Sequence[Document], **update_kwargs: Any
    ) -> List[bool]:
        """刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。
"""
        logger.warning(
            "refresh() is now deprecated, please refer to refresh_ref_docs() to "
            "refresh ingested documents+nodes with an updated list of documents."
        )
        return self.refresh_ref_docs(documents, **update_kwargs)

    def refresh_ref_docs(
        self, documents: Sequence[Document], **update_kwargs: Any
    ) -> List[bool]:
        """刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。
"""
        with self._callback_manager.as_trace("refresh"):
            refreshed_documents = [False] * len(documents)
            for i, document in enumerate(documents):
                existing_doc_hash = self._docstore.get_document_hash(
                    document.get_doc_id()
                )
                if existing_doc_hash is None:
                    self.insert(document, **update_kwargs.pop("insert_kwargs", {}))
                    refreshed_documents[i] = True
                elif existing_doc_hash != document.hash:
                    self.update_ref_doc(
                        document, **update_kwargs.pop("update_kwargs", {})
                    )
                    refreshed_documents[i] = True

            return refreshed_documents

    @property
    @abstractmethod
    def ref_doc_info(self) -> Dict[str, RefDocInfo]:
        """获取已摄取文档及其节点和元数据的字典映射。"""
        ...

    @abstractmethod
    def as_retriever(self, **kwargs: Any) -> BaseRetriever:
        ...

    def as_query_engine(
        self, llm: Optional[LLMType] = None, **kwargs: Any
    ) -> BaseQueryEngine:
        """将索引转换为查询引擎。

调用`index.as_retriever(**kwargs)`来获取检索器,然后将其包装在`RetrieverQueryEngine.from_args(retriever, **kwrags)`调用中。
"""
        # NOTE: lazy import
        from llama_index.core.query_engine.retriever_query_engine import (
            RetrieverQueryEngine,
        )

        retriever = self.as_retriever(**kwargs)
        llm = (
            resolve_llm(llm, callback_manager=self._callback_manager)
            if llm
            else llm_from_settings_or_context(Settings, self.service_context)
        )

        return RetrieverQueryEngine.from_args(
            retriever,
            llm=llm,
            **kwargs,
        )

    def as_chat_engine(
        self,
        chat_mode: ChatMode = ChatMode.BEST,
        llm: Optional[LLMType] = None,
        **kwargs: Any,
    ) -> BaseChatEngine:
        """将索引转换为聊天引擎。

调用`index.as_query_engine(llm=llm, **kwargs)`来获取查询引擎,然后根据聊天模式将其包装成聊天引擎。

聊天模式:
    - `ChatMode.BEST`(默认):使用带有查询引擎工具的代理(react或openai)的聊天引擎
    - `ChatMode.CONTEXT`:使用检索器获取上下文的聊天引擎
    - `ChatMode.CONDENSE_QUESTION`:压缩问题的聊天引擎
    - `ChatMode.CONDENSE_PLUS_CONTEXT`:压缩问题并使用检索器获取上下文的聊天引擎
    - `ChatMode.SIMPLE`:直接使用LLM的简单聊天引擎
    - `ChatMode.REACT`:使用带有查询引擎工具的react代理的聊天引擎
    - `ChatMode.OPENAI`:使用带有查询引擎工具的openai代理的聊天引擎
"""
        service_context = kwargs.get("service_context", self.service_context)

        if service_context is not None:
            llm = (
                resolve_llm(llm, callback_manager=self._callback_manager)
                if llm
                else service_context.llm
            )
        else:
            llm = (
                resolve_llm(llm, callback_manager=self._callback_manager)
                if llm
                else Settings.llm
            )

        query_engine = self.as_query_engine(llm=llm, **kwargs)

        # resolve chat mode
        if chat_mode in [ChatMode.REACT, ChatMode.OPENAI, ChatMode.BEST]:
            # use an agent with query engine tool in these chat modes
            # NOTE: lazy import
            from llama_index.core.agent import AgentRunner
            from llama_index.core.tools.query_engine import QueryEngineTool

            # convert query engine to tool
            query_engine_tool = QueryEngineTool.from_defaults(query_engine=query_engine)

            return AgentRunner.from_llm(
                tools=[query_engine_tool],
                llm=llm,
                **kwargs,
            )

        if chat_mode == ChatMode.CONDENSE_QUESTION:
            # NOTE: lazy import
            from llama_index.core.chat_engine import CondenseQuestionChatEngine

            return CondenseQuestionChatEngine.from_defaults(
                query_engine=query_engine,
                llm=llm,
                **kwargs,
            )
        elif chat_mode == ChatMode.CONTEXT:
            from llama_index.core.chat_engine import ContextChatEngine

            return ContextChatEngine.from_defaults(
                retriever=self.as_retriever(**kwargs),
                llm=llm,
                **kwargs,
            )

        elif chat_mode == ChatMode.CONDENSE_PLUS_CONTEXT:
            from llama_index.core.chat_engine import CondensePlusContextChatEngine

            return CondensePlusContextChatEngine.from_defaults(
                retriever=self.as_retriever(**kwargs),
                llm=llm,
                **kwargs,
            )

        elif chat_mode == ChatMode.SIMPLE:
            from llama_index.core.chat_engine import SimpleChatEngine

            return SimpleChatEngine.from_defaults(
                llm=llm,
                **kwargs,
            )
        else:
            raise ValueError(f"Unknown chat mode: {chat_mode}")

index_struct property #

index_struct: IS

获取索引结构。

index_id property #

index_id: str

获取索引结构。

docstore property #

获取与索引对应的文档存储。

ref_doc_info abstractmethod property #

ref_doc_info: Dict[str, RefDocInfo]

获取已摄取文档及其节点和元数据的字典映射。

from_documents classmethod #

from_documents(
    documents: Sequence[Document],
    storage_context: Optional[StorageContext] = None,
    show_progress: bool = False,
    callback_manager: Optional[CallbackManager] = None,
    transformations: Optional[
        List[TransformComponent]
    ] = None,
    service_context: Optional[ServiceContext] = None,
    **kwargs: Any
) -> IndexType

从文档中创建索引。

Parameters:

Name Type Description Default
documents Optional[Sequence[BaseDocument]]

用于构建索引的文档列表。

required
Source code in llama_index/core/indices/base.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    @classmethod
    def from_documents(
        cls: Type[IndexType],
        documents: Sequence[Document],
        storage_context: Optional[StorageContext] = None,
        show_progress: bool = False,
        callback_manager: Optional[CallbackManager] = None,
        transformations: Optional[List[TransformComponent]] = None,
        # deprecated
        service_context: Optional[ServiceContext] = None,
        **kwargs: Any,
    ) -> IndexType:
        """从文档中创建索引。

Args:
    documents (Optional[Sequence[BaseDocument]]): 用于构建索引的文档列表。
"""
        storage_context = storage_context or StorageContext.from_defaults()
        docstore = storage_context.docstore
        callback_manager = (
            callback_manager
            or callback_manager_from_settings_or_context(Settings, service_context)
        )
        transformations = transformations or transformations_from_settings_or_context(
            Settings, service_context
        )

        with callback_manager.as_trace("index_construction"):
            for doc in documents:
                docstore.set_document_hash(doc.get_doc_id(), doc.hash)

            nodes = run_transformations(
                documents,  # type: ignore
                transformations,
                show_progress=show_progress,
                **kwargs,
            )

            return cls(
                nodes=nodes,
                storage_context=storage_context,
                callback_manager=callback_manager,
                show_progress=show_progress,
                transformations=transformations,
                service_context=service_context,
                **kwargs,
            )

set_index_id #

set_index_id(index_id: str) -> None

设置索引id。

注意:如果您决定手动在index_struct上设置index_id,您需要显式调用add_index_structindex_store上更新索引存储。

Source code in llama_index/core/indices/base.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    def set_index_id(self, index_id: str) -> None:
        """设置索引id。

注意:如果您决定手动在index_struct上设置index_id,您需要显式调用`add_index_struct`在`index_store`上更新索引存储。

Args:
    index_id(str):要设置的索引id。
"""
        # delete the old index struct
        old_id = self._index_struct.index_id
        self._storage_context.index_store.delete_index_struct(old_id)
        # add the new index struct
        self._index_struct.index_id = index_id
        self._storage_context.index_store.add_index_struct(self._index_struct)

build_index_from_nodes #

build_index_from_nodes(nodes: Sequence[BaseNode]) -> IS

从节点构建索引。

Source code in llama_index/core/indices/base.py
201
202
203
204
def build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IS:
    """从节点构建索引。"""
    self._docstore.add_documents(nodes, allow_update=True)
    return self._build_index_from_nodes(nodes)

insert_nodes #

insert_nodes(
    nodes: Sequence[BaseNode], **insert_kwargs: Any
) -> None

插入节点。

Source code in llama_index/core/indices/base.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def insert_nodes(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None:
    """插入节点。"""
    for node in nodes:
        if isinstance(node, IndexNode):
            try:
                node.dict()
            except ValueError:
                self._object_map[node.index_id] = node.obj
                node.obj = None

    with self._callback_manager.as_trace("insert_nodes"):
        self.docstore.add_documents(nodes, allow_update=True)
        self._insert(nodes, **insert_kwargs)
        self._storage_context.index_store.add_index_struct(self._index_struct)

insert #

insert(document: Document, **insert_kwargs: Any) -> None

插入一个文档。

Source code in llama_index/core/indices/base.py
225
226
227
228
229
230
231
232
233
234
235
def insert(self, document: Document, **insert_kwargs: Any) -> None:
    """插入一个文档。"""
    with self._callback_manager.as_trace("insert"):
        nodes = run_transformations(
            [document],
            self._transformations,
            show_progress=self._show_progress,
        )

        self.insert_nodes(nodes, **insert_kwargs)
        self.docstore.set_document_hash(document.get_doc_id(), document.hash)

delete_nodes #

delete_nodes(
    node_ids: List[str],
    delete_from_docstore: bool = False,
    **delete_kwargs: Any
) -> None

从索引中删除节点列表。

Source code in llama_index/core/indices/base.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    def delete_nodes(
        self,
        node_ids: List[str],
        delete_from_docstore: bool = False,
        **delete_kwargs: Any,
    ) -> None:
        """从索引中删除节点列表。

Args:
    doc_ids(List[str]):要删除的节点的doc_ids列表
"""
        for node_id in node_ids:
            self._delete_node(node_id, **delete_kwargs)
            if delete_from_docstore:
                self.docstore.delete_document(node_id, raise_error=False)

        self._storage_context.index_store.add_index_struct(self._index_struct)

delete #

delete(doc_id: str, **delete_kwargs: Any) -> None

从索引中删除文档。 与索引相关的所有节点将被删除。

Source code in llama_index/core/indices/base.py
259
260
261
262
263
264
265
266
267
268
269
270
    def delete(self, doc_id: str, **delete_kwargs: Any) -> None:
        """从索引中删除文档。
与索引相关的所有节点将被删除。

Args:
    doc_id(str):已摄取文档的doc_id
"""
        logger.warning(
            "delete() is now deprecated, please refer to delete_ref_doc() to delete "
            "ingested documents+nodes or delete_nodes to delete a list of nodes."
        )
        self.delete_ref_doc(doc_id)

delete_ref_doc #

delete_ref_doc(
    ref_doc_id: str,
    delete_from_docstore: bool = False,
    **delete_kwargs: Any
) -> None

使用ref_doc_id删除文档及其节点。

Source code in llama_index/core/indices/base.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def delete_ref_doc(
    self, ref_doc_id: str, delete_from_docstore: bool = False, **delete_kwargs: Any
) -> None:
    """使用ref_doc_id删除文档及其节点。"""
    ref_doc_info = self.docstore.get_ref_doc_info(ref_doc_id)
    if ref_doc_info is None:
        logger.warning(f"ref_doc_id {ref_doc_id} not found, nothing deleted.")
        return

    self.delete_nodes(
        ref_doc_info.node_ids,
        delete_from_docstore=False,
        **delete_kwargs,
    )

    if delete_from_docstore:
        self.docstore.delete_ref_doc(ref_doc_id, raise_error=False)

update #

update(document: Document, **update_kwargs: Any) -> None

更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Parameters:

Name Type Description Default
document Union[BaseDocument, BaseIndex]

要更新的文档

required
insert_kwargs Dict

传递给插入操作的kwargs

required
delete_kwargs Dict

传递给删除操作的kwargs

required
Source code in llama_index/core/indices/base.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    def update(self, document: Document, **update_kwargs: Any) -> None:
        """更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Args:
    document (Union[BaseDocument, BaseIndex]): 要更新的文档
    insert_kwargs (Dict): 传递给插入操作的kwargs
    delete_kwargs (Dict): 传递给删除操作的kwargs
"""
        logger.warning(
            "update() is now deprecated, please refer to update_ref_doc() to update "
            "ingested documents+nodes."
        )
        self.update_ref_doc(document, **update_kwargs)

update_ref_doc #

update_ref_doc(
    document: Document, **update_kwargs: Any
) -> None

更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Parameters:

Name Type Description Default
document Union[BaseDocument, BaseIndex]

要更新的文档

required
insert_kwargs Dict

传递给插入操作的kwargs

required
delete_kwargs Dict

传递给删除操作的kwargs

required
Source code in llama_index/core/indices/base.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    def update_ref_doc(self, document: Document, **update_kwargs: Any) -> None:
        """更新文档及其对应的节点。

这相当于删除文档,然后再次插入它。

Args:
    document (Union[BaseDocument, BaseIndex]): 要更新的文档
    insert_kwargs (Dict): 传递给插入操作的kwargs
    delete_kwargs (Dict): 传递给删除操作的kwargs
"""
        with self._callback_manager.as_trace("update"):
            self.delete_ref_doc(
                document.get_doc_id(),
                delete_from_docstore=True,
                **update_kwargs.pop("delete_kwargs", {}),
            )
            self.insert(document, **update_kwargs.pop("insert_kwargs", {}))

refresh #

refresh(
    documents: Sequence[Document], **update_kwargs: Any
) -> List[bool]

刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。

Source code in llama_index/core/indices/base.py
324
325
326
327
328
329
330
331
332
333
334
335
    def refresh(
        self, documents: Sequence[Document], **update_kwargs: Any
    ) -> List[bool]:
        """刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。
"""
        logger.warning(
            "refresh() is now deprecated, please refer to refresh_ref_docs() to "
            "refresh ingested documents+nodes with an updated list of documents."
        )
        return self.refresh_ref_docs(documents, **update_kwargs)

refresh_ref_docs #

refresh_ref_docs(
    documents: Sequence[Document], **update_kwargs: Any
) -> List[bool]

刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。

Source code in llama_index/core/indices/base.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    def refresh_ref_docs(
        self, documents: Sequence[Document], **update_kwargs: Any
    ) -> List[bool]:
        """刷新具有更改的文档的索引。

这允许用户保存LLM和嵌入模型调用,同时只更新具有文本或元数据更改的文档。它还将插入以前未存储的任何文档。
"""
        with self._callback_manager.as_trace("refresh"):
            refreshed_documents = [False] * len(documents)
            for i, document in enumerate(documents):
                existing_doc_hash = self._docstore.get_document_hash(
                    document.get_doc_id()
                )
                if existing_doc_hash is None:
                    self.insert(document, **update_kwargs.pop("insert_kwargs", {}))
                    refreshed_documents[i] = True
                elif existing_doc_hash != document.hash:
                    self.update_ref_doc(
                        document, **update_kwargs.pop("update_kwargs", {})
                    )
                    refreshed_documents[i] = True

            return refreshed_documents

as_query_engine #

as_query_engine(
    llm: Optional[LLMType] = None, **kwargs: Any
) -> BaseQueryEngine

将索引转换为查询引擎。

调用index.as_retriever(**kwargs)来获取检索器,然后将其包装在RetrieverQueryEngine.from_args(retriever, **kwrags)调用中。

Source code in llama_index/core/indices/base.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    def as_query_engine(
        self, llm: Optional[LLMType] = None, **kwargs: Any
    ) -> BaseQueryEngine:
        """将索引转换为查询引擎。

调用`index.as_retriever(**kwargs)`来获取检索器,然后将其包装在`RetrieverQueryEngine.from_args(retriever, **kwrags)`调用中。
"""
        # NOTE: lazy import
        from llama_index.core.query_engine.retriever_query_engine import (
            RetrieverQueryEngine,
        )

        retriever = self.as_retriever(**kwargs)
        llm = (
            resolve_llm(llm, callback_manager=self._callback_manager)
            if llm
            else llm_from_settings_or_context(Settings, self.service_context)
        )

        return RetrieverQueryEngine.from_args(
            retriever,
            llm=llm,
            **kwargs,
        )

as_chat_engine #

as_chat_engine(
    chat_mode: ChatMode = ChatMode.BEST,
    llm: Optional[LLMType] = None,
    **kwargs: Any
) -> BaseChatEngine

将索引转换为聊天引擎。

调用index.as_query_engine(llm=llm, **kwargs)来获取查询引擎,然后根据聊天模式将其包装成聊天引擎。

聊天模式: - ChatMode.BEST(默认):使用带有查询引擎工具的代理(react或openai)的聊天引擎 - ChatMode.CONTEXT:使用检索器获取上下文的聊天引擎 - ChatMode.CONDENSE_QUESTION:压缩问题的聊天引擎 - ChatMode.CONDENSE_PLUS_CONTEXT:压缩问题并使用检索器获取上下文的聊天引擎 - ChatMode.SIMPLE:直接使用LLM的简单聊天引擎 - ChatMode.REACT:使用带有查询引擎工具的react代理的聊天引擎 - ChatMode.OPENAI:使用带有查询引擎工具的openai代理的聊天引擎

Source code in llama_index/core/indices/base.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
    def as_chat_engine(
        self,
        chat_mode: ChatMode = ChatMode.BEST,
        llm: Optional[LLMType] = None,
        **kwargs: Any,
    ) -> BaseChatEngine:
        """将索引转换为聊天引擎。

调用`index.as_query_engine(llm=llm, **kwargs)`来获取查询引擎,然后根据聊天模式将其包装成聊天引擎。

聊天模式:
    - `ChatMode.BEST`(默认):使用带有查询引擎工具的代理(react或openai)的聊天引擎
    - `ChatMode.CONTEXT`:使用检索器获取上下文的聊天引擎
    - `ChatMode.CONDENSE_QUESTION`:压缩问题的聊天引擎
    - `ChatMode.CONDENSE_PLUS_CONTEXT`:压缩问题并使用检索器获取上下文的聊天引擎
    - `ChatMode.SIMPLE`:直接使用LLM的简单聊天引擎
    - `ChatMode.REACT`:使用带有查询引擎工具的react代理的聊天引擎
    - `ChatMode.OPENAI`:使用带有查询引擎工具的openai代理的聊天引擎
"""
        service_context = kwargs.get("service_context", self.service_context)

        if service_context is not None:
            llm = (
                resolve_llm(llm, callback_manager=self._callback_manager)
                if llm
                else service_context.llm
            )
        else:
            llm = (
                resolve_llm(llm, callback_manager=self._callback_manager)
                if llm
                else Settings.llm
            )

        query_engine = self.as_query_engine(llm=llm, **kwargs)

        # resolve chat mode
        if chat_mode in [ChatMode.REACT, ChatMode.OPENAI, ChatMode.BEST]:
            # use an agent with query engine tool in these chat modes
            # NOTE: lazy import
            from llama_index.core.agent import AgentRunner
            from llama_index.core.tools.query_engine import QueryEngineTool

            # convert query engine to tool
            query_engine_tool = QueryEngineTool.from_defaults(query_engine=query_engine)

            return AgentRunner.from_llm(
                tools=[query_engine_tool],
                llm=llm,
                **kwargs,
            )

        if chat_mode == ChatMode.CONDENSE_QUESTION:
            # NOTE: lazy import
            from llama_index.core.chat_engine import CondenseQuestionChatEngine

            return CondenseQuestionChatEngine.from_defaults(
                query_engine=query_engine,
                llm=llm,
                **kwargs,
            )
        elif chat_mode == ChatMode.CONTEXT:
            from llama_index.core.chat_engine import ContextChatEngine

            return ContextChatEngine.from_defaults(
                retriever=self.as_retriever(**kwargs),
                llm=llm,
                **kwargs,
            )

        elif chat_mode == ChatMode.CONDENSE_PLUS_CONTEXT:
            from llama_index.core.chat_engine import CondensePlusContextChatEngine

            return CondensePlusContextChatEngine.from_defaults(
                retriever=self.as_retriever(**kwargs),
                llm=llm,
                **kwargs,
            )

        elif chat_mode == ChatMode.SIMPLE:
            from llama_index.core.chat_engine import SimpleChatEngine

            return SimpleChatEngine.from_defaults(
                llm=llm,
                **kwargs,
            )
        else:
            raise ValueError(f"Unknown chat mode: {chat_mode}")