code
stringlengths
161
67.2k
apis
sequencelengths
1
24
extract_api
stringlengths
164
53.3k
from collections import ChainMap from typing import ( Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator from llama_index.legacy.callbacks import CBEventType, EventPayload from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) from llama_index.legacy.core.query_pipeline.query_component import ( InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable, ) from llama_index.legacy.llms.base import BaseLLM from llama_index.legacy.llms.generic_utils import ( messages_to_prompt as generic_messages_to_prompt, ) from llama_index.legacy.llms.generic_utils import ( prompt_to_messages, ) from llama_index.legacy.prompts import BasePromptTemplate, PromptTemplate from llama_index.legacy.types import ( BaseOutputParser, PydanticProgramMode, TokenAsyncGen, TokenGen, ) # NOTE: These two protocols are needed to appease mypy @runtime_checkable class MessagesToPromptType(Protocol): def __call__(self, messages: Sequence[ChatMessage]) -> str: pass @runtime_checkable class CompletionToPromptType(Protocol): def __call__(self, prompt: str) -> str: pass def stream_completion_response_to_tokens( completion_response_gen: CompletionResponseGen, ) -> TokenGen: """Convert a stream completion response to a stream of tokens.""" def gen() -> TokenGen: for response in completion_response_gen: yield response.delta or "" return gen() def stream_chat_response_to_tokens( chat_response_gen: ChatResponseGen, ) -> TokenGen: """Convert a stream completion response to a stream of tokens.""" def gen() -> TokenGen: for response in chat_response_gen: yield response.delta or "" return gen() async def astream_completion_response_to_tokens( completion_response_gen: CompletionResponseAsyncGen, ) -> TokenAsyncGen: """Convert a stream completion response to a stream of tokens.""" async def gen() -> TokenAsyncGen: async for response in completion_response_gen: yield response.delta or "" return gen() async def astream_chat_response_to_tokens( chat_response_gen: ChatResponseAsyncGen, ) -> TokenAsyncGen: """Convert a stream completion response to a stream of tokens.""" async def gen() -> TokenAsyncGen: async for response in chat_response_gen: yield response.delta or "" return gen() def default_completion_to_prompt(prompt: str) -> str: return prompt class LLM(BaseLLM): system_prompt: Optional[str] = Field( default=None, description="System prompt for LLM calls." ) messages_to_prompt: MessagesToPromptType = Field( description="Function to convert a list of messages to an LLM prompt.", default=generic_messages_to_prompt, exclude=True, ) completion_to_prompt: CompletionToPromptType = Field( description="Function to convert a completion to an LLM prompt.", default=default_completion_to_prompt, exclude=True, ) output_parser: Optional[BaseOutputParser] = Field( description="Output parser to parse, validate, and correct errors programmatically.", default=None, exclude=True, ) pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT # deprecated query_wrapper_prompt: Optional[BasePromptTemplate] = Field( description="Query wrapper prompt for LLM calls.", default=None, exclude=True, ) @validator("messages_to_prompt", pre=True) def set_messages_to_prompt( cls, messages_to_prompt: Optional[MessagesToPromptType] ) -> MessagesToPromptType: return messages_to_prompt or generic_messages_to_prompt @validator("completion_to_prompt", pre=True) def set_completion_to_prompt( cls, completion_to_prompt: Optional[CompletionToPromptType] ) -> CompletionToPromptType: return completion_to_prompt or default_completion_to_prompt def _log_template_data( self, prompt: BasePromptTemplate, **prompt_args: Any ) -> None: template_vars = { k: v for k, v in ChainMap(prompt.kwargs, prompt_args).items() if k in prompt.template_vars } with self.callback_manager.event( CBEventType.TEMPLATING, payload={ EventPayload.TEMPLATE: prompt.get_template(llm=self), EventPayload.TEMPLATE_VARS: template_vars, EventPayload.SYSTEM_PROMPT: self.system_prompt, EventPayload.QUERY_WRAPPER_PROMPT: self.query_wrapper_prompt, }, ): pass def _get_prompt(self, prompt: BasePromptTemplate, **prompt_args: Any) -> str: formatted_prompt = prompt.format( llm=self, messages_to_prompt=self.messages_to_prompt, completion_to_prompt=self.completion_to_prompt, **prompt_args, ) if self.output_parser is not None: formatted_prompt = self.output_parser.format(formatted_prompt) return self._extend_prompt(formatted_prompt) def _get_messages( self, prompt: BasePromptTemplate, **prompt_args: Any ) -> List[ChatMessage]: messages = prompt.format_messages(llm=self, **prompt_args) if self.output_parser is not None: messages = self.output_parser.format_messages(messages) return self._extend_messages(messages) def structured_predict( self, output_cls: BaseModel, prompt: PromptTemplate, **prompt_args: Any, ) -> BaseModel: from llama_index.legacy.program.utils import get_program_for_llm program = get_program_for_llm( output_cls, prompt, self, pydantic_program_mode=self.pydantic_program_mode, ) return program(**prompt_args) async def astructured_predict( self, output_cls: BaseModel, prompt: PromptTemplate, **prompt_args: Any, ) -> BaseModel: from llama_index.legacy.program.utils import get_program_for_llm program = get_program_for_llm( output_cls, prompt, self, pydantic_program_mode=self.pydantic_program_mode, ) return await program.acall(**prompt_args) def _parse_output(self, output: str) -> str: if self.output_parser is not None: return str(self.output_parser.parse(output)) return output def predict( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> str: """Predict.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = self.chat(messages) output = chat_response.message.content or "" else: formatted_prompt = self._get_prompt(prompt, **prompt_args) response = self.complete(formatted_prompt, formatted=True) output = response.text return self._parse_output(output) def stream( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> TokenGen: """Stream.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = self.stream_chat(messages) stream_tokens = stream_chat_response_to_tokens(chat_response) else: formatted_prompt = self._get_prompt(prompt, **prompt_args) stream_response = self.stream_complete(formatted_prompt, formatted=True) stream_tokens = stream_completion_response_to_tokens(stream_response) if prompt.output_parser is not None or self.output_parser is not None: raise NotImplementedError("Output parser is not supported for streaming.") return stream_tokens async def apredict( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> str: """Async predict.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = await self.achat(messages) output = chat_response.message.content or "" else: formatted_prompt = self._get_prompt(prompt, **prompt_args) response = await self.acomplete(formatted_prompt, formatted=True) output = response.text return self._parse_output(output) async def astream( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> TokenAsyncGen: """Async stream.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = await self.astream_chat(messages) stream_tokens = await astream_chat_response_to_tokens(chat_response) else: formatted_prompt = self._get_prompt(prompt, **prompt_args) stream_response = await self.astream_complete( formatted_prompt, formatted=True ) stream_tokens = await astream_completion_response_to_tokens(stream_response) if prompt.output_parser is not None or self.output_parser is not None: raise NotImplementedError("Output parser is not supported for streaming.") return stream_tokens def _extend_prompt( self, formatted_prompt: str, ) -> str: """Add system and query wrapper prompts to base prompt.""" extended_prompt = formatted_prompt if self.system_prompt: extended_prompt = self.system_prompt + "\n\n" + extended_prompt if self.query_wrapper_prompt: extended_prompt = self.query_wrapper_prompt.format( query_str=extended_prompt ) return extended_prompt def _extend_messages(self, messages: List[ChatMessage]) -> List[ChatMessage]: """Add system prompt to chat message list.""" if self.system_prompt: messages = [ ChatMessage(role=MessageRole.SYSTEM, content=self.system_prompt), *messages, ] return messages def _as_query_component(self, **kwargs: Any) -> QueryComponent: """Return query component.""" if self.metadata.is_chat_model: return LLMChatComponent(llm=self, **kwargs) else: return LLMCompleteComponent(llm=self, **kwargs) class BaseLLMComponent(QueryComponent): """Base LLM component.""" llm: LLM = Field(..., description="LLM") streaming: bool = Field(default=False, description="Streaming mode") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: Any) -> None: """Set callback manager.""" self.llm.callback_manager = callback_manager class LLMCompleteComponent(BaseLLMComponent): """LLM completion component.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" if "prompt" not in input: raise ValueError("Prompt must be in input dict.") # do special check to see if prompt is a list of chat messages if isinstance(input["prompt"], get_args(List[ChatMessage])): input["prompt"] = self.llm.messages_to_prompt(input["prompt"]) input["prompt"] = validate_and_convert_stringable(input["prompt"]) else: input["prompt"] = validate_and_convert_stringable(input["prompt"]) input["prompt"] = self.llm.completion_to_prompt(input["prompt"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. prompt = kwargs["prompt"] # ignore all other kwargs for now if self.streaming: response = self.llm.stream_complete(prompt, formatted=True) else: response = self.llm.complete(prompt, formatted=True) return {"output": response} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. prompt = kwargs["prompt"] # ignore all other kwargs for now response = await self.llm.acomplete(prompt, formatted=True) return {"output": response} @property def input_keys(self) -> InputKeys: """Input keys.""" # TODO: support only complete for now return InputKeys.from_keys({"prompt"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class LLMChatComponent(BaseLLMComponent): """LLM chat component.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" if "messages" not in input: raise ValueError("Messages must be in input dict.") # if `messages` is a string, convert to a list of chat message if isinstance(input["messages"], get_args(StringableInput)): input["messages"] = validate_and_convert_stringable(input["messages"]) input["messages"] = prompt_to_messages(str(input["messages"])) for message in input["messages"]: if not isinstance(message, ChatMessage): raise ValueError("Messages must be a list of ChatMessage") return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. messages = kwargs["messages"] if self.streaming: response = self.llm.stream_chat(messages) else: response = self.llm.chat(messages) return {"output": response} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. messages = kwargs["messages"] if self.streaming: response = await self.llm.astream_chat(messages) else: response = await self.llm.achat(messages) return {"output": response} @property def input_keys(self) -> InputKeys: """Input keys.""" # TODO: support only complete for now return InputKeys.from_keys({"messages"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"})
[ "llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable", "llama_index.legacy.program.utils.get_program_for_llm", "llama_index.legacy.bridge.pydantic.validator" ]
[((2828, 2891), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""System prompt for LLM calls."""'}), "(default=None, description='System prompt for LLM calls.')\n", (2833, 2891), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((2953, 3090), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Function to convert a list of messages to an LLM prompt."""', 'default': 'generic_messages_to_prompt', 'exclude': '(True)'}), "(description=\n 'Function to convert a list of messages to an LLM prompt.', default=\n generic_messages_to_prompt, exclude=True)\n", (2958, 3090), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3163, 3290), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Function to convert a completion to an LLM prompt."""', 'default': 'default_completion_to_prompt', 'exclude': '(True)'}), "(description='Function to convert a completion to an LLM prompt.',\n default=default_completion_to_prompt, exclude=True)\n", (3168, 3290), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3366, 3494), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Output parser to parse, validate, and correct errors programmatically."""', 'default': 'None', 'exclude': '(True)'}), "(description=\n 'Output parser to parse, validate, and correct errors programmatically.',\n default=None, exclude=True)\n", (3371, 3494), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3669, 3757), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Query wrapper prompt for LLM calls."""', 'default': 'None', 'exclude': '(True)'}), "(description='Query wrapper prompt for LLM calls.', default=None,\n exclude=True)\n", (3674, 3757), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3791, 3832), 'llama_index.legacy.bridge.pydantic.validator', 'validator', (['"""messages_to_prompt"""'], {'pre': '(True)'}), "('messages_to_prompt', pre=True)\n", (3800, 3832), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((4030, 4073), 'llama_index.legacy.bridge.pydantic.validator', 'validator', (['"""completion_to_prompt"""'], {'pre': '(True)'}), "('completion_to_prompt', pre=True)\n", (4039, 4073), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((11157, 11186), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""LLM"""'}), "(..., description='LLM')\n", (11162, 11186), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((11209, 11259), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Streaming mode"""'}), "(default=False, description='Streaming mode')\n", (11214, 11259), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((6014, 6114), 'llama_index.legacy.program.utils.get_program_for_llm', 'get_program_for_llm', (['output_cls', 'prompt', 'self'], {'pydantic_program_mode': 'self.pydantic_program_mode'}), '(output_cls, prompt, self, pydantic_program_mode=self.\n pydantic_program_mode)\n', (6033, 6114), False, 'from llama_index.legacy.program.utils import get_program_for_llm\n'), ((6461, 6561), 'llama_index.legacy.program.utils.get_program_for_llm', 'get_program_for_llm', (['output_cls', 'prompt', 'self'], {'pydantic_program_mode': 'self.pydantic_program_mode'}), '(output_cls, prompt, self, pydantic_program_mode=self.\n pydantic_program_mode)\n', (6480, 6561), False, 'from llama_index.legacy.program.utils import get_program_for_llm\n'), ((13294, 13325), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'prompt'}"], {}), "({'prompt'})\n", (13313, 13325), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((13424, 13456), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (13444, 13456), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((15250, 15283), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'messages'}"], {}), "({'messages'})\n", (15269, 15283), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((15382, 15414), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (15402, 15414), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((11912, 11939), 'typing.get_args', 'get_args', (['List[ChatMessage]'], {}), '(List[ChatMessage])\n', (11920, 11939), False, 'from typing import Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable\n'), ((12047, 12095), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['prompt']"], {}), "(input['prompt'])\n", (12078, 12095), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((12140, 12188), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['prompt']"], {}), "(input['prompt'])\n", (12171, 12188), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((13890, 13915), 'typing.get_args', 'get_args', (['StringableInput'], {}), '(StringableInput)\n', (13898, 13915), False, 'from typing import Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable\n'), ((13950, 14000), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['messages']"], {}), "(input['messages'])\n", (13981, 14000), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((10661, 10725), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.SYSTEM', 'content': 'self.system_prompt'}), '(role=MessageRole.SYSTEM, content=self.system_prompt)\n', (10672, 10725), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole\n'), ((4449, 4485), 'collections.ChainMap', 'ChainMap', (['prompt.kwargs', 'prompt_args'], {}), '(prompt.kwargs, prompt_args)\n', (4457, 4485), False, 'from collections import ChainMap\n')]
from collections import ChainMap from typing import ( Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable, ) from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator from llama_index.legacy.callbacks import CBEventType, EventPayload from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole, ) from llama_index.legacy.core.query_pipeline.query_component import ( InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable, ) from llama_index.legacy.llms.base import BaseLLM from llama_index.legacy.llms.generic_utils import ( messages_to_prompt as generic_messages_to_prompt, ) from llama_index.legacy.llms.generic_utils import ( prompt_to_messages, ) from llama_index.legacy.prompts import BasePromptTemplate, PromptTemplate from llama_index.legacy.types import ( BaseOutputParser, PydanticProgramMode, TokenAsyncGen, TokenGen, ) # NOTE: These two protocols are needed to appease mypy @runtime_checkable class MessagesToPromptType(Protocol): def __call__(self, messages: Sequence[ChatMessage]) -> str: pass @runtime_checkable class CompletionToPromptType(Protocol): def __call__(self, prompt: str) -> str: pass def stream_completion_response_to_tokens( completion_response_gen: CompletionResponseGen, ) -> TokenGen: """Convert a stream completion response to a stream of tokens.""" def gen() -> TokenGen: for response in completion_response_gen: yield response.delta or "" return gen() def stream_chat_response_to_tokens( chat_response_gen: ChatResponseGen, ) -> TokenGen: """Convert a stream completion response to a stream of tokens.""" def gen() -> TokenGen: for response in chat_response_gen: yield response.delta or "" return gen() async def astream_completion_response_to_tokens( completion_response_gen: CompletionResponseAsyncGen, ) -> TokenAsyncGen: """Convert a stream completion response to a stream of tokens.""" async def gen() -> TokenAsyncGen: async for response in completion_response_gen: yield response.delta or "" return gen() async def astream_chat_response_to_tokens( chat_response_gen: ChatResponseAsyncGen, ) -> TokenAsyncGen: """Convert a stream completion response to a stream of tokens.""" async def gen() -> TokenAsyncGen: async for response in chat_response_gen: yield response.delta or "" return gen() def default_completion_to_prompt(prompt: str) -> str: return prompt class LLM(BaseLLM): system_prompt: Optional[str] = Field( default=None, description="System prompt for LLM calls." ) messages_to_prompt: MessagesToPromptType = Field( description="Function to convert a list of messages to an LLM prompt.", default=generic_messages_to_prompt, exclude=True, ) completion_to_prompt: CompletionToPromptType = Field( description="Function to convert a completion to an LLM prompt.", default=default_completion_to_prompt, exclude=True, ) output_parser: Optional[BaseOutputParser] = Field( description="Output parser to parse, validate, and correct errors programmatically.", default=None, exclude=True, ) pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT # deprecated query_wrapper_prompt: Optional[BasePromptTemplate] = Field( description="Query wrapper prompt for LLM calls.", default=None, exclude=True, ) @validator("messages_to_prompt", pre=True) def set_messages_to_prompt( cls, messages_to_prompt: Optional[MessagesToPromptType] ) -> MessagesToPromptType: return messages_to_prompt or generic_messages_to_prompt @validator("completion_to_prompt", pre=True) def set_completion_to_prompt( cls, completion_to_prompt: Optional[CompletionToPromptType] ) -> CompletionToPromptType: return completion_to_prompt or default_completion_to_prompt def _log_template_data( self, prompt: BasePromptTemplate, **prompt_args: Any ) -> None: template_vars = { k: v for k, v in ChainMap(prompt.kwargs, prompt_args).items() if k in prompt.template_vars } with self.callback_manager.event( CBEventType.TEMPLATING, payload={ EventPayload.TEMPLATE: prompt.get_template(llm=self), EventPayload.TEMPLATE_VARS: template_vars, EventPayload.SYSTEM_PROMPT: self.system_prompt, EventPayload.QUERY_WRAPPER_PROMPT: self.query_wrapper_prompt, }, ): pass def _get_prompt(self, prompt: BasePromptTemplate, **prompt_args: Any) -> str: formatted_prompt = prompt.format( llm=self, messages_to_prompt=self.messages_to_prompt, completion_to_prompt=self.completion_to_prompt, **prompt_args, ) if self.output_parser is not None: formatted_prompt = self.output_parser.format(formatted_prompt) return self._extend_prompt(formatted_prompt) def _get_messages( self, prompt: BasePromptTemplate, **prompt_args: Any ) -> List[ChatMessage]: messages = prompt.format_messages(llm=self, **prompt_args) if self.output_parser is not None: messages = self.output_parser.format_messages(messages) return self._extend_messages(messages) def structured_predict( self, output_cls: BaseModel, prompt: PromptTemplate, **prompt_args: Any, ) -> BaseModel: from llama_index.legacy.program.utils import get_program_for_llm program = get_program_for_llm( output_cls, prompt, self, pydantic_program_mode=self.pydantic_program_mode, ) return program(**prompt_args) async def astructured_predict( self, output_cls: BaseModel, prompt: PromptTemplate, **prompt_args: Any, ) -> BaseModel: from llama_index.legacy.program.utils import get_program_for_llm program = get_program_for_llm( output_cls, prompt, self, pydantic_program_mode=self.pydantic_program_mode, ) return await program.acall(**prompt_args) def _parse_output(self, output: str) -> str: if self.output_parser is not None: return str(self.output_parser.parse(output)) return output def predict( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> str: """Predict.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = self.chat(messages) output = chat_response.message.content or "" else: formatted_prompt = self._get_prompt(prompt, **prompt_args) response = self.complete(formatted_prompt, formatted=True) output = response.text return self._parse_output(output) def stream( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> TokenGen: """Stream.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = self.stream_chat(messages) stream_tokens = stream_chat_response_to_tokens(chat_response) else: formatted_prompt = self._get_prompt(prompt, **prompt_args) stream_response = self.stream_complete(formatted_prompt, formatted=True) stream_tokens = stream_completion_response_to_tokens(stream_response) if prompt.output_parser is not None or self.output_parser is not None: raise NotImplementedError("Output parser is not supported for streaming.") return stream_tokens async def apredict( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> str: """Async predict.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = await self.achat(messages) output = chat_response.message.content or "" else: formatted_prompt = self._get_prompt(prompt, **prompt_args) response = await self.acomplete(formatted_prompt, formatted=True) output = response.text return self._parse_output(output) async def astream( self, prompt: BasePromptTemplate, **prompt_args: Any, ) -> TokenAsyncGen: """Async stream.""" self._log_template_data(prompt, **prompt_args) if self.metadata.is_chat_model: messages = self._get_messages(prompt, **prompt_args) chat_response = await self.astream_chat(messages) stream_tokens = await astream_chat_response_to_tokens(chat_response) else: formatted_prompt = self._get_prompt(prompt, **prompt_args) stream_response = await self.astream_complete( formatted_prompt, formatted=True ) stream_tokens = await astream_completion_response_to_tokens(stream_response) if prompt.output_parser is not None or self.output_parser is not None: raise NotImplementedError("Output parser is not supported for streaming.") return stream_tokens def _extend_prompt( self, formatted_prompt: str, ) -> str: """Add system and query wrapper prompts to base prompt.""" extended_prompt = formatted_prompt if self.system_prompt: extended_prompt = self.system_prompt + "\n\n" + extended_prompt if self.query_wrapper_prompt: extended_prompt = self.query_wrapper_prompt.format( query_str=extended_prompt ) return extended_prompt def _extend_messages(self, messages: List[ChatMessage]) -> List[ChatMessage]: """Add system prompt to chat message list.""" if self.system_prompt: messages = [ ChatMessage(role=MessageRole.SYSTEM, content=self.system_prompt), *messages, ] return messages def _as_query_component(self, **kwargs: Any) -> QueryComponent: """Return query component.""" if self.metadata.is_chat_model: return LLMChatComponent(llm=self, **kwargs) else: return LLMCompleteComponent(llm=self, **kwargs) class BaseLLMComponent(QueryComponent): """Base LLM component.""" llm: LLM = Field(..., description="LLM") streaming: bool = Field(default=False, description="Streaming mode") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: Any) -> None: """Set callback manager.""" self.llm.callback_manager = callback_manager class LLMCompleteComponent(BaseLLMComponent): """LLM completion component.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" if "prompt" not in input: raise ValueError("Prompt must be in input dict.") # do special check to see if prompt is a list of chat messages if isinstance(input["prompt"], get_args(List[ChatMessage])): input["prompt"] = self.llm.messages_to_prompt(input["prompt"]) input["prompt"] = validate_and_convert_stringable(input["prompt"]) else: input["prompt"] = validate_and_convert_stringable(input["prompt"]) input["prompt"] = self.llm.completion_to_prompt(input["prompt"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. prompt = kwargs["prompt"] # ignore all other kwargs for now if self.streaming: response = self.llm.stream_complete(prompt, formatted=True) else: response = self.llm.complete(prompt, formatted=True) return {"output": response} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. prompt = kwargs["prompt"] # ignore all other kwargs for now response = await self.llm.acomplete(prompt, formatted=True) return {"output": response} @property def input_keys(self) -> InputKeys: """Input keys.""" # TODO: support only complete for now return InputKeys.from_keys({"prompt"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class LLMChatComponent(BaseLLMComponent): """LLM chat component.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" if "messages" not in input: raise ValueError("Messages must be in input dict.") # if `messages` is a string, convert to a list of chat message if isinstance(input["messages"], get_args(StringableInput)): input["messages"] = validate_and_convert_stringable(input["messages"]) input["messages"] = prompt_to_messages(str(input["messages"])) for message in input["messages"]: if not isinstance(message, ChatMessage): raise ValueError("Messages must be a list of ChatMessage") return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. messages = kwargs["messages"] if self.streaming: response = self.llm.stream_chat(messages) else: response = self.llm.chat(messages) return {"output": response} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # TODO: support only complete for now # non-trivial to figure how to support chat/complete/etc. messages = kwargs["messages"] if self.streaming: response = await self.llm.astream_chat(messages) else: response = await self.llm.achat(messages) return {"output": response} @property def input_keys(self) -> InputKeys: """Input keys.""" # TODO: support only complete for now return InputKeys.from_keys({"messages"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"})
[ "llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable", "llama_index.legacy.program.utils.get_program_for_llm", "llama_index.legacy.bridge.pydantic.validator" ]
[((2828, 2891), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""System prompt for LLM calls."""'}), "(default=None, description='System prompt for LLM calls.')\n", (2833, 2891), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((2953, 3090), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Function to convert a list of messages to an LLM prompt."""', 'default': 'generic_messages_to_prompt', 'exclude': '(True)'}), "(description=\n 'Function to convert a list of messages to an LLM prompt.', default=\n generic_messages_to_prompt, exclude=True)\n", (2958, 3090), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3163, 3290), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Function to convert a completion to an LLM prompt."""', 'default': 'default_completion_to_prompt', 'exclude': '(True)'}), "(description='Function to convert a completion to an LLM prompt.',\n default=default_completion_to_prompt, exclude=True)\n", (3168, 3290), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3366, 3494), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Output parser to parse, validate, and correct errors programmatically."""', 'default': 'None', 'exclude': '(True)'}), "(description=\n 'Output parser to parse, validate, and correct errors programmatically.',\n default=None, exclude=True)\n", (3371, 3494), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3669, 3757), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Query wrapper prompt for LLM calls."""', 'default': 'None', 'exclude': '(True)'}), "(description='Query wrapper prompt for LLM calls.', default=None,\n exclude=True)\n", (3674, 3757), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((3791, 3832), 'llama_index.legacy.bridge.pydantic.validator', 'validator', (['"""messages_to_prompt"""'], {'pre': '(True)'}), "('messages_to_prompt', pre=True)\n", (3800, 3832), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((4030, 4073), 'llama_index.legacy.bridge.pydantic.validator', 'validator', (['"""completion_to_prompt"""'], {'pre': '(True)'}), "('completion_to_prompt', pre=True)\n", (4039, 4073), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((11157, 11186), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""LLM"""'}), "(..., description='LLM')\n", (11162, 11186), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((11209, 11259), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Streaming mode"""'}), "(default=False, description='Streaming mode')\n", (11214, 11259), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field, validator\n'), ((6014, 6114), 'llama_index.legacy.program.utils.get_program_for_llm', 'get_program_for_llm', (['output_cls', 'prompt', 'self'], {'pydantic_program_mode': 'self.pydantic_program_mode'}), '(output_cls, prompt, self, pydantic_program_mode=self.\n pydantic_program_mode)\n', (6033, 6114), False, 'from llama_index.legacy.program.utils import get_program_for_llm\n'), ((6461, 6561), 'llama_index.legacy.program.utils.get_program_for_llm', 'get_program_for_llm', (['output_cls', 'prompt', 'self'], {'pydantic_program_mode': 'self.pydantic_program_mode'}), '(output_cls, prompt, self, pydantic_program_mode=self.\n pydantic_program_mode)\n', (6480, 6561), False, 'from llama_index.legacy.program.utils import get_program_for_llm\n'), ((13294, 13325), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'prompt'}"], {}), "({'prompt'})\n", (13313, 13325), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((13424, 13456), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (13444, 13456), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((15250, 15283), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'messages'}"], {}), "({'messages'})\n", (15269, 15283), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((15382, 15414), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (15402, 15414), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((11912, 11939), 'typing.get_args', 'get_args', (['List[ChatMessage]'], {}), '(List[ChatMessage])\n', (11920, 11939), False, 'from typing import Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable\n'), ((12047, 12095), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['prompt']"], {}), "(input['prompt'])\n", (12078, 12095), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((12140, 12188), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['prompt']"], {}), "(input['prompt'])\n", (12171, 12188), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((13890, 13915), 'typing.get_args', 'get_args', (['StringableInput'], {}), '(StringableInput)\n', (13898, 13915), False, 'from typing import Any, Dict, List, Optional, Protocol, Sequence, get_args, runtime_checkable\n'), ((13950, 14000), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['messages']"], {}), "(input['messages'])\n", (13981, 14000), False, 'from llama_index.legacy.core.query_pipeline.query_component import InputKeys, OutputKeys, QueryComponent, StringableInput, validate_and_convert_stringable\n'), ((10661, 10725), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.SYSTEM', 'content': 'self.system_prompt'}), '(role=MessageRole.SYSTEM, content=self.system_prompt)\n', (10672, 10725), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponseAsyncGen, ChatResponseGen, CompletionResponseAsyncGen, CompletionResponseGen, MessageRole\n'), ((4449, 4485), 'collections.ChainMap', 'ChainMap', (['prompt.kwargs', 'prompt_args'], {}), '(prompt.kwargs, prompt_args)\n', (4457, 4485), False, 'from collections import ChainMap\n')]
"""Base reader class.""" from abc import ABC from typing import TYPE_CHECKING, Any, Dict, Iterable, List if TYPE_CHECKING: from llama_index.core.bridge.langchain import Document as LCDocument from llama_index.core.bridge.pydantic import Field from llama_index.core.schema import BaseComponent, Document class BaseReader(ABC): """Utilities for loading data from a directory.""" def lazy_load_data(self, *args: Any, **load_kwargs: Any) -> Iterable[Document]: """Load data from the input directory lazily.""" raise NotImplementedError( f"{self.__class__.__name__} does not provide lazy_load_data method currently" ) def load_data(self, *args: Any, **load_kwargs: Any) -> List[Document]: """Load data from the input directory.""" return list(self.lazy_load_data(*args, **load_kwargs)) def load_langchain_documents(self, **load_kwargs: Any) -> List["LCDocument"]: """Load data in LangChain document format.""" docs = self.load_data(**load_kwargs) return [d.to_langchain_format() for d in docs] class BasePydanticReader(BaseReader, BaseComponent): """Serialiable Data Loader with Pydantic.""" is_remote: bool = Field( default=False, description="Whether the data is loaded from a remote API or a local file.", ) class Config: arbitrary_types_allowed = True class ReaderConfig(BaseComponent): """Represents a reader and it's input arguments.""" reader: BasePydanticReader = Field(..., description="Reader to use.") reader_args: List[Any] = Field(default_factory=list, description="Reader args.") reader_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Reader kwargs." ) class Config: arbitrary_types_allowed = True @classmethod def class_name(cls) -> str: """Get the name identifier of the class.""" return "ReaderConfig" def to_dict(self, **kwargs: Any) -> Dict[str, Any]: """Convert the class to a dictionary.""" return { "loader": self.reader.to_dict(**kwargs), "reader_args": self.reader_args, "reader_kwargs": self.reader_kwargs, "class_name": self.class_name(), } def read(self) -> List[Document]: """Call the loader with the given arguments.""" return self.reader.load_data(*self.reader_args, **self.reader_kwargs)
[ "llama_index.core.bridge.pydantic.Field" ]
[((1219, 1321), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether the data is loaded from a remote API or a local file."""'}), "(default=False, description=\n 'Whether the data is loaded from a remote API or a local file.')\n", (1224, 1321), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((1525, 1565), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Reader to use."""'}), "(..., description='Reader to use.')\n", (1530, 1565), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((1595, 1650), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'list', 'description': '"""Reader args."""'}), "(default_factory=list, description='Reader args.')\n", (1600, 1650), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((1687, 1744), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Reader kwargs."""'}), "(default_factory=dict, description='Reader kwargs.')\n", (1692, 1744), False, 'from llama_index.core.bridge.pydantic import Field\n')]
"""Base object types.""" import pickle import warnings from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.vector_store.base import VectorStoreIndex from llama_index.core.objects.base_node_mapping import ( DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping, ) from llama_index.core.schema import QueryType from llama_index.core.storage.storage_context import ( DEFAULT_PERSIST_DIR, StorageContext, ) OT = TypeVar("OT") class ObjectRetriever(ChainableMixin, Generic[OT]): """Object retriever.""" def __init__( self, retriever: BaseRetriever, object_node_mapping: BaseObjectNodeMapping[OT] ): self._retriever = retriever self._object_node_mapping = object_node_mapping @property def retriever(self) -> BaseRetriever: """Retriever.""" return self._retriever def retrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = self._retriever.retrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] async def aretrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = await self._retriever.aretrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" return ObjectRetrieverComponent(retriever=self) class ObjectRetrieverComponent(QueryComponent): """Object retriever component.""" retriever: ObjectRetriever = Field(..., description="Retriever.") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" self.retriever.retriever.callback_manager = callback_manager def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" # make sure input is a string input["input"] = validate_and_convert_stringable(input["input"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" output = self.retriever.retrieve(kwargs["input"]) return {"output": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" output = await self.retriever.aretrieve(kwargs["input"]) return {"output": output} @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys({"input"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class ObjectIndex(Generic[OT]): """Object index.""" def __init__( self, index: BaseIndex, object_node_mapping: BaseObjectNodeMapping ) -> None: self._index = index self._object_node_mapping = object_node_mapping @classmethod def from_objects( cls, objects: Sequence[OT], object_mapping: Optional[BaseObjectNodeMapping] = None, index_cls: Type[BaseIndex] = VectorStoreIndex, **index_kwargs: Any, ) -> "ObjectIndex": if object_mapping is None: object_mapping = SimpleObjectNodeMapping.from_objects(objects) nodes = object_mapping.to_nodes(objects) index = index_cls(nodes, **index_kwargs) return cls(index, object_mapping) def insert_object(self, obj: Any) -> None: self._object_node_mapping.add_object(obj) node = self._object_node_mapping.to_node(obj) self._index.insert_nodes([node]) def as_retriever(self, **kwargs: Any) -> ObjectRetriever: return ObjectRetriever( retriever=self._index.as_retriever(**kwargs), object_node_mapping=self._object_node_mapping, ) def as_node_retriever(self, **kwargs: Any) -> BaseRetriever: return self._index.as_retriever(**kwargs) def persist( self, persist_dir: str = DEFAULT_PERSIST_DIR, obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME, ) -> None: # try to persist object node mapping try: self._object_node_mapping.persist( persist_dir=persist_dir, obj_node_mapping_fname=obj_node_mapping_fname ) except (NotImplementedError, pickle.PickleError) as err: warnings.warn( ( "Unable to persist ObjectNodeMapping. You will need to " "reconstruct the same object node mapping to build this ObjectIndex" ), stacklevel=2, ) self._index._storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls, persist_dir: str = DEFAULT_PERSIST_DIR, object_node_mapping: Optional[BaseObjectNodeMapping] = None, ) -> "ObjectIndex": from llama_index.core.indices import load_index_from_storage storage_context = StorageContext.from_defaults(persist_dir=persist_dir) index = load_index_from_storage(storage_context) if object_node_mapping: return cls(index=index, object_node_mapping=object_node_mapping) else: # try to load object_node_mapping # assume SimpleObjectNodeMapping for simplicity as its only subclass # that supports this method try: object_node_mapping = SimpleObjectNodeMapping.from_persist_dir( persist_dir=persist_dir ) except Exception as err: raise Exception( "Unable to load from persist dir. The object_node_mapping cannot be loaded." ) from err else: return cls(index=index, object_node_mapping=object_node_mapping)
[ "llama_index.core.indices.load_index_from_storage", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects", "llama_index.core.base.query_pipeline.query.InputKeys.from_keys", "llama_index.core.base.query_pipeline.query.OutputKeys.from_keys", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir", "llama_index.core.bridge.pydantic.Field", "llama_index.core.base.query_pipeline.query.validate_and_convert_stringable", "llama_index.core.storage.storage_context.StorageContext.from_defaults" ]
[((897, 910), 'typing.TypeVar', 'TypeVar', (['"""OT"""'], {}), "('OT')\n", (904, 910), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n'), ((2032, 2068), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Retriever."""'}), "(..., description='Retriever.')\n", (2037, 2068), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((2521, 2568), 'llama_index.core.base.query_pipeline.query.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['input']"], {}), "(input['input'])\n", (2552, 2568), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3055, 3085), 'llama_index.core.base.query_pipeline.query.InputKeys.from_keys', 'InputKeys.from_keys', (["{'input'}"], {}), "({'input'})\n", (3074, 3085), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3184, 3216), 'llama_index.core.base.query_pipeline.query.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (3204, 3216), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((5570, 5623), 'llama_index.core.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (5598, 5623), False, 'from llama_index.core.storage.storage_context import DEFAULT_PERSIST_DIR, StorageContext\n'), ((5640, 5680), 'llama_index.core.indices.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (5663, 5680), False, 'from llama_index.core.indices import load_index_from_storage\n'), ((3788, 3833), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects', 'SimpleObjectNodeMapping.from_objects', (['objects'], {}), '(objects)\n', (3824, 3833), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n'), ((4944, 5105), 'warnings.warn', 'warnings.warn', (['"""Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex"""'], {'stacklevel': '(2)'}), "(\n 'Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex'\n , stacklevel=2)\n", (4957, 5105), False, 'import warnings\n'), ((6026, 6091), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir', 'SimpleObjectNodeMapping.from_persist_dir', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (6066, 6091), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n')]
"""Base object types.""" import pickle import warnings from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.vector_store.base import VectorStoreIndex from llama_index.core.objects.base_node_mapping import ( DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping, ) from llama_index.core.schema import QueryType from llama_index.core.storage.storage_context import ( DEFAULT_PERSIST_DIR, StorageContext, ) OT = TypeVar("OT") class ObjectRetriever(ChainableMixin, Generic[OT]): """Object retriever.""" def __init__( self, retriever: BaseRetriever, object_node_mapping: BaseObjectNodeMapping[OT] ): self._retriever = retriever self._object_node_mapping = object_node_mapping @property def retriever(self) -> BaseRetriever: """Retriever.""" return self._retriever def retrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = self._retriever.retrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] async def aretrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = await self._retriever.aretrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" return ObjectRetrieverComponent(retriever=self) class ObjectRetrieverComponent(QueryComponent): """Object retriever component.""" retriever: ObjectRetriever = Field(..., description="Retriever.") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" self.retriever.retriever.callback_manager = callback_manager def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" # make sure input is a string input["input"] = validate_and_convert_stringable(input["input"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" output = self.retriever.retrieve(kwargs["input"]) return {"output": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" output = await self.retriever.aretrieve(kwargs["input"]) return {"output": output} @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys({"input"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class ObjectIndex(Generic[OT]): """Object index.""" def __init__( self, index: BaseIndex, object_node_mapping: BaseObjectNodeMapping ) -> None: self._index = index self._object_node_mapping = object_node_mapping @classmethod def from_objects( cls, objects: Sequence[OT], object_mapping: Optional[BaseObjectNodeMapping] = None, index_cls: Type[BaseIndex] = VectorStoreIndex, **index_kwargs: Any, ) -> "ObjectIndex": if object_mapping is None: object_mapping = SimpleObjectNodeMapping.from_objects(objects) nodes = object_mapping.to_nodes(objects) index = index_cls(nodes, **index_kwargs) return cls(index, object_mapping) def insert_object(self, obj: Any) -> None: self._object_node_mapping.add_object(obj) node = self._object_node_mapping.to_node(obj) self._index.insert_nodes([node]) def as_retriever(self, **kwargs: Any) -> ObjectRetriever: return ObjectRetriever( retriever=self._index.as_retriever(**kwargs), object_node_mapping=self._object_node_mapping, ) def as_node_retriever(self, **kwargs: Any) -> BaseRetriever: return self._index.as_retriever(**kwargs) def persist( self, persist_dir: str = DEFAULT_PERSIST_DIR, obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME, ) -> None: # try to persist object node mapping try: self._object_node_mapping.persist( persist_dir=persist_dir, obj_node_mapping_fname=obj_node_mapping_fname ) except (NotImplementedError, pickle.PickleError) as err: warnings.warn( ( "Unable to persist ObjectNodeMapping. You will need to " "reconstruct the same object node mapping to build this ObjectIndex" ), stacklevel=2, ) self._index._storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls, persist_dir: str = DEFAULT_PERSIST_DIR, object_node_mapping: Optional[BaseObjectNodeMapping] = None, ) -> "ObjectIndex": from llama_index.core.indices import load_index_from_storage storage_context = StorageContext.from_defaults(persist_dir=persist_dir) index = load_index_from_storage(storage_context) if object_node_mapping: return cls(index=index, object_node_mapping=object_node_mapping) else: # try to load object_node_mapping # assume SimpleObjectNodeMapping for simplicity as its only subclass # that supports this method try: object_node_mapping = SimpleObjectNodeMapping.from_persist_dir( persist_dir=persist_dir ) except Exception as err: raise Exception( "Unable to load from persist dir. The object_node_mapping cannot be loaded." ) from err else: return cls(index=index, object_node_mapping=object_node_mapping)
[ "llama_index.core.indices.load_index_from_storage", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects", "llama_index.core.base.query_pipeline.query.InputKeys.from_keys", "llama_index.core.base.query_pipeline.query.OutputKeys.from_keys", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir", "llama_index.core.bridge.pydantic.Field", "llama_index.core.base.query_pipeline.query.validate_and_convert_stringable", "llama_index.core.storage.storage_context.StorageContext.from_defaults" ]
[((897, 910), 'typing.TypeVar', 'TypeVar', (['"""OT"""'], {}), "('OT')\n", (904, 910), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n'), ((2032, 2068), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Retriever."""'}), "(..., description='Retriever.')\n", (2037, 2068), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((2521, 2568), 'llama_index.core.base.query_pipeline.query.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['input']"], {}), "(input['input'])\n", (2552, 2568), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3055, 3085), 'llama_index.core.base.query_pipeline.query.InputKeys.from_keys', 'InputKeys.from_keys', (["{'input'}"], {}), "({'input'})\n", (3074, 3085), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3184, 3216), 'llama_index.core.base.query_pipeline.query.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (3204, 3216), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((5570, 5623), 'llama_index.core.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (5598, 5623), False, 'from llama_index.core.storage.storage_context import DEFAULT_PERSIST_DIR, StorageContext\n'), ((5640, 5680), 'llama_index.core.indices.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (5663, 5680), False, 'from llama_index.core.indices import load_index_from_storage\n'), ((3788, 3833), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects', 'SimpleObjectNodeMapping.from_objects', (['objects'], {}), '(objects)\n', (3824, 3833), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n'), ((4944, 5105), 'warnings.warn', 'warnings.warn', (['"""Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex"""'], {'stacklevel': '(2)'}), "(\n 'Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex'\n , stacklevel=2)\n", (4957, 5105), False, 'import warnings\n'), ((6026, 6091), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir', 'SimpleObjectNodeMapping.from_persist_dir', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (6066, 6091), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n')]
"""Base object types.""" import pickle import warnings from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.bridge.pydantic import Field from llama_index.core.callbacks.base import CallbackManager from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.vector_store.base import VectorStoreIndex from llama_index.core.objects.base_node_mapping import ( DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping, ) from llama_index.core.schema import QueryType from llama_index.core.storage.storage_context import ( DEFAULT_PERSIST_DIR, StorageContext, ) OT = TypeVar("OT") class ObjectRetriever(ChainableMixin, Generic[OT]): """Object retriever.""" def __init__( self, retriever: BaseRetriever, object_node_mapping: BaseObjectNodeMapping[OT] ): self._retriever = retriever self._object_node_mapping = object_node_mapping @property def retriever(self) -> BaseRetriever: """Retriever.""" return self._retriever def retrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = self._retriever.retrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] async def aretrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = await self._retriever.aretrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" return ObjectRetrieverComponent(retriever=self) class ObjectRetrieverComponent(QueryComponent): """Object retriever component.""" retriever: ObjectRetriever = Field(..., description="Retriever.") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" self.retriever.retriever.callback_manager = callback_manager def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" # make sure input is a string input["input"] = validate_and_convert_stringable(input["input"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" output = self.retriever.retrieve(kwargs["input"]) return {"output": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" output = await self.retriever.aretrieve(kwargs["input"]) return {"output": output} @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys({"input"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class ObjectIndex(Generic[OT]): """Object index.""" def __init__( self, index: BaseIndex, object_node_mapping: BaseObjectNodeMapping ) -> None: self._index = index self._object_node_mapping = object_node_mapping @classmethod def from_objects( cls, objects: Sequence[OT], object_mapping: Optional[BaseObjectNodeMapping] = None, index_cls: Type[BaseIndex] = VectorStoreIndex, **index_kwargs: Any, ) -> "ObjectIndex": if object_mapping is None: object_mapping = SimpleObjectNodeMapping.from_objects(objects) nodes = object_mapping.to_nodes(objects) index = index_cls(nodes, **index_kwargs) return cls(index, object_mapping) def insert_object(self, obj: Any) -> None: self._object_node_mapping.add_object(obj) node = self._object_node_mapping.to_node(obj) self._index.insert_nodes([node]) def as_retriever(self, **kwargs: Any) -> ObjectRetriever: return ObjectRetriever( retriever=self._index.as_retriever(**kwargs), object_node_mapping=self._object_node_mapping, ) def as_node_retriever(self, **kwargs: Any) -> BaseRetriever: return self._index.as_retriever(**kwargs) def persist( self, persist_dir: str = DEFAULT_PERSIST_DIR, obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME, ) -> None: # try to persist object node mapping try: self._object_node_mapping.persist( persist_dir=persist_dir, obj_node_mapping_fname=obj_node_mapping_fname ) except (NotImplementedError, pickle.PickleError) as err: warnings.warn( ( "Unable to persist ObjectNodeMapping. You will need to " "reconstruct the same object node mapping to build this ObjectIndex" ), stacklevel=2, ) self._index._storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls, persist_dir: str = DEFAULT_PERSIST_DIR, object_node_mapping: Optional[BaseObjectNodeMapping] = None, ) -> "ObjectIndex": from llama_index.core.indices import load_index_from_storage storage_context = StorageContext.from_defaults(persist_dir=persist_dir) index = load_index_from_storage(storage_context) if object_node_mapping: return cls(index=index, object_node_mapping=object_node_mapping) else: # try to load object_node_mapping # assume SimpleObjectNodeMapping for simplicity as its only subclass # that supports this method try: object_node_mapping = SimpleObjectNodeMapping.from_persist_dir( persist_dir=persist_dir ) except Exception as err: raise Exception( "Unable to load from persist dir. The object_node_mapping cannot be loaded." ) from err else: return cls(index=index, object_node_mapping=object_node_mapping)
[ "llama_index.core.indices.load_index_from_storage", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects", "llama_index.core.base.query_pipeline.query.InputKeys.from_keys", "llama_index.core.base.query_pipeline.query.OutputKeys.from_keys", "llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir", "llama_index.core.bridge.pydantic.Field", "llama_index.core.base.query_pipeline.query.validate_and_convert_stringable", "llama_index.core.storage.storage_context.StorageContext.from_defaults" ]
[((897, 910), 'typing.TypeVar', 'TypeVar', (['"""OT"""'], {}), "('OT')\n", (904, 910), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n'), ((2032, 2068), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Retriever."""'}), "(..., description='Retriever.')\n", (2037, 2068), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((2521, 2568), 'llama_index.core.base.query_pipeline.query.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['input']"], {}), "(input['input'])\n", (2552, 2568), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3055, 3085), 'llama_index.core.base.query_pipeline.query.InputKeys.from_keys', 'InputKeys.from_keys', (["{'input'}"], {}), "({'input'})\n", (3074, 3085), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3184, 3216), 'llama_index.core.base.query_pipeline.query.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (3204, 3216), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((5570, 5623), 'llama_index.core.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (5598, 5623), False, 'from llama_index.core.storage.storage_context import DEFAULT_PERSIST_DIR, StorageContext\n'), ((5640, 5680), 'llama_index.core.indices.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (5663, 5680), False, 'from llama_index.core.indices import load_index_from_storage\n'), ((3788, 3833), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects', 'SimpleObjectNodeMapping.from_objects', (['objects'], {}), '(objects)\n', (3824, 3833), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n'), ((4944, 5105), 'warnings.warn', 'warnings.warn', (['"""Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex"""'], {'stacklevel': '(2)'}), "(\n 'Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex'\n , stacklevel=2)\n", (4957, 5105), False, 'import warnings\n'), ((6026, 6091), 'llama_index.core.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir', 'SimpleObjectNodeMapping.from_persist_dir', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (6066, 6091), False, 'from llama_index.core.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n')]
from typing import Any, Callable, Optional, Sequence from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.types import PydanticProgramMode class MockLLM(CustomLLM): max_tokens: Optional[int] def __init__( self, max_tokens: Optional[int] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, ) -> None: super().__init__( max_tokens=max_tokens, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, ) @classmethod def class_name(cls) -> str: return "MockLLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata(num_output=self.max_tokens or -1) def _generate_text(self, length: int) -> str: return " ".join(["text" for _ in range(length)]) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: response_text = ( self._generate_text(self.max_tokens) if self.max_tokens else prompt ) return CompletionResponse( text=response_text, ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: def gen_prompt() -> CompletionResponseGen: for ch in prompt: yield CompletionResponse( text=prompt, delta=ch, ) def gen_response(max_tokens: int) -> CompletionResponseGen: for i in range(max_tokens): response_text = self._generate_text(i) yield CompletionResponse( text=response_text, delta="text ", ) return gen_response(self.max_tokens) if self.max_tokens else gen_prompt()
[ "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.core.llms.types.LLMMetadata" ]
[((1537, 1562), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (1560, 1562), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((1876, 1901), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (1899, 1901), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((1377, 1422), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'num_output': '(self.max_tokens or -1)'}), '(num_output=self.max_tokens or -1)\n', (1388, 1422), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((1808, 1846), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response_text'}), '(text=response_text)\n', (1826, 1846), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2128, 2169), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'prompt', 'delta': 'ch'}), '(text=prompt, delta=ch)\n', (2146, 2169), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2415, 2468), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response_text', 'delta': '"""text """'}), "(text=response_text, delta='text ')\n", (2433, 2468), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n')]
from typing import Any, Callable, Optional, Sequence from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.types import PydanticProgramMode class MockLLM(CustomLLM): max_tokens: Optional[int] def __init__( self, max_tokens: Optional[int] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, ) -> None: super().__init__( max_tokens=max_tokens, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, ) @classmethod def class_name(cls) -> str: return "MockLLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata(num_output=self.max_tokens or -1) def _generate_text(self, length: int) -> str: return " ".join(["text" for _ in range(length)]) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: response_text = ( self._generate_text(self.max_tokens) if self.max_tokens else prompt ) return CompletionResponse( text=response_text, ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: def gen_prompt() -> CompletionResponseGen: for ch in prompt: yield CompletionResponse( text=prompt, delta=ch, ) def gen_response(max_tokens: int) -> CompletionResponseGen: for i in range(max_tokens): response_text = self._generate_text(i) yield CompletionResponse( text=response_text, delta="text ", ) return gen_response(self.max_tokens) if self.max_tokens else gen_prompt()
[ "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.core.llms.types.LLMMetadata" ]
[((1537, 1562), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (1560, 1562), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((1876, 1901), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (1899, 1901), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((1377, 1422), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'num_output': '(self.max_tokens or -1)'}), '(num_output=self.max_tokens or -1)\n', (1388, 1422), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((1808, 1846), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response_text'}), '(text=response_text)\n', (1826, 1846), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2128, 2169), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'prompt', 'delta': 'ch'}), '(text=prompt, delta=ch)\n', (2146, 2169), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2415, 2468), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response_text', 'delta': '"""text """'}), "(text=response_text, delta='text ')\n", (2433, 2468), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset("MiniCovidQaDataset", "./data") # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=40, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 319), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MiniCovidQaDataset"""', '"""./data"""'], {}), "('MiniCovidQaDataset', './data')\n", (287, 319), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((364, 416), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (395, 416), False, 'from llama_index.core import VectorStoreIndex\n'), ((509, 558), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack"""'], {}), "('RagEvaluatorPack', './pack')\n", (528, 558), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1409, 1433), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1431, 1433), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset("MiniCovidQaDataset", "./data") # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=40, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 319), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MiniCovidQaDataset"""', '"""./data"""'], {}), "('MiniCovidQaDataset', './data')\n", (287, 319), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((364, 416), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (395, 416), False, 'from llama_index.core import VectorStoreIndex\n'), ((509, 558), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack"""'], {}), "('RagEvaluatorPack', './pack')\n", (528, 558), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1409, 1433), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1431, 1433), False, 'import asyncio\n')]
"""Palm API.""" import os from typing import Any, Callable, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode DEFAULT_PALM_MODEL = "models/text-bison-001" class PaLM(CustomLLM): """PaLM LLM.""" model_name: str = Field( default=DEFAULT_PALM_MODEL, description="The PaLM model to use." ) num_output: int = Field( default=DEFAULT_NUM_OUTPUTS, description="The number of tokens to generate.", gt=0, ) generate_kwargs: dict = Field( default_factory=dict, description="Kwargs for generation." ) _model: Any = PrivateAttr() def __init__( self, api_key: Optional[str] = None, model_name: Optional[str] = DEFAULT_PALM_MODEL, num_output: Optional[int] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **generate_kwargs: Any, ) -> None: """Initialize params.""" try: import google.generativeai as palm except ImportError: raise ValueError( "PaLM is not installed. " "Please install it with `pip install google-generativeai`." ) api_key = api_key or os.environ.get("PALM_API_KEY") palm.configure(api_key=api_key) models = palm.list_models() models_dict = {m.name: m for m in models} if model_name not in models_dict: raise ValueError( f"Model name {model_name} not found in {models_dict.keys()}" ) model_name = model_name self._model = models_dict[model_name] # get num_output num_output = num_output or self._model.output_token_limit generate_kwargs = generate_kwargs or {} super().__init__( model_name=model_name, num_output=num_output, generate_kwargs=generate_kwargs, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "PaLM_llm" @property def metadata(self) -> LLMMetadata: """Get LLM metadata.""" # TODO: google palm actually separates input and output token limits total_tokens = self._model.input_token_limit + self.num_output return LLMMetadata( context_window=total_tokens, num_output=self.num_output, model_name=self.model_name, ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Predict the answer to a query. Args: prompt (str): Prompt to use for prediction. Returns: Tuple[str, str]: Tuple of the predicted answer and the formatted prompt. """ import google.generativeai as palm completion = palm.generate_text( model=self.model_name, prompt=prompt, **kwargs, ) return CompletionResponse(text=completion.result, raw=completion.candidates[0]) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Stream the answer to a query. NOTE: this is a beta feature. Will try to build or use better abstractions about response handling. Args: prompt (str): Prompt to use for prediction. Returns: str: The predicted answer. """ raise NotImplementedError( "PaLM does not support streaming completion in LlamaIndex currently." )
[ "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse" ]
[((708, 779), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_PALM_MODEL', 'description': '"""The PaLM model to use."""'}), "(default=DEFAULT_PALM_MODEL, description='The PaLM model to use.')\n", (713, 779), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((816, 910), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_NUM_OUTPUTS', 'description': '"""The number of tokens to generate."""', 'gt': '(0)'}), "(default=DEFAULT_NUM_OUTPUTS, description=\n 'The number of tokens to generate.', gt=0)\n", (821, 910), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((965, 1030), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Kwargs for generation."""'}), "(default_factory=dict, description='Kwargs for generation.')\n", (970, 1030), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1064, 1077), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1075, 1077), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3465, 3490), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3488, 3490), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((4106, 4131), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (4129, 4131), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((2045, 2076), 'google.generativeai.configure', 'palm.configure', ([], {'api_key': 'api_key'}), '(api_key=api_key)\n', (2059, 2076), True, 'import google.generativeai as palm\n'), ((2095, 2113), 'google.generativeai.list_models', 'palm.list_models', ([], {}), '()\n', (2111, 2113), True, 'import google.generativeai as palm\n'), ((3315, 3415), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'total_tokens', 'num_output': 'self.num_output', 'model_name': 'self.model_name'}), '(context_window=total_tokens, num_output=self.num_output,\n model_name=self.model_name)\n', (3326, 3415), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((3898, 3964), 'google.generativeai.generate_text', 'palm.generate_text', ([], {'model': 'self.model_name', 'prompt': 'prompt'}), '(model=self.model_name, prompt=prompt, **kwargs)\n', (3916, 3964), True, 'import google.generativeai as palm\n'), ((4027, 4099), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'completion.result', 'raw': 'completion.candidates[0]'}), '(text=completion.result, raw=completion.candidates[0])\n', (4045, 4099), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2006, 2036), 'os.environ.get', 'os.environ.get', (['"""PALM_API_KEY"""'], {}), "('PALM_API_KEY')\n", (2020, 2036), False, 'import os\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.ai21_utils import ai21_model_to_context_size from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.llms.generic_utils import ( completion_to_chat_decorator, get_from_param_or_env, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class AI21(CustomLLM): """AI21 Labs LLM.""" model: str = Field(description="The AI21 model to use.") maxTokens: int = Field(description="The maximum number of tokens to generate.") temperature: float = Field(description="The temperature to use for sampling.") additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the anthropic API." ) _api_key = PrivateAttr() def __init__( self, api_key: Optional[str] = None, model: Optional[str] = "j2-mid", maxTokens: Optional[int] = 512, temperature: Optional[float] = 0.1, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: """Initialize params.""" try: import ai21 as _ # noqa except ImportError as e: raise ImportError( "You must install the `ai21` package to use AI21." "Please `pip install ai21`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) api_key = get_from_param_or_env("api_key", api_key, "AI21_API_KEY") self._api_key = api_key super().__init__( model=model, maxTokens=maxTokens, temperature=temperature, additional_kwargs=additional_kwargs, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(self) -> str: """Get Class Name.""" return "AI21_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=ai21_model_to_context_size(self.model), num_output=self.maxTokens, model_name=self.model, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "maxTokens": self.maxTokens, "temperature": self.temperature, } return {**base_kwargs, **self.additional_kwargs} def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) import ai21 ai21.api_key = self._api_key response = ai21.Completion.execute(**all_kwargs, prompt=prompt) return CompletionResponse( text=response["completions"][0]["data"]["text"], raw=response.__dict__ ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise NotImplementedError( "AI21 does not currently support streaming completion." ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: all_kwargs = self._get_all_kwargs(**kwargs) chat_fn = completion_to_chat_decorator(self.complete) return chat_fn(messages, **all_kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise NotImplementedError("AI21 does not Currently Support Streaming Chat.")
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.get_from_param_or_env", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.ai21_utils.ai21_model_to_context_size", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator" ]
[((827, 870), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The AI21 model to use."""'}), "(description='The AI21 model to use.')\n", (832, 870), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((892, 954), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (897, 954), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((980, 1037), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (985, 1037), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1079, 1167), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the anthropic API."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the anthropic API.')\n", (1084, 1167), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1193, 1206), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1204, 1206), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3625, 3650), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3648, 3650), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4083, 4108), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (4106, 4108), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4351, 4370), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4368, 4370), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4623, 4642), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4640, 4642), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2296, 2353), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_key"""', 'api_key', '"""AI21_API_KEY"""'], {}), "('api_key', api_key, 'AI21_API_KEY')\n", (2317, 2353), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, get_from_param_or_env\n'), ((3895, 3947), 'ai21.Completion.execute', 'ai21.Completion.execute', ([], {'prompt': 'prompt'}), '(**all_kwargs, prompt=prompt)\n', (3918, 3947), False, 'import ai21\n'), ((3964, 4059), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': "response['completions'][0]['data']['text']", 'raw': 'response.__dict__'}), "(text=response['completions'][0]['data']['text'], raw=\n response.__dict__)\n", (3982, 4059), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((4525, 4568), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self.complete'], {}), '(self.complete)\n', (4553, 4568), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, get_from_param_or_env\n'), ((2257, 2276), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (2272, 2276), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((3075, 3113), 'llama_index.legacy.llms.ai21_utils.ai21_model_to_context_size', 'ai21_model_to_context_size', (['self.model'], {}), '(self.model)\n', (3101, 3113), False, 'from llama_index.legacy.llms.ai21_utils import ai21_model_to_context_size\n')]
import json from typing import Any, Callable, Dict, List, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( completion_response_to_chat_response, stream_completion_response_to_chat_response, ) from llama_index.legacy.llms.generic_utils import ( messages_to_prompt as generic_messages_to_prompt, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.vllm_utils import get_response, post_http_request from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Vllm(LLM): model: Optional[str] = Field(description="The HuggingFace Model to use.") temperature: float = Field(description="The temperature to use for sampling.") tensor_parallel_size: Optional[int] = Field( default=1, description="The number of GPUs to use for distributed execution with tensor parallelism.", ) trust_remote_code: Optional[bool] = Field( default=True, description="Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.", ) n: int = Field( default=1, description="Number of output sequences to return for the given prompt.", ) best_of: Optional[int] = Field( default=None, description="Number of output sequences that are generated from the prompt.", ) presence_penalty: float = Field( default=0.0, description="Float that penalizes new tokens based on whether they appear in the generated text so far.", ) frequency_penalty: float = Field( default=0.0, description="Float that penalizes new tokens based on their frequency in the generated text so far.", ) top_p: float = Field( default=1.0, description="Float that controls the cumulative probability of the top tokens to consider.", ) top_k: int = Field( default=-1, description="Integer that controls the number of top tokens to consider.", ) use_beam_search: bool = Field( default=False, description="Whether to use beam search instead of sampling." ) stop: Optional[List[str]] = Field( default=None, description="List of strings that stop the generation when they are generated.", ) ignore_eos: bool = Field( default=False, description="Whether to ignore the EOS token and continue generating tokens after the EOS token is generated.", ) max_new_tokens: int = Field( default=512, description="Maximum number of tokens to generate per output sequence.", ) logprobs: Optional[int] = Field( default=None, description="Number of log probabilities to return per output token.", ) dtype: str = Field( default="auto", description="The data type for the model weights and activations.", ) download_dir: Optional[str] = Field( default=None, description="Directory to download and load the weights. (Default to the default cache dir of huggingface)", ) vllm_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Holds any model parameters valid for `vllm.LLM` call not explicitly specified.", ) api_url: str = Field(description="The api url for vllm server") _client: Any = PrivateAttr() def __init__( self, model: str = "facebook/opt-125m", temperature: float = 1.0, tensor_parallel_size: int = 1, trust_remote_code: bool = True, n: int = 1, best_of: Optional[int] = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, top_p: float = 1.0, top_k: int = -1, use_beam_search: bool = False, stop: Optional[List[str]] = None, ignore_eos: bool = False, max_new_tokens: int = 512, logprobs: Optional[int] = None, dtype: str = "auto", download_dir: Optional[str] = None, vllm_kwargs: Dict[str, Any] = {}, api_url: Optional[str] = "", callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from vllm import LLM as VLLModel except ImportError: raise ImportError( "Could not import vllm python package. " "Please install it with `pip install vllm`." ) if model != "": self._client = VLLModel( model=model, tensor_parallel_size=tensor_parallel_size, trust_remote_code=trust_remote_code, dtype=dtype, download_dir=download_dir, **vllm_kwargs ) else: self._client = None callback_manager = callback_manager or CallbackManager([]) super().__init__( model=model, temperature=temperature, n=n, best_of=best_of, presence_penalty=presence_penalty, frequency_penalty=frequency_penalty, top_p=top_p, top_k=top_k, use_beam_search=use_beam_search, stop=stop, ignore_eos=ignore_eos, max_new_tokens=max_new_tokens, logprobs=logprobs, dtype=dtype, download_dir=download_dir, vllm_kwargs=vllm_kwargs, api_url=api_url, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "Vllm" @property def metadata(self) -> LLMMetadata: return LLMMetadata(model_name=self.model) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, "max_tokens": self.max_new_tokens, "n": self.n, "frequency_penalty": self.frequency_penalty, "presence_penalty": self.presence_penalty, "use_beam_search": self.use_beam_search, "best_of": self.best_of, "ignore_eos": self.ignore_eos, "stop": self.stop, "logprobs": self.logprobs, "top_k": self.top_k, "top_p": self.top_p, "stop": self.stop, } return {**base_kwargs} def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: kwargs = kwargs if kwargs else {} prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, **kwargs) return completion_response_to_chat_response(completion_response) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params) outputs = self._client.generate([prompt], sampling_params) return CompletionResponse(text=outputs[0].outputs[0].text) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise (ValueError("Not Implemented")) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise (ValueError("Not Implemented")) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: kwargs = kwargs if kwargs else {} return self.chat(messages, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise (ValueError("Not Implemented")) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise (ValueError("Not Implemented")) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise (ValueError("Not Implemented")) class VllmServer(Vllm): def __init__( self, model: str = "facebook/opt-125m", api_url: str = "http://localhost:8000", temperature: float = 1.0, tensor_parallel_size: Optional[int] = 1, trust_remote_code: Optional[bool] = True, n: int = 1, best_of: Optional[int] = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, top_p: float = 1.0, top_k: int = -1, use_beam_search: bool = False, stop: Optional[List[str]] = None, ignore_eos: bool = False, max_new_tokens: int = 512, logprobs: Optional[int] = None, dtype: str = "auto", download_dir: Optional[str] = None, messages_to_prompt: Optional[Callable] = None, completion_to_prompt: Optional[Callable] = None, vllm_kwargs: Dict[str, Any] = {}, callback_manager: Optional[CallbackManager] = None, output_parser: Optional[BaseOutputParser] = None, ) -> None: self._client = None messages_to_prompt = messages_to_prompt or generic_messages_to_prompt completion_to_prompt = completion_to_prompt or (lambda x: x) callback_manager = callback_manager or CallbackManager([]) model = "" super().__init__( model=model, temperature=temperature, n=n, best_of=best_of, presence_penalty=presence_penalty, frequency_penalty=frequency_penalty, top_p=top_p, top_k=top_k, use_beam_search=use_beam_search, stop=stop, ignore_eos=ignore_eos, max_new_tokens=max_new_tokens, logprobs=logprobs, dtype=dtype, download_dir=download_dir, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, vllm_kwargs=vllm_kwargs, api_url=api_url, callback_manager=callback_manager, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "VllmServer" @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> List[CompletionResponse]: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt response = post_http_request(self.api_url, sampling_params, stream=False) output = get_response(response) return CompletionResponse(text=output[0]) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt response = post_http_request(self.api_url, sampling_params, stream=True) def gen() -> CompletionResponseGen: for chunk in response.iter_lines( chunk_size=8192, decode_unicode=False, delimiter=b"\0" ): if chunk: data = json.loads(chunk.decode("utf-8")) yield CompletionResponse(text=data["text"][0]) return gen() @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: kwargs = kwargs if kwargs else {} return self.complete(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt async def gen() -> CompletionResponseAsyncGen: for message in self.stream_complete(prompt, **kwargs): yield message return gen() @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: prompt = self.messages_to_prompt(messages) completion_response = self.stream_complete(prompt, **kwargs) return stream_completion_response_to_chat_response(completion_response) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: return self.stream_chat(messages, **kwargs)
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.llms.vllm_utils.get_response", "llama_index.legacy.llms.generic_utils.completion_response_to_chat_response", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.vllm_utils.post_http_request" ]
[((1015, 1065), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The HuggingFace Model to use."""'}), "(description='The HuggingFace Model to use.')\n", (1020, 1065), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1092, 1149), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1097, 1149), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1193, 1311), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1)', 'description': '"""The number of GPUs to use for distributed execution with tensor parallelism."""'}), "(default=1, description=\n 'The number of GPUs to use for distributed execution with tensor parallelism.'\n )\n", (1198, 1311), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1366, 1495), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(True)', 'description': '"""Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer."""'}), "(default=True, description=\n 'Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.'\n )\n", (1371, 1495), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1523, 1618), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1)', 'description': '"""Number of output sequences to return for the given prompt."""'}), "(default=1, description=\n 'Number of output sequences to return for the given prompt.')\n", (1528, 1618), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1667, 1769), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Number of output sequences that are generated from the prompt."""'}), "(default=None, description=\n 'Number of output sequences that are generated from the prompt.')\n", (1672, 1769), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1819, 1953), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.0)', 'description': '"""Float that penalizes new tokens based on whether they appear in the generated text so far."""'}), "(default=0.0, description=\n 'Float that penalizes new tokens based on whether they appear in the generated text so far.'\n )\n", (1824, 1953), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1999, 2129), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.0)', 'description': '"""Float that penalizes new tokens based on their frequency in the generated text so far."""'}), "(default=0.0, description=\n 'Float that penalizes new tokens based on their frequency in the generated text so far.'\n )\n", (2004, 2129), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2163, 2284), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1.0)', 'description': '"""Float that controls the cumulative probability of the top tokens to consider."""'}), "(default=1.0, description=\n 'Float that controls the cumulative probability of the top tokens to consider.'\n )\n", (2168, 2284), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2316, 2413), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(-1)', 'description': '"""Integer that controls the number of top tokens to consider."""'}), "(default=-1, description=\n 'Integer that controls the number of top tokens to consider.')\n", (2321, 2413), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2461, 2549), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to use beam search instead of sampling."""'}), "(default=False, description=\n 'Whether to use beam search instead of sampling.')\n", (2466, 2549), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2592, 2697), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""List of strings that stop the generation when they are generated."""'}), "(default=None, description=\n 'List of strings that stop the generation when they are generated.')\n", (2597, 2697), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2740, 2882), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to ignore the EOS token and continue generating tokens after the EOS token is generated."""'}), "(default=False, description=\n 'Whether to ignore the EOS token and continue generating tokens after the EOS token is generated.'\n )\n", (2745, 2882), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2923, 3019), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(512)', 'description': '"""Maximum number of tokens to generate per output sequence."""'}), "(default=512, description=\n 'Maximum number of tokens to generate per output sequence.')\n", (2928, 3019), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3069, 3164), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Number of log probabilities to return per output token."""'}), "(default=None, description=\n 'Number of log probabilities to return per output token.')\n", (3074, 3164), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3201, 3295), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""auto"""', 'description': '"""The data type for the model weights and activations."""'}), "(default='auto', description=\n 'The data type for the model weights and activations.')\n", (3206, 3295), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3349, 3487), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Directory to download and load the weights. (Default to the default cache dir of huggingface)"""'}), "(default=None, description=\n 'Directory to download and load the weights. (Default to the default cache dir of huggingface)'\n )\n", (3354, 3487), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3536, 3667), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Holds any model parameters valid for `vllm.LLM` call not explicitly specified."""'}), "(default_factory=dict, description=\n 'Holds any model parameters valid for `vllm.LLM` call not explicitly specified.'\n )\n", (3541, 3667), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3701, 3749), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The api url for vllm server"""'}), "(description='The api url for vllm server')\n", (3706, 3749), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3770, 3783), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3781, 3783), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((7427, 7446), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (7444, 7446), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7765, 7790), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7788, 7790), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8265, 8284), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8282, 8284), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8445, 8470), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8468, 8470), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8646, 8665), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8663, 8665), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8864, 8889), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8887, 8889), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9062, 9081), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9079, 9081), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9254, 9279), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (9277, 9279), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((11620, 11645), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (11643, 11645), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12217, 12242), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (12240, 12242), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13080, 13105), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13103, 13105), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13321, 13346), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13344, 13346), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13936, 13955), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (13953, 13955), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((14270, 14289), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (14287, 14289), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6582, 6616), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'model_name': 'self.model'}), '(model_name=self.model)\n', (6593, 6616), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((7701, 7758), 'llama_index.legacy.llms.generic_utils.completion_response_to_chat_response', 'completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (7737, 7758), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((8100, 8124), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (8114, 8124), False, 'from vllm import SamplingParams\n'), ((8207, 8258), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'outputs[0].outputs[0].text'}), '(text=outputs[0].outputs[0].text)\n', (8225, 8258), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((12057, 12119), 'llama_index.legacy.llms.vllm_utils.post_http_request', 'post_http_request', (['self.api_url', 'sampling_params'], {'stream': '(False)'}), '(self.api_url, sampling_params, stream=False)\n', (12074, 12119), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((12137, 12159), 'llama_index.legacy.llms.vllm_utils.get_response', 'get_response', (['response'], {}), '(response)\n', (12149, 12159), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((12176, 12210), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'output[0]'}), '(text=output[0])\n', (12194, 12210), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((12658, 12719), 'llama_index.legacy.llms.vllm_utils.post_http_request', 'post_http_request', (['self.api_url', 'sampling_params'], {'stream': '(True)'}), '(self.api_url, sampling_params, stream=True)\n', (12675, 12719), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((14199, 14263), 'llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response', 'stream_completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (14242, 14263), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((5219, 5384), 'vllm.LLM', 'VLLModel', ([], {'model': 'model', 'tensor_parallel_size': 'tensor_parallel_size', 'trust_remote_code': 'trust_remote_code', 'dtype': 'dtype', 'download_dir': 'download_dir'}), '(model=model, tensor_parallel_size=tensor_parallel_size,\n trust_remote_code=trust_remote_code, dtype=dtype, download_dir=\n download_dir, **vllm_kwargs)\n', (5227, 5384), True, 'from vllm import LLM as VLLModel\n'), ((5579, 5598), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (5594, 5598), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((10705, 10724), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (10720, 10724), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((11961, 11985), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (11975, 11985), False, 'from vllm import SamplingParams\n'), ((12562, 12586), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (12576, 12586), False, 'from vllm import SamplingParams\n'), ((13678, 13702), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (13692, 13702), False, 'from vllm import SamplingParams\n'), ((13011, 13051), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': "data['text'][0]"}), "(text=data['text'][0])\n", (13029, 13051), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
import json from typing import Any, Callable, Dict, List, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( completion_response_to_chat_response, stream_completion_response_to_chat_response, ) from llama_index.legacy.llms.generic_utils import ( messages_to_prompt as generic_messages_to_prompt, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.vllm_utils import get_response, post_http_request from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Vllm(LLM): model: Optional[str] = Field(description="The HuggingFace Model to use.") temperature: float = Field(description="The temperature to use for sampling.") tensor_parallel_size: Optional[int] = Field( default=1, description="The number of GPUs to use for distributed execution with tensor parallelism.", ) trust_remote_code: Optional[bool] = Field( default=True, description="Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.", ) n: int = Field( default=1, description="Number of output sequences to return for the given prompt.", ) best_of: Optional[int] = Field( default=None, description="Number of output sequences that are generated from the prompt.", ) presence_penalty: float = Field( default=0.0, description="Float that penalizes new tokens based on whether they appear in the generated text so far.", ) frequency_penalty: float = Field( default=0.0, description="Float that penalizes new tokens based on their frequency in the generated text so far.", ) top_p: float = Field( default=1.0, description="Float that controls the cumulative probability of the top tokens to consider.", ) top_k: int = Field( default=-1, description="Integer that controls the number of top tokens to consider.", ) use_beam_search: bool = Field( default=False, description="Whether to use beam search instead of sampling." ) stop: Optional[List[str]] = Field( default=None, description="List of strings that stop the generation when they are generated.", ) ignore_eos: bool = Field( default=False, description="Whether to ignore the EOS token and continue generating tokens after the EOS token is generated.", ) max_new_tokens: int = Field( default=512, description="Maximum number of tokens to generate per output sequence.", ) logprobs: Optional[int] = Field( default=None, description="Number of log probabilities to return per output token.", ) dtype: str = Field( default="auto", description="The data type for the model weights and activations.", ) download_dir: Optional[str] = Field( default=None, description="Directory to download and load the weights. (Default to the default cache dir of huggingface)", ) vllm_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Holds any model parameters valid for `vllm.LLM` call not explicitly specified.", ) api_url: str = Field(description="The api url for vllm server") _client: Any = PrivateAttr() def __init__( self, model: str = "facebook/opt-125m", temperature: float = 1.0, tensor_parallel_size: int = 1, trust_remote_code: bool = True, n: int = 1, best_of: Optional[int] = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, top_p: float = 1.0, top_k: int = -1, use_beam_search: bool = False, stop: Optional[List[str]] = None, ignore_eos: bool = False, max_new_tokens: int = 512, logprobs: Optional[int] = None, dtype: str = "auto", download_dir: Optional[str] = None, vllm_kwargs: Dict[str, Any] = {}, api_url: Optional[str] = "", callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from vllm import LLM as VLLModel except ImportError: raise ImportError( "Could not import vllm python package. " "Please install it with `pip install vllm`." ) if model != "": self._client = VLLModel( model=model, tensor_parallel_size=tensor_parallel_size, trust_remote_code=trust_remote_code, dtype=dtype, download_dir=download_dir, **vllm_kwargs ) else: self._client = None callback_manager = callback_manager or CallbackManager([]) super().__init__( model=model, temperature=temperature, n=n, best_of=best_of, presence_penalty=presence_penalty, frequency_penalty=frequency_penalty, top_p=top_p, top_k=top_k, use_beam_search=use_beam_search, stop=stop, ignore_eos=ignore_eos, max_new_tokens=max_new_tokens, logprobs=logprobs, dtype=dtype, download_dir=download_dir, vllm_kwargs=vllm_kwargs, api_url=api_url, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "Vllm" @property def metadata(self) -> LLMMetadata: return LLMMetadata(model_name=self.model) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, "max_tokens": self.max_new_tokens, "n": self.n, "frequency_penalty": self.frequency_penalty, "presence_penalty": self.presence_penalty, "use_beam_search": self.use_beam_search, "best_of": self.best_of, "ignore_eos": self.ignore_eos, "stop": self.stop, "logprobs": self.logprobs, "top_k": self.top_k, "top_p": self.top_p, "stop": self.stop, } return {**base_kwargs} def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: kwargs = kwargs if kwargs else {} prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, **kwargs) return completion_response_to_chat_response(completion_response) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params) outputs = self._client.generate([prompt], sampling_params) return CompletionResponse(text=outputs[0].outputs[0].text) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise (ValueError("Not Implemented")) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise (ValueError("Not Implemented")) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: kwargs = kwargs if kwargs else {} return self.chat(messages, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise (ValueError("Not Implemented")) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise (ValueError("Not Implemented")) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise (ValueError("Not Implemented")) class VllmServer(Vllm): def __init__( self, model: str = "facebook/opt-125m", api_url: str = "http://localhost:8000", temperature: float = 1.0, tensor_parallel_size: Optional[int] = 1, trust_remote_code: Optional[bool] = True, n: int = 1, best_of: Optional[int] = None, presence_penalty: float = 0.0, frequency_penalty: float = 0.0, top_p: float = 1.0, top_k: int = -1, use_beam_search: bool = False, stop: Optional[List[str]] = None, ignore_eos: bool = False, max_new_tokens: int = 512, logprobs: Optional[int] = None, dtype: str = "auto", download_dir: Optional[str] = None, messages_to_prompt: Optional[Callable] = None, completion_to_prompt: Optional[Callable] = None, vllm_kwargs: Dict[str, Any] = {}, callback_manager: Optional[CallbackManager] = None, output_parser: Optional[BaseOutputParser] = None, ) -> None: self._client = None messages_to_prompt = messages_to_prompt or generic_messages_to_prompt completion_to_prompt = completion_to_prompt or (lambda x: x) callback_manager = callback_manager or CallbackManager([]) model = "" super().__init__( model=model, temperature=temperature, n=n, best_of=best_of, presence_penalty=presence_penalty, frequency_penalty=frequency_penalty, top_p=top_p, top_k=top_k, use_beam_search=use_beam_search, stop=stop, ignore_eos=ignore_eos, max_new_tokens=max_new_tokens, logprobs=logprobs, dtype=dtype, download_dir=download_dir, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, vllm_kwargs=vllm_kwargs, api_url=api_url, callback_manager=callback_manager, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "VllmServer" @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> List[CompletionResponse]: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt response = post_http_request(self.api_url, sampling_params, stream=False) output = get_response(response) return CompletionResponse(text=output[0]) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt response = post_http_request(self.api_url, sampling_params, stream=True) def gen() -> CompletionResponseGen: for chunk in response.iter_lines( chunk_size=8192, decode_unicode=False, delimiter=b"\0" ): if chunk: data = json.loads(chunk.decode("utf-8")) yield CompletionResponse(text=data["text"][0]) return gen() @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: kwargs = kwargs if kwargs else {} return self.complete(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: kwargs = kwargs if kwargs else {} params = {**self._model_kwargs, **kwargs} from vllm import SamplingParams # build sampling parameters sampling_params = SamplingParams(**params).__dict__ sampling_params["prompt"] = prompt async def gen() -> CompletionResponseAsyncGen: for message in self.stream_complete(prompt, **kwargs): yield message return gen() @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: prompt = self.messages_to_prompt(messages) completion_response = self.stream_complete(prompt, **kwargs) return stream_completion_response_to_chat_response(completion_response) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: return self.stream_chat(messages, **kwargs)
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.llms.vllm_utils.get_response", "llama_index.legacy.llms.generic_utils.completion_response_to_chat_response", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.vllm_utils.post_http_request" ]
[((1015, 1065), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The HuggingFace Model to use."""'}), "(description='The HuggingFace Model to use.')\n", (1020, 1065), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1092, 1149), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1097, 1149), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1193, 1311), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1)', 'description': '"""The number of GPUs to use for distributed execution with tensor parallelism."""'}), "(default=1, description=\n 'The number of GPUs to use for distributed execution with tensor parallelism.'\n )\n", (1198, 1311), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1366, 1495), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(True)', 'description': '"""Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer."""'}), "(default=True, description=\n 'Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.'\n )\n", (1371, 1495), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1523, 1618), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1)', 'description': '"""Number of output sequences to return for the given prompt."""'}), "(default=1, description=\n 'Number of output sequences to return for the given prompt.')\n", (1528, 1618), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1667, 1769), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Number of output sequences that are generated from the prompt."""'}), "(default=None, description=\n 'Number of output sequences that are generated from the prompt.')\n", (1672, 1769), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1819, 1953), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.0)', 'description': '"""Float that penalizes new tokens based on whether they appear in the generated text so far."""'}), "(default=0.0, description=\n 'Float that penalizes new tokens based on whether they appear in the generated text so far.'\n )\n", (1824, 1953), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1999, 2129), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.0)', 'description': '"""Float that penalizes new tokens based on their frequency in the generated text so far."""'}), "(default=0.0, description=\n 'Float that penalizes new tokens based on their frequency in the generated text so far.'\n )\n", (2004, 2129), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2163, 2284), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(1.0)', 'description': '"""Float that controls the cumulative probability of the top tokens to consider."""'}), "(default=1.0, description=\n 'Float that controls the cumulative probability of the top tokens to consider.'\n )\n", (2168, 2284), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2316, 2413), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(-1)', 'description': '"""Integer that controls the number of top tokens to consider."""'}), "(default=-1, description=\n 'Integer that controls the number of top tokens to consider.')\n", (2321, 2413), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2461, 2549), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to use beam search instead of sampling."""'}), "(default=False, description=\n 'Whether to use beam search instead of sampling.')\n", (2466, 2549), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2592, 2697), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""List of strings that stop the generation when they are generated."""'}), "(default=None, description=\n 'List of strings that stop the generation when they are generated.')\n", (2597, 2697), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2740, 2882), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to ignore the EOS token and continue generating tokens after the EOS token is generated."""'}), "(default=False, description=\n 'Whether to ignore the EOS token and continue generating tokens after the EOS token is generated.'\n )\n", (2745, 2882), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2923, 3019), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(512)', 'description': '"""Maximum number of tokens to generate per output sequence."""'}), "(default=512, description=\n 'Maximum number of tokens to generate per output sequence.')\n", (2928, 3019), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3069, 3164), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Number of log probabilities to return per output token."""'}), "(default=None, description=\n 'Number of log probabilities to return per output token.')\n", (3074, 3164), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3201, 3295), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""auto"""', 'description': '"""The data type for the model weights and activations."""'}), "(default='auto', description=\n 'The data type for the model weights and activations.')\n", (3206, 3295), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3349, 3487), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Directory to download and load the weights. (Default to the default cache dir of huggingface)"""'}), "(default=None, description=\n 'Directory to download and load the weights. (Default to the default cache dir of huggingface)'\n )\n", (3354, 3487), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3536, 3667), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Holds any model parameters valid for `vllm.LLM` call not explicitly specified."""'}), "(default_factory=dict, description=\n 'Holds any model parameters valid for `vllm.LLM` call not explicitly specified.'\n )\n", (3541, 3667), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3701, 3749), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The api url for vllm server"""'}), "(description='The api url for vllm server')\n", (3706, 3749), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3770, 3783), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3781, 3783), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((7427, 7446), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (7444, 7446), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7765, 7790), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7788, 7790), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8265, 8284), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8282, 8284), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8445, 8470), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8468, 8470), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8646, 8665), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8663, 8665), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8864, 8889), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8887, 8889), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9062, 9081), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9079, 9081), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9254, 9279), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (9277, 9279), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((11620, 11645), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (11643, 11645), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12217, 12242), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (12240, 12242), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13080, 13105), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13103, 13105), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13321, 13346), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13344, 13346), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13936, 13955), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (13953, 13955), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((14270, 14289), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (14287, 14289), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6582, 6616), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'model_name': 'self.model'}), '(model_name=self.model)\n', (6593, 6616), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((7701, 7758), 'llama_index.legacy.llms.generic_utils.completion_response_to_chat_response', 'completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (7737, 7758), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((8100, 8124), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (8114, 8124), False, 'from vllm import SamplingParams\n'), ((8207, 8258), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'outputs[0].outputs[0].text'}), '(text=outputs[0].outputs[0].text)\n', (8225, 8258), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((12057, 12119), 'llama_index.legacy.llms.vllm_utils.post_http_request', 'post_http_request', (['self.api_url', 'sampling_params'], {'stream': '(False)'}), '(self.api_url, sampling_params, stream=False)\n', (12074, 12119), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((12137, 12159), 'llama_index.legacy.llms.vllm_utils.get_response', 'get_response', (['response'], {}), '(response)\n', (12149, 12159), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((12176, 12210), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'output[0]'}), '(text=output[0])\n', (12194, 12210), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((12658, 12719), 'llama_index.legacy.llms.vllm_utils.post_http_request', 'post_http_request', (['self.api_url', 'sampling_params'], {'stream': '(True)'}), '(self.api_url, sampling_params, stream=True)\n', (12675, 12719), False, 'from llama_index.legacy.llms.vllm_utils import get_response, post_http_request\n'), ((14199, 14263), 'llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response', 'stream_completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (14242, 14263), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((5219, 5384), 'vllm.LLM', 'VLLModel', ([], {'model': 'model', 'tensor_parallel_size': 'tensor_parallel_size', 'trust_remote_code': 'trust_remote_code', 'dtype': 'dtype', 'download_dir': 'download_dir'}), '(model=model, tensor_parallel_size=tensor_parallel_size,\n trust_remote_code=trust_remote_code, dtype=dtype, download_dir=\n download_dir, **vllm_kwargs)\n', (5227, 5384), True, 'from vllm import LLM as VLLModel\n'), ((5579, 5598), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (5594, 5598), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((10705, 10724), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (10720, 10724), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((11961, 11985), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (11975, 11985), False, 'from vllm import SamplingParams\n'), ((12562, 12586), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (12576, 12586), False, 'from vllm import SamplingParams\n'), ((13678, 13702), 'vllm.SamplingParams', 'SamplingParams', ([], {}), '(**params)\n', (13692, 13702), False, 'from vllm import SamplingParams\n'), ((13011, 13051), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': "data['text'][0]"}), "(text=data['text'][0])\n", (13029, 13051), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
"""Prompts.""" from abc import ABC, abstractmethod from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, ) from llama_index.core.bridge.pydantic import Field if TYPE_CHECKING: from llama_index.core.bridge.langchain import ( BasePromptTemplate as LangchainTemplate, ) # pants: no-infer-dep from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) from llama_index.core.base.llms.types import ChatMessage from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.generic_utils import ( messages_to_prompt as default_messages_to_prompt, ) from llama_index.core.base.llms.generic_utils import ( prompt_to_messages, ) from llama_index.core.prompts.prompt_type import PromptType from llama_index.core.prompts.utils import get_template_vars from llama_index.core.types import BaseOutputParser class BasePromptTemplate(ChainableMixin, BaseModel, ABC): metadata: Dict[str, Any] template_vars: List[str] kwargs: Dict[str, str] output_parser: Optional[BaseOutputParser] template_var_mappings: Optional[Dict[str, Any]] = Field( default_factory=dict, description="Template variable mappings (Optional)." ) function_mappings: Optional[Dict[str, Callable]] = Field( default_factory=dict, description=( "Function mappings (Optional). This is a mapping from template " "variable names to functions that take in the current kwargs and " "return a string." ), ) def _map_template_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """For keys in template_var_mappings, swap in the right keys.""" template_var_mappings = self.template_var_mappings or {} return {template_var_mappings.get(k, k): v for k, v in kwargs.items()} def _map_function_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """For keys in function_mappings, compute values and combine w/ kwargs. Users can pass in functions instead of fixed values as format variables. For each function, we call the function with the current kwargs, get back the value, and then use that value in the template for the corresponding format variable. """ function_mappings = self.function_mappings or {} # first generate the values for the functions new_kwargs = {} for k, v in function_mappings.items(): # TODO: figure out what variables to pass into each function # is it the kwargs specified during query time? just the fixed kwargs? # all kwargs? new_kwargs[k] = v(**kwargs) # then, add the fixed variables only if not in new_kwargs already # (implying that function mapping will override fixed variables) for k, v in kwargs.items(): if k not in new_kwargs: new_kwargs[k] = v return new_kwargs def _map_all_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """Map both template and function variables. We (1) first call function mappings to compute functions, and then (2) call the template_var_mappings. """ # map function new_kwargs = self._map_function_vars(kwargs) # map template vars (to point to existing format vars in string template) return self._map_template_vars(new_kwargs) class Config: arbitrary_types_allowed = True @abstractmethod def partial_format(self, **kwargs: Any) -> "BasePromptTemplate": ... @abstractmethod def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: ... @abstractmethod def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: ... @abstractmethod def get_template(self, llm: Optional[BaseLLM] = None) -> str: ... def _as_query_component( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> QueryComponent: """As query component.""" return PromptComponent(prompt=self, format_messages=False, llm=llm) class PromptTemplate(BasePromptTemplate): template: str def __init__( self, template: str, prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, **kwargs: Any, ) -> None: if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type template_vars = get_template_vars(template) super().__init__( template=template, template_vars=template_vars, kwargs=kwargs, metadata=metadata, output_parser=output_parser, template_var_mappings=template_var_mappings, function_mappings=function_mappings, ) def partial_format(self, **kwargs: Any) -> "PromptTemplate": """Partially format the prompt.""" # NOTE: this is a hack to get around deepcopy failing on output parser output_parser = self.output_parser self.output_parser = None # get function and fixed kwargs, and add that to a copy # of the current prompt object prompt = deepcopy(self) prompt.kwargs.update(kwargs) # NOTE: put the output parser back prompt.output_parser = output_parser self.output_parser = output_parser return prompt def format( self, llm: Optional[BaseLLM] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, **kwargs: Any, ) -> str: """Format the prompt into a string.""" del llm # unused all_kwargs = { **self.kwargs, **kwargs, } mapped_all_kwargs = self._map_all_vars(all_kwargs) prompt = self.template.format(**mapped_all_kwargs) if self.output_parser is not None: prompt = self.output_parser.format(prompt) if completion_to_prompt is not None: prompt = completion_to_prompt(prompt) return prompt def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" del llm # unused prompt = self.format(**kwargs) return prompt_to_messages(prompt) def get_template(self, llm: Optional[BaseLLM] = None) -> str: return self.template class ChatPromptTemplate(BasePromptTemplate): message_templates: List[ChatMessage] def __init__( self, message_templates: List[ChatMessage], prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, **kwargs: Any, ): if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type template_vars = [] for message_template in message_templates: template_vars.extend(get_template_vars(message_template.content or "")) super().__init__( message_templates=message_templates, kwargs=kwargs, metadata=metadata, output_parser=output_parser, template_vars=template_vars, template_var_mappings=template_var_mappings, function_mappings=function_mappings, ) @classmethod def from_messages( cls, message_templates: Union[List[Tuple[str, str]], List[ChatMessage]], **kwargs: Any, ) -> "ChatPromptTemplate": """From messages.""" if isinstance(message_templates[0], tuple): message_templates = [ ChatMessage.from_str(role=role, content=content) for role, content in message_templates ] return cls(message_templates=message_templates, **kwargs) def partial_format(self, **kwargs: Any) -> "ChatPromptTemplate": prompt = deepcopy(self) prompt.kwargs.update(kwargs) return prompt def format( self, llm: Optional[BaseLLM] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, **kwargs: Any, ) -> str: del llm # unused messages = self.format_messages(**kwargs) if messages_to_prompt is not None: return messages_to_prompt(messages) return default_messages_to_prompt(messages) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: del llm # unused """Format the prompt into a list of chat messages.""" all_kwargs = { **self.kwargs, **kwargs, } mapped_all_kwargs = self._map_all_vars(all_kwargs) messages: List[ChatMessage] = [] for message_template in self.message_templates: template_vars = get_template_vars(message_template.content or "") relevant_kwargs = { k: v for k, v in mapped_all_kwargs.items() if k in template_vars } content_template = message_template.content or "" # if there's mappings specified, make sure those are used content = content_template.format(**relevant_kwargs) message: ChatMessage = message_template.copy() message.content = content messages.append(message) if self.output_parser is not None: messages = self.output_parser.format_messages(messages) return messages def get_template(self, llm: Optional[BaseLLM] = None) -> str: return default_messages_to_prompt(self.message_templates) def _as_query_component( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> QueryComponent: """As query component.""" return PromptComponent(prompt=self, format_messages=True, llm=llm) class SelectorPromptTemplate(BasePromptTemplate): default_template: BasePromptTemplate conditionals: Optional[ List[Tuple[Callable[[BaseLLM], bool], BasePromptTemplate]] ] = None def __init__( self, default_template: BasePromptTemplate, conditionals: Optional[ List[Tuple[Callable[[BaseLLM], bool], BasePromptTemplate]] ] = None, ): metadata = default_template.metadata kwargs = default_template.kwargs template_vars = default_template.template_vars output_parser = default_template.output_parser super().__init__( default_template=default_template, conditionals=conditionals, metadata=metadata, kwargs=kwargs, template_vars=template_vars, output_parser=output_parser, ) def select(self, llm: Optional[BaseLLM] = None) -> BasePromptTemplate: # ensure output parser is up to date self.default_template.output_parser = self.output_parser if llm is None: return self.default_template if self.conditionals is not None: for condition, prompt in self.conditionals: if condition(llm): # ensure output parser is up to date prompt.output_parser = self.output_parser return prompt return self.default_template def partial_format(self, **kwargs: Any) -> "SelectorPromptTemplate": default_template = self.default_template.partial_format(**kwargs) if self.conditionals is None: conditionals = None else: conditionals = [ (condition, prompt.partial_format(**kwargs)) for condition, prompt in self.conditionals ] return SelectorPromptTemplate( default_template=default_template, conditionals=conditionals ) def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: """Format the prompt into a string.""" prompt = self.select(llm=llm) return prompt.format(**kwargs) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" prompt = self.select(llm=llm) return prompt.format_messages(**kwargs) def get_template(self, llm: Optional[BaseLLM] = None) -> str: prompt = self.select(llm=llm) return prompt.get_template(llm=llm) class LangchainPromptTemplate(BasePromptTemplate): selector: Any requires_langchain_llm: bool = False def __init__( self, template: Optional["LangchainTemplate"] = None, selector: Optional["LangchainSelector"] = None, output_parser: Optional[BaseOutputParser] = None, prompt_type: str = PromptType.CUSTOM, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, requires_langchain_llm: bool = False, ) -> None: try: from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) except ImportError: raise ImportError( "Must install `llama_index[langchain]` to use LangchainPromptTemplate." ) if selector is None: if template is None: raise ValueError("Must provide either template or selector.") selector = LangchainSelector(default_prompt=template) else: if template is not None: raise ValueError("Must provide either template or selector.") selector = selector kwargs = selector.default_prompt.partial_variables template_vars = selector.default_prompt.input_variables if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type super().__init__( selector=selector, metadata=metadata, kwargs=kwargs, template_vars=template_vars, output_parser=output_parser, template_var_mappings=template_var_mappings, function_mappings=function_mappings, requires_langchain_llm=requires_langchain_llm, ) def partial_format(self, **kwargs: Any) -> "BasePromptTemplate": """Partially format the prompt.""" from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) mapped_kwargs = self._map_all_vars(kwargs) default_prompt = self.selector.default_prompt.partial(**mapped_kwargs) conditionals = [ (condition, prompt.partial(**mapped_kwargs)) for condition, prompt in self.selector.conditionals ] lc_selector = LangchainSelector( default_prompt=default_prompt, conditionals=conditionals ) # copy full prompt object, replace selector lc_prompt = deepcopy(self) lc_prompt.selector = lc_selector return lc_prompt def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: """Format the prompt into a string.""" from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt # if there's mappings specified, make sure those are used mapped_kwargs = self._map_all_vars(kwargs) return lc_template.format(**mapped_kwargs) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep from llama_index.llms.langchain.utils import ( from_lc_messages, ) # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt # if there's mappings specified, make sure those are used mapped_kwargs = self._map_all_vars(kwargs) lc_prompt_value = lc_template.format_prompt(**mapped_kwargs) lc_messages = lc_prompt_value.to_messages() return from_lc_messages(lc_messages) def get_template(self, llm: Optional[BaseLLM] = None) -> str: from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt try: return str(lc_template.template) # type: ignore except AttributeError: return str(lc_template) # NOTE: only for backwards compatibility Prompt = PromptTemplate class PromptComponent(QueryComponent): """Prompt component.""" prompt: BasePromptTemplate = Field(..., description="Prompt") llm: Optional[BaseLLM] = Field( default=None, description="LLM to use for formatting prompt." ) format_messages: bool = Field( default=False, description="Whether to format the prompt into a list of chat messages.", ) class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: Any) -> None: """Set callback manager.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" keys = list(input.keys()) for k in keys: input[k] = validate_and_convert_stringable(input[k]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" if self.format_messages: output: Union[str, List[ChatMessage]] = self.prompt.format_messages( llm=self.llm, **kwargs ) else: output = self.prompt.format(llm=self.llm, **kwargs) return {"prompt": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # NOTE: no native async for prompt return self._run_component(**kwargs) @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys( set(self.prompt.template_vars) - set(self.prompt.kwargs) ) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"prompt"})
[ "llama_index.llms.langchain.utils.from_lc_messages", "llama_index.core.base.query_pipeline.query.OutputKeys.from_keys", "llama_index.core.bridge.pydantic.Field", "llama_index.core.bridge.langchain.ConditionalPromptSelector", "llama_index.core.base.query_pipeline.query.validate_and_convert_stringable", "llama_index.core.base.llms.generic_utils.messages_to_prompt", "llama_index.core.base.llms.types.ChatMessage.from_str", "llama_index.core.prompts.utils.get_template_vars", "llama_index.core.base.llms.generic_utils.prompt_to_messages" ]
[((1473, 1559), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Template variable mappings (Optional)."""'}), "(default_factory=dict, description=\n 'Template variable mappings (Optional).')\n", (1478, 1559), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((1624, 1819), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Function mappings (Optional). This is a mapping from template variable names to functions that take in the current kwargs and return a string."""'}), "(default_factory=dict, description=\n 'Function mappings (Optional). This is a mapping from template variable names to functions that take in the current kwargs and return a string.'\n )\n", (1629, 1819), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19377, 19409), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Prompt"""'}), "(..., description='Prompt')\n", (19382, 19409), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19439, 19507), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""LLM to use for formatting prompt."""'}), "(default=None, description='LLM to use for formatting prompt.')\n", (19444, 19507), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19550, 19649), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to format the prompt into a list of chat messages."""'}), "(default=False, description=\n 'Whether to format the prompt into a list of chat messages.')\n", (19555, 19649), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((5075, 5102), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (['template'], {}), '(template)\n', (5092, 5102), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((5803, 5817), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (5811, 5817), False, 'from copy import deepcopy\n'), ((6932, 6958), 'llama_index.core.base.llms.generic_utils.prompt_to_messages', 'prompt_to_messages', (['prompt'], {}), '(prompt)\n', (6950, 6958), False, 'from llama_index.core.base.llms.generic_utils import prompt_to_messages\n'), ((8719, 8733), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (8727, 8733), False, 'from copy import deepcopy\n'), ((9169, 9205), 'llama_index.core.base.llms.generic_utils.messages_to_prompt', 'default_messages_to_prompt', (['messages'], {}), '(messages)\n', (9195, 9205), True, 'from llama_index.core.base.llms.generic_utils import messages_to_prompt as default_messages_to_prompt\n'), ((10403, 10453), 'llama_index.core.base.llms.generic_utils.messages_to_prompt', 'default_messages_to_prompt', (['self.message_templates'], {}), '(self.message_templates)\n', (10429, 10453), True, 'from llama_index.core.base.llms.generic_utils import messages_to_prompt as default_messages_to_prompt\n'), ((15675, 15750), 'llama_index.core.bridge.langchain.ConditionalPromptSelector', 'LangchainSelector', ([], {'default_prompt': 'default_prompt', 'conditionals': 'conditionals'}), '(default_prompt=default_prompt, conditionals=conditionals)\n', (15692, 15750), True, 'from llama_index.core.bridge.langchain import ConditionalPromptSelector as LangchainSelector\n'), ((15846, 15860), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (15854, 15860), False, 'from copy import deepcopy\n'), ((18234, 18263), 'llama_index.llms.langchain.utils.from_lc_messages', 'from_lc_messages', (['lc_messages'], {}), '(lc_messages)\n', (18250, 18263), False, 'from llama_index.llms.langchain.utils import from_lc_messages\n'), ((20950, 20982), 'llama_index.core.base.query_pipeline.query.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'prompt'}"], {}), "({'prompt'})\n", (20970, 20982), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((9674, 9723), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (["(message_template.content or '')"], {}), "(message_template.content or '')\n", (9691, 9723), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((14324, 14366), 'llama_index.core.bridge.langchain.ConditionalPromptSelector', 'LangchainSelector', ([], {'default_prompt': 'template'}), '(default_prompt=template)\n', (14341, 14366), True, 'from llama_index.core.bridge.langchain import ConditionalPromptSelector as LangchainSelector\n'), ((20056, 20097), 'llama_index.core.base.query_pipeline.query.validate_and_convert_stringable', 'validate_and_convert_stringable', (['input[k]'], {}), '(input[k])\n', (20087, 20097), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((7750, 7799), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (["(message_template.content or '')"], {}), "(message_template.content or '')\n", (7767, 7799), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((8448, 8496), 'llama_index.core.base.llms.types.ChatMessage.from_str', 'ChatMessage.from_str', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (8468, 8496), False, 'from llama_index.core.base.llms.types import ChatMessage\n')]
"""Prompts.""" from abc import ABC, abstractmethod from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, ) from llama_index.core.bridge.pydantic import Field if TYPE_CHECKING: from llama_index.core.bridge.langchain import ( BasePromptTemplate as LangchainTemplate, ) # pants: no-infer-dep from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) from llama_index.core.base.llms.types import ChatMessage from llama_index.core.base.query_pipeline.query import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.base.llms.base import BaseLLM from llama_index.core.base.llms.generic_utils import ( messages_to_prompt as default_messages_to_prompt, ) from llama_index.core.base.llms.generic_utils import ( prompt_to_messages, ) from llama_index.core.prompts.prompt_type import PromptType from llama_index.core.prompts.utils import get_template_vars from llama_index.core.types import BaseOutputParser class BasePromptTemplate(ChainableMixin, BaseModel, ABC): metadata: Dict[str, Any] template_vars: List[str] kwargs: Dict[str, str] output_parser: Optional[BaseOutputParser] template_var_mappings: Optional[Dict[str, Any]] = Field( default_factory=dict, description="Template variable mappings (Optional)." ) function_mappings: Optional[Dict[str, Callable]] = Field( default_factory=dict, description=( "Function mappings (Optional). This is a mapping from template " "variable names to functions that take in the current kwargs and " "return a string." ), ) def _map_template_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """For keys in template_var_mappings, swap in the right keys.""" template_var_mappings = self.template_var_mappings or {} return {template_var_mappings.get(k, k): v for k, v in kwargs.items()} def _map_function_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """For keys in function_mappings, compute values and combine w/ kwargs. Users can pass in functions instead of fixed values as format variables. For each function, we call the function with the current kwargs, get back the value, and then use that value in the template for the corresponding format variable. """ function_mappings = self.function_mappings or {} # first generate the values for the functions new_kwargs = {} for k, v in function_mappings.items(): # TODO: figure out what variables to pass into each function # is it the kwargs specified during query time? just the fixed kwargs? # all kwargs? new_kwargs[k] = v(**kwargs) # then, add the fixed variables only if not in new_kwargs already # (implying that function mapping will override fixed variables) for k, v in kwargs.items(): if k not in new_kwargs: new_kwargs[k] = v return new_kwargs def _map_all_vars(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: """Map both template and function variables. We (1) first call function mappings to compute functions, and then (2) call the template_var_mappings. """ # map function new_kwargs = self._map_function_vars(kwargs) # map template vars (to point to existing format vars in string template) return self._map_template_vars(new_kwargs) class Config: arbitrary_types_allowed = True @abstractmethod def partial_format(self, **kwargs: Any) -> "BasePromptTemplate": ... @abstractmethod def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: ... @abstractmethod def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: ... @abstractmethod def get_template(self, llm: Optional[BaseLLM] = None) -> str: ... def _as_query_component( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> QueryComponent: """As query component.""" return PromptComponent(prompt=self, format_messages=False, llm=llm) class PromptTemplate(BasePromptTemplate): template: str def __init__( self, template: str, prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, **kwargs: Any, ) -> None: if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type template_vars = get_template_vars(template) super().__init__( template=template, template_vars=template_vars, kwargs=kwargs, metadata=metadata, output_parser=output_parser, template_var_mappings=template_var_mappings, function_mappings=function_mappings, ) def partial_format(self, **kwargs: Any) -> "PromptTemplate": """Partially format the prompt.""" # NOTE: this is a hack to get around deepcopy failing on output parser output_parser = self.output_parser self.output_parser = None # get function and fixed kwargs, and add that to a copy # of the current prompt object prompt = deepcopy(self) prompt.kwargs.update(kwargs) # NOTE: put the output parser back prompt.output_parser = output_parser self.output_parser = output_parser return prompt def format( self, llm: Optional[BaseLLM] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, **kwargs: Any, ) -> str: """Format the prompt into a string.""" del llm # unused all_kwargs = { **self.kwargs, **kwargs, } mapped_all_kwargs = self._map_all_vars(all_kwargs) prompt = self.template.format(**mapped_all_kwargs) if self.output_parser is not None: prompt = self.output_parser.format(prompt) if completion_to_prompt is not None: prompt = completion_to_prompt(prompt) return prompt def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" del llm # unused prompt = self.format(**kwargs) return prompt_to_messages(prompt) def get_template(self, llm: Optional[BaseLLM] = None) -> str: return self.template class ChatPromptTemplate(BasePromptTemplate): message_templates: List[ChatMessage] def __init__( self, message_templates: List[ChatMessage], prompt_type: str = PromptType.CUSTOM, output_parser: Optional[BaseOutputParser] = None, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, **kwargs: Any, ): if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type template_vars = [] for message_template in message_templates: template_vars.extend(get_template_vars(message_template.content or "")) super().__init__( message_templates=message_templates, kwargs=kwargs, metadata=metadata, output_parser=output_parser, template_vars=template_vars, template_var_mappings=template_var_mappings, function_mappings=function_mappings, ) @classmethod def from_messages( cls, message_templates: Union[List[Tuple[str, str]], List[ChatMessage]], **kwargs: Any, ) -> "ChatPromptTemplate": """From messages.""" if isinstance(message_templates[0], tuple): message_templates = [ ChatMessage.from_str(role=role, content=content) for role, content in message_templates ] return cls(message_templates=message_templates, **kwargs) def partial_format(self, **kwargs: Any) -> "ChatPromptTemplate": prompt = deepcopy(self) prompt.kwargs.update(kwargs) return prompt def format( self, llm: Optional[BaseLLM] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, **kwargs: Any, ) -> str: del llm # unused messages = self.format_messages(**kwargs) if messages_to_prompt is not None: return messages_to_prompt(messages) return default_messages_to_prompt(messages) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: del llm # unused """Format the prompt into a list of chat messages.""" all_kwargs = { **self.kwargs, **kwargs, } mapped_all_kwargs = self._map_all_vars(all_kwargs) messages: List[ChatMessage] = [] for message_template in self.message_templates: template_vars = get_template_vars(message_template.content or "") relevant_kwargs = { k: v for k, v in mapped_all_kwargs.items() if k in template_vars } content_template = message_template.content or "" # if there's mappings specified, make sure those are used content = content_template.format(**relevant_kwargs) message: ChatMessage = message_template.copy() message.content = content messages.append(message) if self.output_parser is not None: messages = self.output_parser.format_messages(messages) return messages def get_template(self, llm: Optional[BaseLLM] = None) -> str: return default_messages_to_prompt(self.message_templates) def _as_query_component( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> QueryComponent: """As query component.""" return PromptComponent(prompt=self, format_messages=True, llm=llm) class SelectorPromptTemplate(BasePromptTemplate): default_template: BasePromptTemplate conditionals: Optional[ List[Tuple[Callable[[BaseLLM], bool], BasePromptTemplate]] ] = None def __init__( self, default_template: BasePromptTemplate, conditionals: Optional[ List[Tuple[Callable[[BaseLLM], bool], BasePromptTemplate]] ] = None, ): metadata = default_template.metadata kwargs = default_template.kwargs template_vars = default_template.template_vars output_parser = default_template.output_parser super().__init__( default_template=default_template, conditionals=conditionals, metadata=metadata, kwargs=kwargs, template_vars=template_vars, output_parser=output_parser, ) def select(self, llm: Optional[BaseLLM] = None) -> BasePromptTemplate: # ensure output parser is up to date self.default_template.output_parser = self.output_parser if llm is None: return self.default_template if self.conditionals is not None: for condition, prompt in self.conditionals: if condition(llm): # ensure output parser is up to date prompt.output_parser = self.output_parser return prompt return self.default_template def partial_format(self, **kwargs: Any) -> "SelectorPromptTemplate": default_template = self.default_template.partial_format(**kwargs) if self.conditionals is None: conditionals = None else: conditionals = [ (condition, prompt.partial_format(**kwargs)) for condition, prompt in self.conditionals ] return SelectorPromptTemplate( default_template=default_template, conditionals=conditionals ) def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: """Format the prompt into a string.""" prompt = self.select(llm=llm) return prompt.format(**kwargs) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" prompt = self.select(llm=llm) return prompt.format_messages(**kwargs) def get_template(self, llm: Optional[BaseLLM] = None) -> str: prompt = self.select(llm=llm) return prompt.get_template(llm=llm) class LangchainPromptTemplate(BasePromptTemplate): selector: Any requires_langchain_llm: bool = False def __init__( self, template: Optional["LangchainTemplate"] = None, selector: Optional["LangchainSelector"] = None, output_parser: Optional[BaseOutputParser] = None, prompt_type: str = PromptType.CUSTOM, metadata: Optional[Dict[str, Any]] = None, template_var_mappings: Optional[Dict[str, Any]] = None, function_mappings: Optional[Dict[str, Callable]] = None, requires_langchain_llm: bool = False, ) -> None: try: from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) except ImportError: raise ImportError( "Must install `llama_index[langchain]` to use LangchainPromptTemplate." ) if selector is None: if template is None: raise ValueError("Must provide either template or selector.") selector = LangchainSelector(default_prompt=template) else: if template is not None: raise ValueError("Must provide either template or selector.") selector = selector kwargs = selector.default_prompt.partial_variables template_vars = selector.default_prompt.input_variables if metadata is None: metadata = {} metadata["prompt_type"] = prompt_type super().__init__( selector=selector, metadata=metadata, kwargs=kwargs, template_vars=template_vars, output_parser=output_parser, template_var_mappings=template_var_mappings, function_mappings=function_mappings, requires_langchain_llm=requires_langchain_llm, ) def partial_format(self, **kwargs: Any) -> "BasePromptTemplate": """Partially format the prompt.""" from llama_index.core.bridge.langchain import ( ConditionalPromptSelector as LangchainSelector, ) mapped_kwargs = self._map_all_vars(kwargs) default_prompt = self.selector.default_prompt.partial(**mapped_kwargs) conditionals = [ (condition, prompt.partial(**mapped_kwargs)) for condition, prompt in self.selector.conditionals ] lc_selector = LangchainSelector( default_prompt=default_prompt, conditionals=conditionals ) # copy full prompt object, replace selector lc_prompt = deepcopy(self) lc_prompt.selector = lc_selector return lc_prompt def format(self, llm: Optional[BaseLLM] = None, **kwargs: Any) -> str: """Format the prompt into a string.""" from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt # if there's mappings specified, make sure those are used mapped_kwargs = self._map_all_vars(kwargs) return lc_template.format(**mapped_kwargs) def format_messages( self, llm: Optional[BaseLLM] = None, **kwargs: Any ) -> List[ChatMessage]: """Format the prompt into a list of chat messages.""" from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep from llama_index.llms.langchain.utils import ( from_lc_messages, ) # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt # if there's mappings specified, make sure those are used mapped_kwargs = self._map_all_vars(kwargs) lc_prompt_value = lc_template.format_prompt(**mapped_kwargs) lc_messages = lc_prompt_value.to_messages() return from_lc_messages(lc_messages) def get_template(self, llm: Optional[BaseLLM] = None) -> str: from llama_index.llms.langchain import LangChainLLM # pants: no-infer-dep if llm is not None: # if llamaindex LLM is provided, and we require a langchain LLM, # then error. but otherwise if `requires_langchain_llm` is False, # then we can just use the default prompt if not isinstance(llm, LangChainLLM) and self.requires_langchain_llm: raise ValueError("Must provide a LangChainLLM.") elif not isinstance(llm, LangChainLLM): lc_template = self.selector.default_prompt else: lc_template = self.selector.get_prompt(llm=llm.llm) else: lc_template = self.selector.default_prompt try: return str(lc_template.template) # type: ignore except AttributeError: return str(lc_template) # NOTE: only for backwards compatibility Prompt = PromptTemplate class PromptComponent(QueryComponent): """Prompt component.""" prompt: BasePromptTemplate = Field(..., description="Prompt") llm: Optional[BaseLLM] = Field( default=None, description="LLM to use for formatting prompt." ) format_messages: bool = Field( default=False, description="Whether to format the prompt into a list of chat messages.", ) class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: Any) -> None: """Set callback manager.""" def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" keys = list(input.keys()) for k in keys: input[k] = validate_and_convert_stringable(input[k]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" if self.format_messages: output: Union[str, List[ChatMessage]] = self.prompt.format_messages( llm=self.llm, **kwargs ) else: output = self.prompt.format(llm=self.llm, **kwargs) return {"prompt": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component.""" # NOTE: no native async for prompt return self._run_component(**kwargs) @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys( set(self.prompt.template_vars) - set(self.prompt.kwargs) ) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"prompt"})
[ "llama_index.llms.langchain.utils.from_lc_messages", "llama_index.core.base.query_pipeline.query.OutputKeys.from_keys", "llama_index.core.bridge.pydantic.Field", "llama_index.core.bridge.langchain.ConditionalPromptSelector", "llama_index.core.base.query_pipeline.query.validate_and_convert_stringable", "llama_index.core.base.llms.generic_utils.messages_to_prompt", "llama_index.core.base.llms.types.ChatMessage.from_str", "llama_index.core.prompts.utils.get_template_vars", "llama_index.core.base.llms.generic_utils.prompt_to_messages" ]
[((1473, 1559), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Template variable mappings (Optional)."""'}), "(default_factory=dict, description=\n 'Template variable mappings (Optional).')\n", (1478, 1559), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((1624, 1819), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Function mappings (Optional). This is a mapping from template variable names to functions that take in the current kwargs and return a string."""'}), "(default_factory=dict, description=\n 'Function mappings (Optional). This is a mapping from template variable names to functions that take in the current kwargs and return a string.'\n )\n", (1629, 1819), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19377, 19409), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Prompt"""'}), "(..., description='Prompt')\n", (19382, 19409), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19439, 19507), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""LLM to use for formatting prompt."""'}), "(default=None, description='LLM to use for formatting prompt.')\n", (19444, 19507), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((19550, 19649), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether to format the prompt into a list of chat messages."""'}), "(default=False, description=\n 'Whether to format the prompt into a list of chat messages.')\n", (19555, 19649), False, 'from llama_index.core.bridge.pydantic import Field\n'), ((5075, 5102), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (['template'], {}), '(template)\n', (5092, 5102), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((5803, 5817), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (5811, 5817), False, 'from copy import deepcopy\n'), ((6932, 6958), 'llama_index.core.base.llms.generic_utils.prompt_to_messages', 'prompt_to_messages', (['prompt'], {}), '(prompt)\n', (6950, 6958), False, 'from llama_index.core.base.llms.generic_utils import prompt_to_messages\n'), ((8719, 8733), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (8727, 8733), False, 'from copy import deepcopy\n'), ((9169, 9205), 'llama_index.core.base.llms.generic_utils.messages_to_prompt', 'default_messages_to_prompt', (['messages'], {}), '(messages)\n', (9195, 9205), True, 'from llama_index.core.base.llms.generic_utils import messages_to_prompt as default_messages_to_prompt\n'), ((10403, 10453), 'llama_index.core.base.llms.generic_utils.messages_to_prompt', 'default_messages_to_prompt', (['self.message_templates'], {}), '(self.message_templates)\n', (10429, 10453), True, 'from llama_index.core.base.llms.generic_utils import messages_to_prompt as default_messages_to_prompt\n'), ((15675, 15750), 'llama_index.core.bridge.langchain.ConditionalPromptSelector', 'LangchainSelector', ([], {'default_prompt': 'default_prompt', 'conditionals': 'conditionals'}), '(default_prompt=default_prompt, conditionals=conditionals)\n', (15692, 15750), True, 'from llama_index.core.bridge.langchain import ConditionalPromptSelector as LangchainSelector\n'), ((15846, 15860), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (15854, 15860), False, 'from copy import deepcopy\n'), ((18234, 18263), 'llama_index.llms.langchain.utils.from_lc_messages', 'from_lc_messages', (['lc_messages'], {}), '(lc_messages)\n', (18250, 18263), False, 'from llama_index.llms.langchain.utils import from_lc_messages\n'), ((20950, 20982), 'llama_index.core.base.query_pipeline.query.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'prompt'}"], {}), "({'prompt'})\n", (20970, 20982), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((9674, 9723), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (["(message_template.content or '')"], {}), "(message_template.content or '')\n", (9691, 9723), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((14324, 14366), 'llama_index.core.bridge.langchain.ConditionalPromptSelector', 'LangchainSelector', ([], {'default_prompt': 'template'}), '(default_prompt=template)\n', (14341, 14366), True, 'from llama_index.core.bridge.langchain import ConditionalPromptSelector as LangchainSelector\n'), ((20056, 20097), 'llama_index.core.base.query_pipeline.query.validate_and_convert_stringable', 'validate_and_convert_stringable', (['input[k]'], {}), '(input[k])\n', (20087, 20097), False, 'from llama_index.core.base.query_pipeline.query import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((7750, 7799), 'llama_index.core.prompts.utils.get_template_vars', 'get_template_vars', (["(message_template.content or '')"], {}), "(message_template.content or '')\n", (7767, 7799), False, 'from llama_index.core.prompts.utils import get_template_vars\n'), ((8448, 8496), 'llama_index.core.base.llms.types.ChatMessage.from_str', 'ChatMessage.from_str', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (8468, 8496), False, 'from llama_index.core.base.llms.types import ChatMessage\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex from llama_index.llms import OpenAI async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "Uber10KDataset2021", "./uber10k_2021_dataset" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") judge_llm = OpenAI(model="gpt-3.5-turbo") rag_evaluator = RagEvaluatorPack( query_engine=query_engine, rag_dataset=rag_dataset, judge_llm=judge_llm ) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.llms.OpenAI", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((301, 371), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""Uber10KDataset2021"""', '"""./uber10k_2021_dataset"""'], {}), "('Uber10KDataset2021', './uber10k_2021_dataset')\n", (323, 371), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((430, 482), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (461, 482), False, 'from llama_index.core import VectorStoreIndex\n'), ((575, 630), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (594, 630), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((647, 676), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'model': '"""gpt-3.5-turbo"""'}), "(model='gpt-3.5-turbo')\n", (653, 676), False, 'from llama_index.llms import OpenAI\n'), ((1562, 1586), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1584, 1586), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex from llama_index.llms import OpenAI async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "Uber10KDataset2021", "./uber10k_2021_dataset" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") judge_llm = OpenAI(model="gpt-3.5-turbo") rag_evaluator = RagEvaluatorPack( query_engine=query_engine, rag_dataset=rag_dataset, judge_llm=judge_llm ) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.llms.OpenAI", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((301, 371), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""Uber10KDataset2021"""', '"""./uber10k_2021_dataset"""'], {}), "('Uber10KDataset2021', './uber10k_2021_dataset')\n", (323, 371), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((430, 482), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (461, 482), False, 'from llama_index.core import VectorStoreIndex\n'), ((575, 630), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (594, 630), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((647, 676), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'model': '"""gpt-3.5-turbo"""'}), "(model='gpt-3.5-turbo')\n", (653, 676), False, 'from llama_index.llms import OpenAI\n'), ((1562, 1586), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1584, 1586), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core.evaluation import PairwiseComparisonEvaluator from llama_index.llms import OpenAI, Gemini from llama_index.core import ServiceContext import pandas as pd async def main(): # DOWNLOAD LLAMADATASET pairwise_evaluator_dataset, _ = download_llama_dataset( "MtBenchHumanJudgementDataset", "./mt_bench_data" ) # DEFINE EVALUATORS gpt_4_context = ServiceContext.from_defaults( llm=OpenAI(temperature=0, model="gpt-4"), ) gpt_3p5_context = ServiceContext.from_defaults( llm=OpenAI(temperature=0, model="gpt-3.5-turbo"), ) gemini_pro_context = ServiceContext.from_defaults( llm=Gemini(model="models/gemini-pro", temperature=0) ) evaluators = { "gpt-4": PairwiseComparisonEvaluator(service_context=gpt_4_context), "gpt-3.5": PairwiseComparisonEvaluator(service_context=gpt_3p5_context), "gemini-pro": PairwiseComparisonEvaluator(service_context=gemini_pro_context), } # EVALUATE WITH PACK ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ EvaluatorBenchmarkerPack = download_llama_pack("EvaluatorBenchmarkerPack", "./pack") evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gpt-3.5"], eval_dataset=pairwise_evaluator_dataset, show_progress=True, ) gpt_3p5_benchmark_df = await evaluator_benchmarker.arun( batch_size=100, sleep_time_in_seconds=0 ) evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gpt-4"], eval_dataset=pairwise_evaluator_dataset, show_progress=True, ) gpt_4_benchmark_df = await evaluator_benchmarker.arun( batch_size=100, sleep_time_in_seconds=0 ) evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gemini-pro"], eval_dataset=pairwise_evaluator_dataset, show_progress=True, ) gemini_pro_benchmark_df = await evaluator_benchmarker.arun( batch_size=5, sleep_time_in_seconds=0.5 ) benchmark_df = pd.concat( [ gpt_3p5_benchmark_df, gpt_4_benchmark_df, gemini_pro_benchmark_df, ], axis=0, ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.llama_pack.download_llama_pack", "llama_index.core.evaluation.PairwiseComparisonEvaluator", "llama_index.llms.Gemini", "llama_index.llms.OpenAI", "llama_index.core.llama_dataset.download_llama_dataset" ]
[((402, 475), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MtBenchHumanJudgementDataset"""', '"""./mt_bench_data"""'], {}), "('MtBenchHumanJudgementDataset', './mt_bench_data')\n", (424, 475), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((1675, 1732), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""EvaluatorBenchmarkerPack"""', '"""./pack"""'], {}), "('EvaluatorBenchmarkerPack', './pack')\n", (1694, 1732), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((2636, 2726), 'pandas.concat', 'pd.concat', (['[gpt_3p5_benchmark_df, gpt_4_benchmark_df, gemini_pro_benchmark_df]'], {'axis': '(0)'}), '([gpt_3p5_benchmark_df, gpt_4_benchmark_df,\n gemini_pro_benchmark_df], axis=0)\n', (2645, 2726), True, 'import pandas as pd\n'), ((2857, 2881), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2879, 2881), False, 'import asyncio\n'), ((898, 956), 'llama_index.core.evaluation.PairwiseComparisonEvaluator', 'PairwiseComparisonEvaluator', ([], {'service_context': 'gpt_4_context'}), '(service_context=gpt_4_context)\n', (925, 956), False, 'from llama_index.core.evaluation import PairwiseComparisonEvaluator\n'), ((977, 1037), 'llama_index.core.evaluation.PairwiseComparisonEvaluator', 'PairwiseComparisonEvaluator', ([], {'service_context': 'gpt_3p5_context'}), '(service_context=gpt_3p5_context)\n', (1004, 1037), False, 'from llama_index.core.evaluation import PairwiseComparisonEvaluator\n'), ((1061, 1124), 'llama_index.core.evaluation.PairwiseComparisonEvaluator', 'PairwiseComparisonEvaluator', ([], {'service_context': 'gemini_pro_context'}), '(service_context=gemini_pro_context)\n', (1088, 1124), False, 'from llama_index.core.evaluation import PairwiseComparisonEvaluator\n'), ((577, 613), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-4"""'}), "(temperature=0, model='gpt-4')\n", (583, 613), False, 'from llama_index.llms import OpenAI, Gemini\n'), ((686, 730), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-3.5-turbo"""'}), "(temperature=0, model='gpt-3.5-turbo')\n", (692, 730), False, 'from llama_index.llms import OpenAI, Gemini\n'), ((806, 854), 'llama_index.llms.Gemini', 'Gemini', ([], {'model': '"""models/gemini-pro"""', 'temperature': '(0)'}), "(model='models/gemini-pro', temperature=0)\n", (812, 854), False, 'from llama_index.llms import OpenAI, Gemini\n')]
from abc import abstractmethod from typing import ( Any, Sequence, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.core.base.query_pipeline.query import ( ChainableMixin, ) from llama_index.core.bridge.pydantic import Field, validator from llama_index.core.callbacks import CallbackManager from llama_index.core.schema import BaseComponent class BaseLLM(ChainableMixin, BaseComponent): """LLM interface.""" callback_manager: CallbackManager = Field( default_factory=CallbackManager, exclude=True ) class Config: arbitrary_types_allowed = True @validator("callback_manager", pre=True) def _validate_callback_manager(cls, v: CallbackManager) -> CallbackManager: if v is None: return CallbackManager([]) return v @property @abstractmethod def metadata(self) -> LLMMetadata: """LLM metadata.""" @abstractmethod def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: """Chat endpoint for LLM.""" @abstractmethod def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint for LLM.""" @abstractmethod def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: """Streaming chat endpoint for LLM.""" @abstractmethod def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Streaming completion endpoint for LLM.""" # ===== Async Endpoints ===== @abstractmethod async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: """Async chat endpoint for LLM.""" @abstractmethod async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Async completion endpoint for LLM.""" @abstractmethod async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: """Async streaming chat endpoint for LLM.""" @abstractmethod async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: """Async streaming completion endpoint for LLM."""
[ "llama_index.core.bridge.pydantic.Field", "llama_index.core.callbacks.CallbackManager", "llama_index.core.bridge.pydantic.validator" ]
[((669, 721), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'CallbackManager', 'exclude': '(True)'}), '(default_factory=CallbackManager, exclude=True)\n', (674, 721), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((800, 839), 'llama_index.core.bridge.pydantic.validator', 'validator', (['"""callback_manager"""'], {'pre': '(True)'}), "('callback_manager', pre=True)\n", (809, 839), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((961, 980), 'llama_index.core.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (976, 980), False, 'from llama_index.core.callbacks import CallbackManager\n')]
from abc import abstractmethod from typing import ( Any, Sequence, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.core.base.query_pipeline.query import ( ChainableMixin, ) from llama_index.core.bridge.pydantic import Field, validator from llama_index.core.callbacks import CallbackManager from llama_index.core.schema import BaseComponent class BaseLLM(ChainableMixin, BaseComponent): """LLM interface.""" callback_manager: CallbackManager = Field( default_factory=CallbackManager, exclude=True ) class Config: arbitrary_types_allowed = True @validator("callback_manager", pre=True) def _validate_callback_manager(cls, v: CallbackManager) -> CallbackManager: if v is None: return CallbackManager([]) return v @property @abstractmethod def metadata(self) -> LLMMetadata: """LLM metadata.""" @abstractmethod def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: """Chat endpoint for LLM.""" @abstractmethod def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint for LLM.""" @abstractmethod def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: """Streaming chat endpoint for LLM.""" @abstractmethod def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Streaming completion endpoint for LLM.""" # ===== Async Endpoints ===== @abstractmethod async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: """Async chat endpoint for LLM.""" @abstractmethod async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Async completion endpoint for LLM.""" @abstractmethod async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: """Async streaming chat endpoint for LLM.""" @abstractmethod async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: """Async streaming completion endpoint for LLM."""
[ "llama_index.core.bridge.pydantic.Field", "llama_index.core.callbacks.CallbackManager", "llama_index.core.bridge.pydantic.validator" ]
[((669, 721), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'CallbackManager', 'exclude': '(True)'}), '(default_factory=CallbackManager, exclude=True)\n', (674, 721), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((800, 839), 'llama_index.core.bridge.pydantic.validator', 'validator', (['"""callback_manager"""'], {'pre': '(True)'}), "('callback_manager', pre=True)\n", (809, 839), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((961, 980), 'llama_index.core.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (976, 980), False, 'from llama_index.core.callbacks import CallbackManager\n')]
from abc import abstractmethod from typing import ( Any, Sequence, ) from llama_index.core.base.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.core.base.query_pipeline.query import ( ChainableMixin, ) from llama_index.core.bridge.pydantic import Field, validator from llama_index.core.callbacks import CallbackManager from llama_index.core.schema import BaseComponent class BaseLLM(ChainableMixin, BaseComponent): """LLM interface.""" callback_manager: CallbackManager = Field( default_factory=CallbackManager, exclude=True ) class Config: arbitrary_types_allowed = True @validator("callback_manager", pre=True) def _validate_callback_manager(cls, v: CallbackManager) -> CallbackManager: if v is None: return CallbackManager([]) return v @property @abstractmethod def metadata(self) -> LLMMetadata: """LLM metadata.""" @abstractmethod def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: """Chat endpoint for LLM.""" @abstractmethod def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint for LLM.""" @abstractmethod def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: """Streaming chat endpoint for LLM.""" @abstractmethod def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Streaming completion endpoint for LLM.""" # ===== Async Endpoints ===== @abstractmethod async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: """Async chat endpoint for LLM.""" @abstractmethod async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Async completion endpoint for LLM.""" @abstractmethod async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: """Async streaming chat endpoint for LLM.""" @abstractmethod async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: """Async streaming completion endpoint for LLM."""
[ "llama_index.core.bridge.pydantic.Field", "llama_index.core.callbacks.CallbackManager", "llama_index.core.bridge.pydantic.validator" ]
[((669, 721), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'CallbackManager', 'exclude': '(True)'}), '(default_factory=CallbackManager, exclude=True)\n', (674, 721), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((800, 839), 'llama_index.core.bridge.pydantic.validator', 'validator', (['"""callback_manager"""'], {'pre': '(True)'}), "('callback_manager', pre=True)\n", (809, 839), False, 'from llama_index.core.bridge.pydantic import Field, validator\n'), ((961, 980), 'llama_index.core.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (976, 980), False, 'from llama_index.core.callbacks import CallbackManager\n')]
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, QueryComponent, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.mixin import PromptMixin, PromptMixinType from llama_index.core.schema import QueryBundle, QueryType from llama_index.core.tools.types import ToolMetadata MetadataType = Union[str, ToolMetadata] class SingleSelection(BaseModel): """A single selection of a choice.""" index: int reason: str class MultiSelection(BaseModel): """A multi-selection of choices.""" selections: List[SingleSelection] @property def ind(self) -> int: if len(self.selections) != 1: raise ValueError( f"There are {len(self.selections)} selections, " "please use .inds." ) return self.selections[0].index @property def reason(self) -> str: if len(self.reasons) != 1: raise ValueError( f"There are {len(self.reasons)} selections, " "please use .reasons." ) return self.selections[0].reason @property def inds(self) -> List[int]: return [x.index for x in self.selections] @property def reasons(self) -> List[str]: return [x.reason for x in self.selections] # separate name for clarity and to not confuse function calling model SelectorResult = MultiSelection def _wrap_choice(choice: MetadataType) -> ToolMetadata: if isinstance(choice, ToolMetadata): return choice elif isinstance(choice, str): return ToolMetadata(description=choice) else: raise ValueError(f"Unexpected type: {type(choice)}") def _wrap_query(query: QueryType) -> QueryBundle: if isinstance(query, QueryBundle): return query elif isinstance(query, str): return QueryBundle(query_str=query) else: raise ValueError(f"Unexpected type: {type(query)}") class BaseSelector(PromptMixin, ChainableMixin): """Base selector.""" def _get_prompt_modules(self) -> PromptMixinType: """Get prompt sub-modules.""" return {} def select( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return self._select(choices=metadatas, query=query_bundle) async def aselect( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return await self._aselect(choices=metadatas, query=query_bundle) @abstractmethod def _select( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass @abstractmethod async def _aselect( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" from llama_index.core.query_pipeline.components.router import ( SelectorComponent, ) return SelectorComponent(selector=self)
[ "llama_index.core.query_pipeline.components.router.SelectorComponent", "llama_index.core.tools.types.ToolMetadata", "llama_index.core.schema.QueryBundle" ]
[((3300, 3332), 'llama_index.core.query_pipeline.components.router.SelectorComponent', 'SelectorComponent', ([], {'selector': 'self'}), '(selector=self)\n', (3317, 3332), False, 'from llama_index.core.query_pipeline.components.router import SelectorComponent\n'), ((1653, 1685), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'description': 'choice'}), '(description=choice)\n', (1665, 1685), False, 'from llama_index.core.tools.types import ToolMetadata\n'), ((1917, 1945), 'llama_index.core.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'query'}), '(query_str=query)\n', (1928, 1945), False, 'from llama_index.core.schema import QueryBundle, QueryType\n')]
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, QueryComponent, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.mixin import PromptMixin, PromptMixinType from llama_index.core.schema import QueryBundle, QueryType from llama_index.core.tools.types import ToolMetadata MetadataType = Union[str, ToolMetadata] class SingleSelection(BaseModel): """A single selection of a choice.""" index: int reason: str class MultiSelection(BaseModel): """A multi-selection of choices.""" selections: List[SingleSelection] @property def ind(self) -> int: if len(self.selections) != 1: raise ValueError( f"There are {len(self.selections)} selections, " "please use .inds." ) return self.selections[0].index @property def reason(self) -> str: if len(self.reasons) != 1: raise ValueError( f"There are {len(self.reasons)} selections, " "please use .reasons." ) return self.selections[0].reason @property def inds(self) -> List[int]: return [x.index for x in self.selections] @property def reasons(self) -> List[str]: return [x.reason for x in self.selections] # separate name for clarity and to not confuse function calling model SelectorResult = MultiSelection def _wrap_choice(choice: MetadataType) -> ToolMetadata: if isinstance(choice, ToolMetadata): return choice elif isinstance(choice, str): return ToolMetadata(description=choice) else: raise ValueError(f"Unexpected type: {type(choice)}") def _wrap_query(query: QueryType) -> QueryBundle: if isinstance(query, QueryBundle): return query elif isinstance(query, str): return QueryBundle(query_str=query) else: raise ValueError(f"Unexpected type: {type(query)}") class BaseSelector(PromptMixin, ChainableMixin): """Base selector.""" def _get_prompt_modules(self) -> PromptMixinType: """Get prompt sub-modules.""" return {} def select( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return self._select(choices=metadatas, query=query_bundle) async def aselect( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return await self._aselect(choices=metadatas, query=query_bundle) @abstractmethod def _select( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass @abstractmethod async def _aselect( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" from llama_index.core.query_pipeline.components.router import ( SelectorComponent, ) return SelectorComponent(selector=self)
[ "llama_index.core.query_pipeline.components.router.SelectorComponent", "llama_index.core.tools.types.ToolMetadata", "llama_index.core.schema.QueryBundle" ]
[((3300, 3332), 'llama_index.core.query_pipeline.components.router.SelectorComponent', 'SelectorComponent', ([], {'selector': 'self'}), '(selector=self)\n', (3317, 3332), False, 'from llama_index.core.query_pipeline.components.router import SelectorComponent\n'), ((1653, 1685), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'description': 'choice'}), '(description=choice)\n', (1665, 1685), False, 'from llama_index.core.tools.types import ToolMetadata\n'), ((1917, 1945), 'llama_index.core.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'query'}), '(query_str=query)\n', (1928, 1945), False, 'from llama_index.core.schema import QueryBundle, QueryType\n')]
from abc import abstractmethod from typing import Any, List, Sequence, Union from llama_index.core.base.query_pipeline.query import ( ChainableMixin, QueryComponent, ) from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.prompts.mixin import PromptMixin, PromptMixinType from llama_index.core.schema import QueryBundle, QueryType from llama_index.core.tools.types import ToolMetadata MetadataType = Union[str, ToolMetadata] class SingleSelection(BaseModel): """A single selection of a choice.""" index: int reason: str class MultiSelection(BaseModel): """A multi-selection of choices.""" selections: List[SingleSelection] @property def ind(self) -> int: if len(self.selections) != 1: raise ValueError( f"There are {len(self.selections)} selections, " "please use .inds." ) return self.selections[0].index @property def reason(self) -> str: if len(self.reasons) != 1: raise ValueError( f"There are {len(self.reasons)} selections, " "please use .reasons." ) return self.selections[0].reason @property def inds(self) -> List[int]: return [x.index for x in self.selections] @property def reasons(self) -> List[str]: return [x.reason for x in self.selections] # separate name for clarity and to not confuse function calling model SelectorResult = MultiSelection def _wrap_choice(choice: MetadataType) -> ToolMetadata: if isinstance(choice, ToolMetadata): return choice elif isinstance(choice, str): return ToolMetadata(description=choice) else: raise ValueError(f"Unexpected type: {type(choice)}") def _wrap_query(query: QueryType) -> QueryBundle: if isinstance(query, QueryBundle): return query elif isinstance(query, str): return QueryBundle(query_str=query) else: raise ValueError(f"Unexpected type: {type(query)}") class BaseSelector(PromptMixin, ChainableMixin): """Base selector.""" def _get_prompt_modules(self) -> PromptMixinType: """Get prompt sub-modules.""" return {} def select( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return self._select(choices=metadatas, query=query_bundle) async def aselect( self, choices: Sequence[MetadataType], query: QueryType ) -> SelectorResult: metadatas = [_wrap_choice(choice) for choice in choices] query_bundle = _wrap_query(query) return await self._aselect(choices=metadatas, query=query_bundle) @abstractmethod def _select( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass @abstractmethod async def _aselect( self, choices: Sequence[ToolMetadata], query: QueryBundle ) -> SelectorResult: pass def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" from llama_index.core.query_pipeline.components.router import ( SelectorComponent, ) return SelectorComponent(selector=self)
[ "llama_index.core.query_pipeline.components.router.SelectorComponent", "llama_index.core.tools.types.ToolMetadata", "llama_index.core.schema.QueryBundle" ]
[((3300, 3332), 'llama_index.core.query_pipeline.components.router.SelectorComponent', 'SelectorComponent', ([], {'selector': 'self'}), '(selector=self)\n', (3317, 3332), False, 'from llama_index.core.query_pipeline.components.router import SelectorComponent\n'), ((1653, 1685), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'description': 'choice'}), '(description=choice)\n', (1665, 1685), False, 'from llama_index.core.tools.types import ToolMetadata\n'), ((1917, 1945), 'llama_index.core.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'query'}), '(query_str=query)\n', (1928, 1945), False, 'from llama_index.core.schema import QueryBundle, QueryType\n')]
"""Base agent type.""" import uuid from abc import abstractmethod from typing import Any, Dict, List, Optional from llama_index.legacy.bridge.pydantic import BaseModel, Field from llama_index.legacy.callbacks import CallbackManager, trace_method from llama_index.legacy.chat_engine.types import ( BaseChatEngine, StreamingAgentChatResponse, ) from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.llms.types import ChatMessage from llama_index.legacy.core.response.schema import RESPONSE_TYPE, Response from llama_index.legacy.memory.types import BaseMemory from llama_index.legacy.prompts.mixin import ( PromptDictType, PromptMixin, PromptMixinType, ) from llama_index.legacy.schema import QueryBundle class BaseAgent(BaseChatEngine, BaseQueryEngine): """Base Agent.""" def _get_prompts(self) -> PromptDictType: """Get prompts.""" # TODO: the ReAct agent does not explicitly specify prompts, would need a # refactor to expose those prompts return {} def _get_prompt_modules(self) -> PromptMixinType: """Get prompt modules.""" return {} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" # ===== Query Engine Interface ===== @trace_method("query") def _query(self, query_bundle: QueryBundle) -> RESPONSE_TYPE: agent_response = self.chat( query_bundle.query_str, chat_history=[], ) return Response( response=str(agent_response), source_nodes=agent_response.source_nodes ) @trace_method("query") async def _aquery(self, query_bundle: QueryBundle) -> RESPONSE_TYPE: agent_response = await self.achat( query_bundle.query_str, chat_history=[], ) return Response( response=str(agent_response), source_nodes=agent_response.source_nodes ) def stream_chat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> StreamingAgentChatResponse: raise NotImplementedError("stream_chat not implemented") async def astream_chat( self, message: str, chat_history: Optional[List[ChatMessage]] = None ) -> StreamingAgentChatResponse: raise NotImplementedError("astream_chat not implemented") class TaskStep(BaseModel): """Agent task step. Represents a single input step within the execution run ("Task") of an agent given a user input. The output is returned as a `TaskStepOutput`. """ task_id: str = Field(..., diescription="Task ID") step_id: str = Field(..., description="Step ID") input: Optional[str] = Field(default=None, description="User input") # memory: BaseMemory = Field( # ..., type=BaseMemory, description="Conversational Memory" # ) step_state: Dict[str, Any] = Field( default_factory=dict, description="Additional state for a given step." ) # NOTE: the state below may change throughout the course of execution # this tracks the relationships to other steps next_steps: Dict[str, "TaskStep"] = Field( default_factory=dict, description="Next steps to be executed." ) prev_steps: Dict[str, "TaskStep"] = Field( default_factory=dict, description="Previous steps that were dependencies for this step.", ) is_ready: bool = Field( default=True, description="Is this step ready to be executed?" ) def get_next_step( self, step_id: str, input: Optional[str] = None, step_state: Optional[Dict[str, Any]] = None, ) -> "TaskStep": """Convenience function to get next step. Preserve task_id, memory, step_state. """ return TaskStep( task_id=self.task_id, step_id=step_id, input=input, # memory=self.memory, step_state=step_state or self.step_state, ) def link_step( self, next_step: "TaskStep", ) -> None: """Link to next step. Add link from this step to next, and from next step to current. """ self.next_steps[next_step.step_id] = next_step next_step.prev_steps[self.step_id] = self class TaskStepOutput(BaseModel): """Agent task step output.""" output: Any = Field(..., description="Task step output") task_step: TaskStep = Field(..., description="Task step input") next_steps: List[TaskStep] = Field(..., description="Next steps to be executed.") is_last: bool = Field(default=False, description="Is this the last step?") def __str__(self) -> str: """String representation.""" return str(self.output) class Task(BaseModel): """Agent Task. Represents a "run" of an agent given a user input. """ class Config: arbitrary_types_allowed = True task_id: str = Field( default_factory=lambda: str(uuid.uuid4()), type=str, description="Task ID" ) input: str = Field(..., type=str, description="User input") # NOTE: this is state that may be modified throughout the course of execution of the task memory: BaseMemory = Field( ..., type=BaseMemory, description=( "Conversational Memory. Maintains state before execution of this task." ), ) callback_manager: CallbackManager = Field( default_factory=CallbackManager, exclude=True, description="Callback manager for the task.", ) extra_state: Dict[str, Any] = Field( default_factory=dict, description=( "Additional user-specified state for a given task. " "Can be modified throughout the execution of a task." ), ) class BaseAgentWorker(PromptMixin): """Base agent worker.""" class Config: arbitrary_types_allowed = True def _get_prompts(self) -> PromptDictType: """Get prompts.""" # TODO: the ReAct agent does not explicitly specify prompts, would need a # refactor to expose those prompts return {} def _get_prompt_modules(self) -> PromptMixinType: """Get prompt modules.""" return {} def _update_prompts(self, prompts: PromptDictType) -> None: """Update prompts.""" @abstractmethod def initialize_step(self, task: Task, **kwargs: Any) -> TaskStep: """Initialize step from task.""" @abstractmethod def run_step(self, step: TaskStep, task: Task, **kwargs: Any) -> TaskStepOutput: """Run step.""" @abstractmethod async def arun_step( self, step: TaskStep, task: Task, **kwargs: Any ) -> TaskStepOutput: """Run step (async).""" raise NotImplementedError @abstractmethod def stream_step(self, step: TaskStep, task: Task, **kwargs: Any) -> TaskStepOutput: """Run step (stream).""" # TODO: figure out if we need a different type for TaskStepOutput raise NotImplementedError @abstractmethod async def astream_step( self, step: TaskStep, task: Task, **kwargs: Any ) -> TaskStepOutput: """Run step (async stream).""" raise NotImplementedError @abstractmethod def finalize_task(self, task: Task, **kwargs: Any) -> None: """Finalize task, after all the steps are completed.""" def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" # TODO: make this abstractmethod (right now will break some agent impls)
[ "llama_index.legacy.callbacks.trace_method", "llama_index.legacy.bridge.pydantic.Field" ]
[((1310, 1331), 'llama_index.legacy.callbacks.trace_method', 'trace_method', (['"""query"""'], {}), "('query')\n", (1322, 1331), False, 'from llama_index.legacy.callbacks import CallbackManager, trace_method\n'), ((1633, 1654), 'llama_index.legacy.callbacks.trace_method', 'trace_method', (['"""query"""'], {}), "('query')\n", (1645, 1654), False, 'from llama_index.legacy.callbacks import CallbackManager, trace_method\n'), ((2613, 2647), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'diescription': '"""Task ID"""'}), "(..., diescription='Task ID')\n", (2618, 2647), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((2667, 2700), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Step ID"""'}), "(..., description='Step ID')\n", (2672, 2700), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((2728, 2773), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""User input"""'}), "(default=None, description='User input')\n", (2733, 2773), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((2917, 2994), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional state for a given step."""'}), "(default_factory=dict, description='Additional state for a given step.')\n", (2922, 2994), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((3175, 3244), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Next steps to be executed."""'}), "(default_factory=dict, description='Next steps to be executed.')\n", (3180, 3244), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((3299, 3399), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Previous steps that were dependencies for this step."""'}), "(default_factory=dict, description=\n 'Previous steps that were dependencies for this step.')\n", (3304, 3399), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((3439, 3508), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(True)', 'description': '"""Is this step ready to be executed?"""'}), "(default=True, description='Is this step ready to be executed?')\n", (3444, 3508), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((4404, 4446), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Task step output"""'}), "(..., description='Task step output')\n", (4409, 4446), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((4473, 4514), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Task step input"""'}), "(..., description='Task step input')\n", (4478, 4514), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((4548, 4600), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Next steps to be executed."""'}), "(..., description='Next steps to be executed.')\n", (4553, 4600), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((4621, 4679), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Is this the last step?"""'}), "(default=False, description='Is this the last step?')\n", (4626, 4679), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((5080, 5126), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'type': 'str', 'description': '"""User input"""'}), "(..., type=str, description='User input')\n", (5085, 5126), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((5247, 5364), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'type': 'BaseMemory', 'description': '"""Conversational Memory. Maintains state before execution of this task."""'}), "(..., type=BaseMemory, description=\n 'Conversational Memory. Maintains state before execution of this task.')\n", (5252, 5364), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((5456, 5559), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'CallbackManager', 'exclude': '(True)', 'description': '"""Callback manager for the task."""'}), "(default_factory=CallbackManager, exclude=True, description=\n 'Callback manager for the task.')\n", (5461, 5559), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((5621, 5775), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional user-specified state for a given task. Can be modified throughout the execution of a task."""'}), "(default_factory=dict, description=\n 'Additional user-specified state for a given task. Can be modified throughout the execution of a task.'\n )\n", (5626, 5775), False, 'from llama_index.legacy.bridge.pydantic import BaseModel, Field\n'), ((5010, 5022), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (5020, 5022), False, 'import uuid\n')]
import json from typing import Any, Dict, Sequence, Tuple import httpx from httpx import Timeout from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.constants import DEFAULT_CONTEXT_WINDOW, DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM DEFAULT_REQUEST_TIMEOUT = 30.0 def get_addtional_kwargs( response: Dict[str, Any], exclude: Tuple[str, ...] ) -> Dict[str, Any]: return {k: v for k, v in response.items() if k not in exclude} class Ollama(CustomLLM): base_url: str = Field( default="http://localhost:11434", description="Base url the model is hosted under.", ) model: str = Field(description="The Ollama model to use.") temperature: float = Field( default=0.75, description="The temperature to use for sampling.", gte=0.0, lte=1.0, ) context_window: int = Field( default=DEFAULT_CONTEXT_WINDOW, description="The maximum number of context tokens for the model.", gt=0, ) request_timeout: float = Field( default=DEFAULT_REQUEST_TIMEOUT, description="The timeout for making http request to Ollama API server", ) prompt_key: str = Field( default="prompt", description="The key to use for the prompt in API calls." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional model parameters for the Ollama API.", ) @classmethod def class_name(cls) -> str: return "Ollama_llm" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( context_window=self.context_window, num_output=DEFAULT_NUM_OUTPUTS, model_name=self.model, is_chat_model=True, # Ollama supports chat API for all models ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, "num_ctx": self.context_window, } return { **base_kwargs, **self.additional_kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: payload = { "model": self.model, "messages": [ { "role": message.role.value, "content": message.content, **message.additional_kwargs, } for message in messages ], "options": self._model_kwargs, "stream": False, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: response = client.post( url=f"{self.base_url}/api/chat", json=payload, ) response.raise_for_status() raw = response.json() message = raw["message"] return ChatResponse( message=ChatMessage( content=message.get("content"), role=MessageRole(message.get("role")), additional_kwargs=get_addtional_kwargs( message, ("content", "role") ), ), raw=raw, additional_kwargs=get_addtional_kwargs(raw, ("message",)), ) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: payload = { "model": self.model, "messages": [ { "role": message.role.value, "content": message.content, **message.additional_kwargs, } for message in messages ], "options": self._model_kwargs, "stream": True, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: with client.stream( method="POST", url=f"{self.base_url}/api/chat", json=payload, ) as response: response.raise_for_status() text = "" for line in response.iter_lines(): if line: chunk = json.loads(line) if "done" in chunk and chunk["done"]: break message = chunk["message"] delta = message.get("content") text += delta yield ChatResponse( message=ChatMessage( content=text, role=MessageRole(message.get("role")), additional_kwargs=get_addtional_kwargs( message, ("content", "role") ), ), delta=delta, raw=chunk, additional_kwargs=get_addtional_kwargs(chunk, ("message",)), ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: payload = { self.prompt_key: prompt, "model": self.model, "options": self._model_kwargs, "stream": False, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: response = client.post( url=f"{self.base_url}/api/generate", json=payload, ) response.raise_for_status() raw = response.json() text = raw.get("response") return CompletionResponse( text=text, raw=raw, additional_kwargs=get_addtional_kwargs(raw, ("response",)), ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: payload = { self.prompt_key: prompt, "model": self.model, "options": self._model_kwargs, "stream": True, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: with client.stream( method="POST", url=f"{self.base_url}/api/generate", json=payload, ) as response: response.raise_for_status() text = "" for line in response.iter_lines(): if line: chunk = json.loads(line) delta = chunk.get("response") text += delta yield CompletionResponse( delta=delta, text=text, raw=chunk, additional_kwargs=get_addtional_kwargs( chunk, ("response",) ), )
[ "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field" ]
[((816, 911), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""http://localhost:11434"""', 'description': '"""Base url the model is hosted under."""'}), "(default='http://localhost:11434', description=\n 'Base url the model is hosted under.')\n", (821, 911), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((947, 992), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Ollama model to use."""'}), "(description='The Ollama model to use.')\n", (952, 992), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1018, 1112), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.75)', 'description': '"""The temperature to use for sampling."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=0.75, description='The temperature to use for sampling.', gte\n =0.0, lte=1.0)\n", (1023, 1112), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1173, 1288), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_CONTEXT_WINDOW', 'description': '"""The maximum number of context tokens for the model."""', 'gt': '(0)'}), "(default=DEFAULT_CONTEXT_WINDOW, description=\n 'The maximum number of context tokens for the model.', gt=0)\n", (1178, 1288), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1344, 1459), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_REQUEST_TIMEOUT', 'description': '"""The timeout for making http request to Ollama API server"""'}), "(default=DEFAULT_REQUEST_TIMEOUT, description=\n 'The timeout for making http request to Ollama API server')\n", (1349, 1459), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1500, 1587), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""prompt"""', 'description': '"""The key to use for the prompt in API calls."""'}), "(default='prompt', description=\n 'The key to use for the prompt in API calls.')\n", (1505, 1587), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1637, 1732), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional model parameters for the Ollama API."""'}), "(default_factory=dict, description=\n 'Additional model parameters for the Ollama API.')\n", (1642, 1732), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2434, 2453), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (2451, 2453), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3730, 3749), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (3747, 3749), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5575, 5600), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5598, 5600), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6418, 6443), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6441, 6443), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((1926, 2053), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_window', 'num_output': 'DEFAULT_NUM_OUTPUTS', 'model_name': 'self.model', 'is_chat_model': '(True)'}), '(context_window=self.context_window, num_output=\n DEFAULT_NUM_OUTPUTS, model_name=self.model, is_chat_model=True)\n', (1937, 2053), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((2992, 3021), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (2999, 3021), False, 'from httpx import Timeout\n'), ((4311, 4340), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (4318, 4340), False, 'from httpx import Timeout\n'), ((5943, 5972), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (5950, 5972), False, 'from httpx import Timeout\n'), ((6795, 6824), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (6802, 6824), False, 'from httpx import Timeout\n'), ((4704, 4720), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (4714, 4720), False, 'import json\n'), ((7192, 7208), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (7202, 7208), False, 'import json\n')]
import json from typing import Any, Dict, Sequence, Tuple import httpx from httpx import Timeout from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.constants import DEFAULT_CONTEXT_WINDOW, DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM DEFAULT_REQUEST_TIMEOUT = 30.0 def get_addtional_kwargs( response: Dict[str, Any], exclude: Tuple[str, ...] ) -> Dict[str, Any]: return {k: v for k, v in response.items() if k not in exclude} class Ollama(CustomLLM): base_url: str = Field( default="http://localhost:11434", description="Base url the model is hosted under.", ) model: str = Field(description="The Ollama model to use.") temperature: float = Field( default=0.75, description="The temperature to use for sampling.", gte=0.0, lte=1.0, ) context_window: int = Field( default=DEFAULT_CONTEXT_WINDOW, description="The maximum number of context tokens for the model.", gt=0, ) request_timeout: float = Field( default=DEFAULT_REQUEST_TIMEOUT, description="The timeout for making http request to Ollama API server", ) prompt_key: str = Field( default="prompt", description="The key to use for the prompt in API calls." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional model parameters for the Ollama API.", ) @classmethod def class_name(cls) -> str: return "Ollama_llm" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( context_window=self.context_window, num_output=DEFAULT_NUM_OUTPUTS, model_name=self.model, is_chat_model=True, # Ollama supports chat API for all models ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, "num_ctx": self.context_window, } return { **base_kwargs, **self.additional_kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: payload = { "model": self.model, "messages": [ { "role": message.role.value, "content": message.content, **message.additional_kwargs, } for message in messages ], "options": self._model_kwargs, "stream": False, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: response = client.post( url=f"{self.base_url}/api/chat", json=payload, ) response.raise_for_status() raw = response.json() message = raw["message"] return ChatResponse( message=ChatMessage( content=message.get("content"), role=MessageRole(message.get("role")), additional_kwargs=get_addtional_kwargs( message, ("content", "role") ), ), raw=raw, additional_kwargs=get_addtional_kwargs(raw, ("message",)), ) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: payload = { "model": self.model, "messages": [ { "role": message.role.value, "content": message.content, **message.additional_kwargs, } for message in messages ], "options": self._model_kwargs, "stream": True, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: with client.stream( method="POST", url=f"{self.base_url}/api/chat", json=payload, ) as response: response.raise_for_status() text = "" for line in response.iter_lines(): if line: chunk = json.loads(line) if "done" in chunk and chunk["done"]: break message = chunk["message"] delta = message.get("content") text += delta yield ChatResponse( message=ChatMessage( content=text, role=MessageRole(message.get("role")), additional_kwargs=get_addtional_kwargs( message, ("content", "role") ), ), delta=delta, raw=chunk, additional_kwargs=get_addtional_kwargs(chunk, ("message",)), ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: payload = { self.prompt_key: prompt, "model": self.model, "options": self._model_kwargs, "stream": False, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: response = client.post( url=f"{self.base_url}/api/generate", json=payload, ) response.raise_for_status() raw = response.json() text = raw.get("response") return CompletionResponse( text=text, raw=raw, additional_kwargs=get_addtional_kwargs(raw, ("response",)), ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: payload = { self.prompt_key: prompt, "model": self.model, "options": self._model_kwargs, "stream": True, **kwargs, } with httpx.Client(timeout=Timeout(self.request_timeout)) as client: with client.stream( method="POST", url=f"{self.base_url}/api/generate", json=payload, ) as response: response.raise_for_status() text = "" for line in response.iter_lines(): if line: chunk = json.loads(line) delta = chunk.get("response") text += delta yield CompletionResponse( delta=delta, text=text, raw=chunk, additional_kwargs=get_addtional_kwargs( chunk, ("response",) ), )
[ "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field" ]
[((816, 911), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""http://localhost:11434"""', 'description': '"""Base url the model is hosted under."""'}), "(default='http://localhost:11434', description=\n 'Base url the model is hosted under.')\n", (821, 911), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((947, 992), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Ollama model to use."""'}), "(description='The Ollama model to use.')\n", (952, 992), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1018, 1112), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(0.75)', 'description': '"""The temperature to use for sampling."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=0.75, description='The temperature to use for sampling.', gte\n =0.0, lte=1.0)\n", (1023, 1112), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1173, 1288), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_CONTEXT_WINDOW', 'description': '"""The maximum number of context tokens for the model."""', 'gt': '(0)'}), "(default=DEFAULT_CONTEXT_WINDOW, description=\n 'The maximum number of context tokens for the model.', gt=0)\n", (1178, 1288), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1344, 1459), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_REQUEST_TIMEOUT', 'description': '"""The timeout for making http request to Ollama API server"""'}), "(default=DEFAULT_REQUEST_TIMEOUT, description=\n 'The timeout for making http request to Ollama API server')\n", (1349, 1459), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1500, 1587), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '"""prompt"""', 'description': '"""The key to use for the prompt in API calls."""'}), "(default='prompt', description=\n 'The key to use for the prompt in API calls.')\n", (1505, 1587), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1637, 1732), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional model parameters for the Ollama API."""'}), "(default_factory=dict, description=\n 'Additional model parameters for the Ollama API.')\n", (1642, 1732), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2434, 2453), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (2451, 2453), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3730, 3749), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (3747, 3749), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5575, 5600), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5598, 5600), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6418, 6443), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6441, 6443), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((1926, 2053), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_window', 'num_output': 'DEFAULT_NUM_OUTPUTS', 'model_name': 'self.model', 'is_chat_model': '(True)'}), '(context_window=self.context_window, num_output=\n DEFAULT_NUM_OUTPUTS, model_name=self.model, is_chat_model=True)\n', (1937, 2053), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((2992, 3021), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (2999, 3021), False, 'from httpx import Timeout\n'), ((4311, 4340), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (4318, 4340), False, 'from httpx import Timeout\n'), ((5943, 5972), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (5950, 5972), False, 'from httpx import Timeout\n'), ((6795, 6824), 'httpx.Timeout', 'Timeout', (['self.request_timeout'], {}), '(self.request_timeout)\n', (6802, 6824), False, 'from httpx import Timeout\n'), ((4704, 4720), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (4714, 4720), False, 'import json\n'), ((7192, 7208), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (7202, 7208), False, 'import json\n')]
import warnings from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.cohere_utils import ( CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Cohere(LLM): model: str = Field(description="The cohere model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_retries: int = Field( default=10, description="The maximum number of API retries." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the Cohere API." ) max_tokens: int = Field(description="The maximum number of tokens to generate.") _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() def __init__( self, model: str = "command", temperature: float = 0.5, max_tokens: int = 512, timeout: Optional[float] = None, max_retries: int = 10, api_key: Optional[str] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: import cohere except ImportError as e: raise ImportError( "You must install the `cohere` package to use Cohere." "Please `pip install cohere`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) self._client = cohere.Client(api_key, client_name="llama_index") self._aclient = cohere.AsyncClient(api_key, client_name="llama_index") super().__init__( temperature=temperature, additional_kwargs=additional_kwargs, timeout=timeout, max_retries=max_retries, model=model, callback_manager=callback_manager, max_tokens=max_tokens, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: """Get class name.""" return "Cohere_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=cohere_modelname_to_contextsize(self.model), num_output=self.max_tokens, is_chat_model=True, model_name=self.model, system_role=MessageRole.CHATBOT, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) return ChatResponse( message=ChatMessage(role=MessageRole.ASSISTANT, content=response.text), raw=response.__dict__, ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) return CompletionResponse( text=response.generations[0].text, raw=response.__dict__, ) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) def gen() -> ChatResponseGen: content = "" role = MessageRole.ASSISTANT for r in response: if "text" in r.__dict__: content_delta = r.text else: content_delta = "" content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=r.__dict__, ) return gen() @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) def gen() -> CompletionResponseGen: content = "" for r in response: content_delta = r.text content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=r._asdict() ) return gen() @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) return ChatResponse( message=ChatMessage(role=MessageRole.ASSISTANT, content=response.text), raw=response.__dict__, ) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) return CompletionResponse( text=response.generations[0].text, raw=response.__dict__, ) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) async def gen() -> ChatResponseAsyncGen: content = "" role = MessageRole.ASSISTANT async for r in response: if "text" in r.__dict__: content_delta = r.text else: content_delta = "" content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=r.__dict__, ) return gen() @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) async def gen() -> CompletionResponseAsyncGen: content = "" async for r in response: content_delta = r.text content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=r._asdict() ) return gen()
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.cohere_utils.cohere_modelname_to_contextsize", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.cohere_utils.messages_to_cohere_history", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.cohere_utils.acompletion_with_retry", "llama_index.legacy.llms.cohere_utils.completion_with_retry" ]
[((897, 942), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The cohere model to use."""'}), "(description='The cohere model to use.')\n", (902, 942), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((968, 1025), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (973, 1025), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1049, 1116), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""'}), "(default=10, description='The maximum number of API retries.')\n", (1054, 1116), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1171, 1256), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the Cohere API."""'}), "(default_factory=dict, description='Additional kwargs for the Cohere API.'\n )\n", (1176, 1256), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1288, 1350), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1293, 1350), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1371, 1384), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1382, 1384), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1405, 1418), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1416, 1418), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((4032, 4051), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4049, 4051), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5025, 5050), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5048, 5050), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5762, 5781), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5779, 5781), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6993, 7018), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7016, 7018), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7775, 7794), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (7792, 7794), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8799, 8824), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8822, 8824), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9552, 9571), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9569, 9571), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((10821, 10846), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (10844, 10846), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2518, 2567), 'cohere.Client', 'cohere.Client', (['api_key'], {'client_name': '"""llama_index"""'}), "(api_key, client_name='llama_index')\n", (2531, 2567), False, 'import cohere\n'), ((2592, 2646), 'cohere.AsyncClient', 'cohere.AsyncClient', (['api_key'], {'client_name': '"""llama_index"""'}), "(api_key, client_name='llama_index')\n", (2610, 2646), False, 'import cohere\n'), ((4154, 4195), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (4180, 4195), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((4642, 4781), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(client=self._client, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (4663, 4781), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((5443, 5560), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(client=self._client, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (5464, 5560), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((5644, 5720), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response.generations[0].text', 'raw': 'response.__dict__'}), '(text=response.generations[0].text, raw=response.__dict__)\n', (5662, 5720), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((5908, 5949), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (5934, 5949), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((6224, 6363), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(client=self._client, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (6245, 6363), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((7250, 7367), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(client=self._client, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (7271, 7367), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((7918, 7959), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (7944, 7959), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((9434, 9510), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response.generations[0].text', 'raw': 'response.__dict__'}), '(text=response.generations[0].text, raw=response.__dict__)\n', (9452, 9510), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((9710, 9751), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (9736, 9751), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((2474, 2493), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (2489, 2493), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((4463, 4583), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (4476, 4583), False, 'import warnings\n'), ((5263, 5383), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (5276, 5383), False, 'import warnings\n'), ((8226, 8346), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (8239, 8346), False, 'import warnings\n'), ((8412, 8554), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (8434, 8554), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((9044, 9164), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (9057, 9164), False, 'import warnings\n'), ((9230, 9350), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (9252, 9350), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((10032, 10174), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (10054, 10174), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((11096, 11216), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (11118, 11216), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((3405, 3448), 'llama_index.legacy.llms.cohere_utils.cohere_modelname_to_contextsize', 'cohere_modelname_to_contextsize', (['self.model'], {}), '(self.model)\n', (3436, 3448), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((4910, 4972), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.text'}), '(role=MessageRole.ASSISTANT, content=response.text)\n', (4921, 4972), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((8684, 8746), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.text'}), '(role=MessageRole.ASSISTANT, content=response.text)\n', (8695, 8746), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((6829, 6868), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (6840, 6868), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((10657, 10696), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (10668, 10696), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n')]
import warnings from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.cohere_utils import ( CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Cohere(LLM): model: str = Field(description="The cohere model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_retries: int = Field( default=10, description="The maximum number of API retries." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the Cohere API." ) max_tokens: int = Field(description="The maximum number of tokens to generate.") _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() def __init__( self, model: str = "command", temperature: float = 0.5, max_tokens: int = 512, timeout: Optional[float] = None, max_retries: int = 10, api_key: Optional[str] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: import cohere except ImportError as e: raise ImportError( "You must install the `cohere` package to use Cohere." "Please `pip install cohere`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) self._client = cohere.Client(api_key, client_name="llama_index") self._aclient = cohere.AsyncClient(api_key, client_name="llama_index") super().__init__( temperature=temperature, additional_kwargs=additional_kwargs, timeout=timeout, max_retries=max_retries, model=model, callback_manager=callback_manager, max_tokens=max_tokens, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: """Get class name.""" return "Cohere_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=cohere_modelname_to_contextsize(self.model), num_output=self.max_tokens, is_chat_model=True, model_name=self.model, system_role=MessageRole.CHATBOT, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) return ChatResponse( message=ChatMessage(role=MessageRole.ASSISTANT, content=response.text), raw=response.__dict__, ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) return CompletionResponse( text=response.generations[0].text, raw=response.__dict__, ) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) def gen() -> ChatResponseGen: content = "" role = MessageRole.ASSISTANT for r in response: if "text" in r.__dict__: content_delta = r.text else: content_delta = "" content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=r.__dict__, ) return gen() @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True response = completion_with_retry( client=self._client, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) def gen() -> CompletionResponseGen: content = "" for r in response: content_delta = r.text content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=r._asdict() ) return gen() @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) return ChatResponse( message=ChatMessage(role=MessageRole.ASSISTANT, content=response.text), raw=response.__dict__, ) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) if "stream" in all_kwargs: warnings.warn( "Parameter `stream` is not supported by the `chat` method." "Use the `stream_chat` method instead" ) response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) return CompletionResponse( text=response.generations[0].text, raw=response.__dict__, ) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: history = messages_to_cohere_history(messages[:-1]) prompt = messages[-1].content all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True if all_kwargs["model"] not in CHAT_MODELS: raise ValueError(f"{all_kwargs['model']} not supported for chat") response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=True, message=prompt, chat_history=history, **all_kwargs, ) async def gen() -> ChatResponseAsyncGen: content = "" role = MessageRole.ASSISTANT async for r in response: if "text" in r.__dict__: content_delta = r.text else: content_delta = "" content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=r.__dict__, ) return gen() @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: all_kwargs = self._get_all_kwargs(**kwargs) all_kwargs["stream"] = True response = await acompletion_with_retry( aclient=self._aclient, max_retries=self.max_retries, chat=False, prompt=prompt, **all_kwargs, ) async def gen() -> CompletionResponseAsyncGen: content = "" async for r in response: content_delta = r.text content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=r._asdict() ) return gen()
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.cohere_utils.cohere_modelname_to_contextsize", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.cohere_utils.messages_to_cohere_history", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.cohere_utils.acompletion_with_retry", "llama_index.legacy.llms.cohere_utils.completion_with_retry" ]
[((897, 942), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The cohere model to use."""'}), "(description='The cohere model to use.')\n", (902, 942), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((968, 1025), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (973, 1025), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1049, 1116), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""'}), "(default=10, description='The maximum number of API retries.')\n", (1054, 1116), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1171, 1256), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the Cohere API."""'}), "(default_factory=dict, description='Additional kwargs for the Cohere API.'\n )\n", (1176, 1256), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1288, 1350), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1293, 1350), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1371, 1384), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1382, 1384), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1405, 1418), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1416, 1418), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((4032, 4051), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4049, 4051), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5025, 5050), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5048, 5050), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5762, 5781), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5779, 5781), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6993, 7018), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7016, 7018), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7775, 7794), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (7792, 7794), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8799, 8824), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8822, 8824), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9552, 9571), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9569, 9571), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((10821, 10846), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (10844, 10846), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2518, 2567), 'cohere.Client', 'cohere.Client', (['api_key'], {'client_name': '"""llama_index"""'}), "(api_key, client_name='llama_index')\n", (2531, 2567), False, 'import cohere\n'), ((2592, 2646), 'cohere.AsyncClient', 'cohere.AsyncClient', (['api_key'], {'client_name': '"""llama_index"""'}), "(api_key, client_name='llama_index')\n", (2610, 2646), False, 'import cohere\n'), ((4154, 4195), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (4180, 4195), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((4642, 4781), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(client=self._client, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (4663, 4781), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((5443, 5560), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(client=self._client, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (5464, 5560), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((5644, 5720), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response.generations[0].text', 'raw': 'response.__dict__'}), '(text=response.generations[0].text, raw=response.__dict__)\n', (5662, 5720), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((5908, 5949), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (5934, 5949), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((6224, 6363), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(client=self._client, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (6245, 6363), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((7250, 7367), 'llama_index.legacy.llms.cohere_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(client=self._client, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (7271, 7367), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((7918, 7959), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (7944, 7959), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((9434, 9510), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response.generations[0].text', 'raw': 'response.__dict__'}), '(text=response.generations[0].text, raw=response.__dict__)\n', (9452, 9510), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((9710, 9751), 'llama_index.legacy.llms.cohere_utils.messages_to_cohere_history', 'messages_to_cohere_history', (['messages[:-1]'], {}), '(messages[:-1])\n', (9736, 9751), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((2474, 2493), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (2489, 2493), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((4463, 4583), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (4476, 4583), False, 'import warnings\n'), ((5263, 5383), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (5276, 5383), False, 'import warnings\n'), ((8226, 8346), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (8239, 8346), False, 'import warnings\n'), ((8412, 8554), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (8434, 8554), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((9044, 9164), 'warnings.warn', 'warnings.warn', (['"""Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead"""'], {}), "(\n 'Parameter `stream` is not supported by the `chat` method.Use the `stream_chat` method instead'\n )\n", (9057, 9164), False, 'import warnings\n'), ((9230, 9350), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (9252, 9350), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((10032, 10174), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(True)', 'message': 'prompt', 'chat_history': 'history'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=True, message=prompt, chat_history=history, **all_kwargs)\n', (10054, 10174), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((11096, 11216), 'llama_index.legacy.llms.cohere_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'aclient': 'self._aclient', 'max_retries': 'self.max_retries', 'chat': '(False)', 'prompt': 'prompt'}), '(aclient=self._aclient, max_retries=self.max_retries,\n chat=False, prompt=prompt, **all_kwargs)\n', (11118, 11216), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((3405, 3448), 'llama_index.legacy.llms.cohere_utils.cohere_modelname_to_contextsize', 'cohere_modelname_to_contextsize', (['self.model'], {}), '(self.model)\n', (3436, 3448), False, 'from llama_index.legacy.llms.cohere_utils import CHAT_MODELS, acompletion_with_retry, cohere_modelname_to_contextsize, completion_with_retry, messages_to_cohere_history\n'), ((4910, 4972), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.text'}), '(role=MessageRole.ASSISTANT, content=response.text)\n', (4921, 4972), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((8684, 8746), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.text'}), '(role=MessageRole.ASSISTANT, content=response.text)\n', (8695, 8746), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((6829, 6868), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (6840, 6868), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((10657, 10696), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (10668, 10696), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n')]
from abc import abstractmethod from typing import List from llama_index.core.indices.query.schema import QueryBundle, QueryType from llama_index.core.prompts.mixin import PromptMixin from llama_index.core.schema import NodeWithScore class BaseImageRetriever(PromptMixin): """Base Image Retriever Abstraction.""" def text_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: """Retrieve image nodes given query or single image input. Args: str_or_query_bundle (QueryType): a query text string or a QueryBundle object. """ if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(query_str=str_or_query_bundle) return self._text_to_image_retrieve(str_or_query_bundle) @abstractmethod def _text_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Retrieve image nodes or documents given query text. Implemented by the user. """ def image_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: """Retrieve image nodes given single image input. Args: str_or_query_bundle (QueryType): a image path string or a QueryBundle object. """ if isinstance(str_or_query_bundle, str): # leave query_str as empty since we are using image_path for image retrieval str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return self._image_to_image_retrieve(str_or_query_bundle) @abstractmethod def _image_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Retrieve image nodes or documents given image. Implemented by the user. """ # Async Methods async def atext_to_image_retrieve( self, str_or_query_bundle: QueryType, ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(query_str=str_or_query_bundle) return await self._atext_to_image_retrieve(str_or_query_bundle) @abstractmethod async def _atext_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Async retrieve image nodes or documents given query text. Implemented by the user. """ async def aimage_to_image_retrieve( self, str_or_query_bundle: QueryType, ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): # leave query_str as empty since we are using image_path for image retrieval str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return await self._aimage_to_image_retrieve(str_or_query_bundle) @abstractmethod async def _aimage_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Async retrieve image nodes or documents given image. Implemented by the user. """
[ "llama_index.core.indices.query.schema.QueryBundle" ]
[((706, 748), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'str_or_query_bundle'}), '(query_str=str_or_query_bundle)\n', (717, 748), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((1525, 1582), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': '""""""', 'image_path': 'str_or_query_bundle'}), "(query_str='', image_path=str_or_query_bundle)\n", (1536, 1582), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((2145, 2187), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'str_or_query_bundle'}), '(query_str=str_or_query_bundle)\n', (2156, 2187), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((2813, 2870), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': '""""""', 'image_path': 'str_or_query_bundle'}), "(query_str='', image_path=str_or_query_bundle)\n", (2824, 2870), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n')]
from abc import abstractmethod from typing import List from llama_index.core.indices.query.schema import QueryBundle, QueryType from llama_index.core.prompts.mixin import PromptMixin from llama_index.core.schema import NodeWithScore class BaseImageRetriever(PromptMixin): """Base Image Retriever Abstraction.""" def text_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: """Retrieve image nodes given query or single image input. Args: str_or_query_bundle (QueryType): a query text string or a QueryBundle object. """ if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(query_str=str_or_query_bundle) return self._text_to_image_retrieve(str_or_query_bundle) @abstractmethod def _text_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Retrieve image nodes or documents given query text. Implemented by the user. """ def image_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: """Retrieve image nodes given single image input. Args: str_or_query_bundle (QueryType): a image path string or a QueryBundle object. """ if isinstance(str_or_query_bundle, str): # leave query_str as empty since we are using image_path for image retrieval str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return self._image_to_image_retrieve(str_or_query_bundle) @abstractmethod def _image_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Retrieve image nodes or documents given image. Implemented by the user. """ # Async Methods async def atext_to_image_retrieve( self, str_or_query_bundle: QueryType, ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(query_str=str_or_query_bundle) return await self._atext_to_image_retrieve(str_or_query_bundle) @abstractmethod async def _atext_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Async retrieve image nodes or documents given query text. Implemented by the user. """ async def aimage_to_image_retrieve( self, str_or_query_bundle: QueryType, ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): # leave query_str as empty since we are using image_path for image retrieval str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return await self._aimage_to_image_retrieve(str_or_query_bundle) @abstractmethod async def _aimage_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: """Async retrieve image nodes or documents given image. Implemented by the user. """
[ "llama_index.core.indices.query.schema.QueryBundle" ]
[((706, 748), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'str_or_query_bundle'}), '(query_str=str_or_query_bundle)\n', (717, 748), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((1525, 1582), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': '""""""', 'image_path': 'str_or_query_bundle'}), "(query_str='', image_path=str_or_query_bundle)\n", (1536, 1582), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((2145, 2187), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': 'str_or_query_bundle'}), '(query_str=str_or_query_bundle)\n', (2156, 2187), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n'), ((2813, 2870), 'llama_index.core.indices.query.schema.QueryBundle', 'QueryBundle', ([], {'query_str': '""""""', 'image_path': 'str_or_query_bundle'}), "(query_str='', image_path=str_or_query_bundle)\n", (2824, 2870), False, 'from llama_index.core.indices.query.schema import QueryBundle, QueryType\n')]
import json from abc import abstractmethod from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, Optional, Type if TYPE_CHECKING: from llama_index.legacy.bridge.langchain import StructuredTool, Tool from deprecated import deprecated from llama_index.legacy.bridge.pydantic import BaseModel class DefaultToolFnSchema(BaseModel): """Default tool function Schema.""" input: str @dataclass class ToolMetadata: description: str name: Optional[str] = None fn_schema: Optional[Type[BaseModel]] = DefaultToolFnSchema def get_parameters_dict(self) -> dict: if self.fn_schema is None: parameters = { "type": "object", "properties": { "input": {"title": "input query string", "type": "string"}, }, "required": ["input"], } else: parameters = self.fn_schema.schema() parameters = { k: v for k, v in parameters.items() if k in ["type", "properties", "required", "definitions"] } return parameters @property def fn_schema_str(self) -> str: """Get fn schema as string.""" if self.fn_schema is None: raise ValueError("fn_schema is None.") parameters = self.get_parameters_dict() return json.dumps(parameters) def get_name(self) -> str: """Get name.""" if self.name is None: raise ValueError("name is None.") return self.name @deprecated( "Deprecated in favor of `to_openai_tool`, which should be used instead." ) def to_openai_function(self) -> Dict[str, Any]: """Deprecated and replaced by `to_openai_tool`. The name and arguments of a function that should be called, as generated by the model. """ return { "name": self.name, "description": self.description, "parameters": self.get_parameters_dict(), } def to_openai_tool(self) -> Dict[str, Any]: """To OpenAI tool.""" return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.get_parameters_dict(), }, } class ToolOutput(BaseModel): """Tool output.""" content: str tool_name: str raw_input: Dict[str, Any] raw_output: Any def __str__(self) -> str: """String.""" return str(self.content) class BaseTool: @property @abstractmethod def metadata(self) -> ToolMetadata: pass @abstractmethod def __call__(self, input: Any) -> ToolOutput: pass def _process_langchain_tool_kwargs( self, langchain_tool_kwargs: Any, ) -> Dict[str, Any]: """Process langchain tool kwargs.""" if "name" not in langchain_tool_kwargs: langchain_tool_kwargs["name"] = self.metadata.name or "" if "description" not in langchain_tool_kwargs: langchain_tool_kwargs["description"] = self.metadata.description if "fn_schema" not in langchain_tool_kwargs: langchain_tool_kwargs["args_schema"] = self.metadata.fn_schema return langchain_tool_kwargs def to_langchain_tool( self, **langchain_tool_kwargs: Any, ) -> "Tool": """To langchain tool.""" from llama_index.legacy.bridge.langchain import Tool langchain_tool_kwargs = self._process_langchain_tool_kwargs( langchain_tool_kwargs ) return Tool.from_function( func=self.__call__, **langchain_tool_kwargs, ) def to_langchain_structured_tool( self, **langchain_tool_kwargs: Any, ) -> "StructuredTool": """To langchain structured tool.""" from llama_index.legacy.bridge.langchain import StructuredTool langchain_tool_kwargs = self._process_langchain_tool_kwargs( langchain_tool_kwargs ) return StructuredTool.from_function( func=self.__call__, **langchain_tool_kwargs, ) class AsyncBaseTool(BaseTool): """ Base-level tool class that is backwards compatible with the old tool spec but also supports async. """ def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput: return self.call(*args, **kwargs) @abstractmethod def call(self, input: Any) -> ToolOutput: """ This is the method that should be implemented by the tool developer. """ @abstractmethod async def acall(self, input: Any) -> ToolOutput: """ This is the async version of the call method. Should also be implemented by the tool developer as an async-compatible implementation. """ class BaseToolAsyncAdapter(AsyncBaseTool): """ Adapter class that allows a synchronous tool to be used as an async tool. """ def __init__(self, tool: BaseTool): self.base_tool = tool @property def metadata(self) -> ToolMetadata: return self.base_tool.metadata def call(self, input: Any) -> ToolOutput: return self.base_tool(input) async def acall(self, input: Any) -> ToolOutput: return self.call(input) def adapt_to_async_tool(tool: BaseTool) -> AsyncBaseTool: """ Converts a synchronous tool to an async tool. """ if isinstance(tool, AsyncBaseTool): return tool else: return BaseToolAsyncAdapter(tool)
[ "llama_index.legacy.bridge.langchain.Tool.from_function", "llama_index.legacy.bridge.langchain.StructuredTool.from_function" ]
[((1586, 1675), 'deprecated.deprecated', 'deprecated', (['"""Deprecated in favor of `to_openai_tool`, which should be used instead."""'], {}), "(\n 'Deprecated in favor of `to_openai_tool`, which should be used instead.')\n", (1596, 1675), False, 'from deprecated import deprecated\n'), ((1400, 1422), 'json.dumps', 'json.dumps', (['parameters'], {}), '(parameters)\n', (1410, 1422), False, 'import json\n'), ((3697, 3760), 'llama_index.legacy.bridge.langchain.Tool.from_function', 'Tool.from_function', ([], {'func': 'self.__call__'}), '(func=self.__call__, **langchain_tool_kwargs)\n', (3715, 3760), False, 'from llama_index.legacy.bridge.langchain import Tool\n'), ((4158, 4231), 'llama_index.legacy.bridge.langchain.StructuredTool.from_function', 'StructuredTool.from_function', ([], {'func': 'self.__call__'}), '(func=self.__call__, **langchain_tool_kwargs)\n', (4186, 4231), False, 'from llama_index.legacy.bridge.langchain import StructuredTool\n')]
import json from abc import abstractmethod from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, Optional, Type if TYPE_CHECKING: from llama_index.legacy.bridge.langchain import StructuredTool, Tool from deprecated import deprecated from llama_index.legacy.bridge.pydantic import BaseModel class DefaultToolFnSchema(BaseModel): """Default tool function Schema.""" input: str @dataclass class ToolMetadata: description: str name: Optional[str] = None fn_schema: Optional[Type[BaseModel]] = DefaultToolFnSchema def get_parameters_dict(self) -> dict: if self.fn_schema is None: parameters = { "type": "object", "properties": { "input": {"title": "input query string", "type": "string"}, }, "required": ["input"], } else: parameters = self.fn_schema.schema() parameters = { k: v for k, v in parameters.items() if k in ["type", "properties", "required", "definitions"] } return parameters @property def fn_schema_str(self) -> str: """Get fn schema as string.""" if self.fn_schema is None: raise ValueError("fn_schema is None.") parameters = self.get_parameters_dict() return json.dumps(parameters) def get_name(self) -> str: """Get name.""" if self.name is None: raise ValueError("name is None.") return self.name @deprecated( "Deprecated in favor of `to_openai_tool`, which should be used instead." ) def to_openai_function(self) -> Dict[str, Any]: """Deprecated and replaced by `to_openai_tool`. The name and arguments of a function that should be called, as generated by the model. """ return { "name": self.name, "description": self.description, "parameters": self.get_parameters_dict(), } def to_openai_tool(self) -> Dict[str, Any]: """To OpenAI tool.""" return { "type": "function", "function": { "name": self.name, "description": self.description, "parameters": self.get_parameters_dict(), }, } class ToolOutput(BaseModel): """Tool output.""" content: str tool_name: str raw_input: Dict[str, Any] raw_output: Any def __str__(self) -> str: """String.""" return str(self.content) class BaseTool: @property @abstractmethod def metadata(self) -> ToolMetadata: pass @abstractmethod def __call__(self, input: Any) -> ToolOutput: pass def _process_langchain_tool_kwargs( self, langchain_tool_kwargs: Any, ) -> Dict[str, Any]: """Process langchain tool kwargs.""" if "name" not in langchain_tool_kwargs: langchain_tool_kwargs["name"] = self.metadata.name or "" if "description" not in langchain_tool_kwargs: langchain_tool_kwargs["description"] = self.metadata.description if "fn_schema" not in langchain_tool_kwargs: langchain_tool_kwargs["args_schema"] = self.metadata.fn_schema return langchain_tool_kwargs def to_langchain_tool( self, **langchain_tool_kwargs: Any, ) -> "Tool": """To langchain tool.""" from llama_index.legacy.bridge.langchain import Tool langchain_tool_kwargs = self._process_langchain_tool_kwargs( langchain_tool_kwargs ) return Tool.from_function( func=self.__call__, **langchain_tool_kwargs, ) def to_langchain_structured_tool( self, **langchain_tool_kwargs: Any, ) -> "StructuredTool": """To langchain structured tool.""" from llama_index.legacy.bridge.langchain import StructuredTool langchain_tool_kwargs = self._process_langchain_tool_kwargs( langchain_tool_kwargs ) return StructuredTool.from_function( func=self.__call__, **langchain_tool_kwargs, ) class AsyncBaseTool(BaseTool): """ Base-level tool class that is backwards compatible with the old tool spec but also supports async. """ def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput: return self.call(*args, **kwargs) @abstractmethod def call(self, input: Any) -> ToolOutput: """ This is the method that should be implemented by the tool developer. """ @abstractmethod async def acall(self, input: Any) -> ToolOutput: """ This is the async version of the call method. Should also be implemented by the tool developer as an async-compatible implementation. """ class BaseToolAsyncAdapter(AsyncBaseTool): """ Adapter class that allows a synchronous tool to be used as an async tool. """ def __init__(self, tool: BaseTool): self.base_tool = tool @property def metadata(self) -> ToolMetadata: return self.base_tool.metadata def call(self, input: Any) -> ToolOutput: return self.base_tool(input) async def acall(self, input: Any) -> ToolOutput: return self.call(input) def adapt_to_async_tool(tool: BaseTool) -> AsyncBaseTool: """ Converts a synchronous tool to an async tool. """ if isinstance(tool, AsyncBaseTool): return tool else: return BaseToolAsyncAdapter(tool)
[ "llama_index.legacy.bridge.langchain.Tool.from_function", "llama_index.legacy.bridge.langchain.StructuredTool.from_function" ]
[((1586, 1675), 'deprecated.deprecated', 'deprecated', (['"""Deprecated in favor of `to_openai_tool`, which should be used instead."""'], {}), "(\n 'Deprecated in favor of `to_openai_tool`, which should be used instead.')\n", (1596, 1675), False, 'from deprecated import deprecated\n'), ((1400, 1422), 'json.dumps', 'json.dumps', (['parameters'], {}), '(parameters)\n', (1410, 1422), False, 'import json\n'), ((3697, 3760), 'llama_index.legacy.bridge.langchain.Tool.from_function', 'Tool.from_function', ([], {'func': 'self.__call__'}), '(func=self.__call__, **langchain_tool_kwargs)\n', (3715, 3760), False, 'from llama_index.legacy.bridge.langchain import Tool\n'), ((4158, 4231), 'llama_index.legacy.bridge.langchain.StructuredTool.from_function', 'StructuredTool.from_function', ([], {'func': 'self.__call__'}), '(func=self.__call__, **langchain_tool_kwargs)\n', (4186, 4231), False, 'from llama_index.legacy.bridge.langchain import StructuredTool\n')]
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast from deprecated import deprecated import llama_index.core from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.indices.prompt_helper import PromptHelper from llama_index.core.service_context_elements.llm_predictor import ( LLMPredictor, BaseLLMPredictor, ) from llama_index.core.base.llms.types import LLMMetadata from llama_index.core.llms.llm import LLM from llama_index.core.llms.utils import LLMType, resolve_llm from llama_index.core.service_context_elements.llama_logger import LlamaLogger from llama_index.core.node_parser.interface import NodeParser, TextSplitter from llama_index.core.node_parser.text.sentence import ( DEFAULT_CHUNK_SIZE, SENTENCE_CHUNK_OVERLAP, SentenceSplitter, ) from llama_index.core.prompts.base import BasePromptTemplate from llama_index.core.schema import TransformComponent from llama_index.core.types import PydanticProgramMode logger = logging.getLogger(__name__) def _get_default_node_parser( chunk_size: int = DEFAULT_CHUNK_SIZE, chunk_overlap: int = SENTENCE_CHUNK_OVERLAP, callback_manager: Optional[CallbackManager] = None, ) -> NodeParser: """Get default node parser.""" return SentenceSplitter( chunk_size=chunk_size, chunk_overlap=chunk_overlap, callback_manager=callback_manager or CallbackManager(), ) def _get_default_prompt_helper( llm_metadata: LLMMetadata, context_window: Optional[int] = None, num_output: Optional[int] = None, ) -> PromptHelper: """Get default prompt helper.""" if context_window is not None: llm_metadata.context_window = context_window if num_output is not None: llm_metadata.num_output = num_output return PromptHelper.from_llm_metadata(llm_metadata=llm_metadata) class ServiceContextData(BaseModel): llm: dict llm_predictor: dict prompt_helper: dict embed_model: dict transformations: List[dict] @dataclass class ServiceContext: """Service Context container. The service context container is a utility container for LlamaIndex index and query classes. It contains the following: - llm_predictor: BaseLLMPredictor - prompt_helper: PromptHelper - embed_model: BaseEmbedding - node_parser: NodeParser - llama_logger: LlamaLogger (deprecated) - callback_manager: CallbackManager """ llm_predictor: BaseLLMPredictor prompt_helper: PromptHelper embed_model: BaseEmbedding transformations: List[TransformComponent] llama_logger: LlamaLogger callback_manager: CallbackManager @classmethod @deprecated( version="0.10.0", reason="ServiceContext is deprecated, please use `llama_index.settings.Settings` instead.", ) def from_defaults( cls, llm_predictor: Optional[BaseLLMPredictor] = None, llm: Optional[LLMType] = "default", prompt_helper: Optional[PromptHelper] = None, embed_model: Optional[Any] = "default", node_parser: Optional[NodeParser] = None, text_splitter: Optional[TextSplitter] = None, transformations: Optional[List[TransformComponent]] = None, llama_logger: Optional[LlamaLogger] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, query_wrapper_prompt: Optional[BasePromptTemplate] = None, # pydantic program mode (used if output_cls is specified) pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, # node parser kwargs chunk_size: Optional[int] = None, chunk_overlap: Optional[int] = None, # prompt helper kwargs context_window: Optional[int] = None, num_output: Optional[int] = None, # deprecated kwargs chunk_size_limit: Optional[int] = None, ) -> "ServiceContext": """Create a ServiceContext from defaults. If an argument is specified, then use the argument value provided for that parameter. If an argument is not specified, then use the default value. You can change the base defaults by setting llama_index.global_service_context to a ServiceContext object with your desired settings. Args: llm_predictor (Optional[BaseLLMPredictor]): LLMPredictor prompt_helper (Optional[PromptHelper]): PromptHelper embed_model (Optional[BaseEmbedding]): BaseEmbedding or "local" (use local model) node_parser (Optional[NodeParser]): NodeParser llama_logger (Optional[LlamaLogger]): LlamaLogger (deprecated) chunk_size (Optional[int]): chunk_size callback_manager (Optional[CallbackManager]): CallbackManager system_prompt (Optional[str]): System-wide prompt to be prepended to all input prompts, used to guide system "decision making" query_wrapper_prompt (Optional[BasePromptTemplate]): A format to wrap passed-in input queries. Deprecated Args: chunk_size_limit (Optional[int]): renamed to chunk_size """ from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model embed_model = cast(EmbedType, embed_model) if chunk_size_limit is not None and chunk_size is None: logger.warning( "chunk_size_limit is deprecated, please specify chunk_size instead" ) chunk_size = chunk_size_limit if llama_index.core.global_service_context is not None: return cls.from_service_context( llama_index.core.global_service_context, llm=llm, llm_predictor=llm_predictor, prompt_helper=prompt_helper, embed_model=embed_model, node_parser=node_parser, text_splitter=text_splitter, llama_logger=llama_logger, callback_manager=callback_manager, context_window=context_window, chunk_size=chunk_size, chunk_size_limit=chunk_size_limit, chunk_overlap=chunk_overlap, num_output=num_output, system_prompt=system_prompt, query_wrapper_prompt=query_wrapper_prompt, transformations=transformations, ) callback_manager = callback_manager or CallbackManager([]) if llm != "default": if llm_predictor is not None: raise ValueError("Cannot specify both llm and llm_predictor") llm = resolve_llm(llm) llm.system_prompt = llm.system_prompt or system_prompt llm.query_wrapper_prompt = llm.query_wrapper_prompt or query_wrapper_prompt llm.pydantic_program_mode = ( llm.pydantic_program_mode or pydantic_program_mode ) if llm_predictor is not None: print("LLMPredictor is deprecated, please use LLM instead.") llm_predictor = llm_predictor or LLMPredictor( llm=llm, pydantic_program_mode=pydantic_program_mode ) if isinstance(llm_predictor, LLMPredictor): llm_predictor.llm.callback_manager = callback_manager if system_prompt: llm_predictor.system_prompt = system_prompt if query_wrapper_prompt: llm_predictor.query_wrapper_prompt = query_wrapper_prompt # NOTE: the embed_model isn't used in all indices # NOTE: embed model should be a transformation, but the way the service # context works, we can't put in there yet. embed_model = resolve_embed_model(embed_model) embed_model.callback_manager = callback_manager prompt_helper = prompt_helper or _get_default_prompt_helper( llm_metadata=llm_predictor.metadata, context_window=context_window, num_output=num_output, ) if text_splitter is not None and node_parser is not None: raise ValueError("Cannot specify both text_splitter and node_parser") node_parser = ( text_splitter # text splitter extends node parser or node_parser or _get_default_node_parser( chunk_size=chunk_size or DEFAULT_CHUNK_SIZE, chunk_overlap=chunk_overlap or SENTENCE_CHUNK_OVERLAP, callback_manager=callback_manager, ) ) transformations = transformations or [node_parser] llama_logger = llama_logger or LlamaLogger() return cls( llm_predictor=llm_predictor, embed_model=embed_model, prompt_helper=prompt_helper, transformations=transformations, llama_logger=llama_logger, # deprecated callback_manager=callback_manager, ) @classmethod def from_service_context( cls, service_context: "ServiceContext", llm_predictor: Optional[BaseLLMPredictor] = None, llm: Optional[LLMType] = "default", prompt_helper: Optional[PromptHelper] = None, embed_model: Optional[Any] = "default", node_parser: Optional[NodeParser] = None, text_splitter: Optional[TextSplitter] = None, transformations: Optional[List[TransformComponent]] = None, llama_logger: Optional[LlamaLogger] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, query_wrapper_prompt: Optional[BasePromptTemplate] = None, # node parser kwargs chunk_size: Optional[int] = None, chunk_overlap: Optional[int] = None, # prompt helper kwargs context_window: Optional[int] = None, num_output: Optional[int] = None, # deprecated kwargs chunk_size_limit: Optional[int] = None, ) -> "ServiceContext": """Instantiate a new service context using a previous as the defaults.""" from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model embed_model = cast(EmbedType, embed_model) if chunk_size_limit is not None and chunk_size is None: logger.warning( "chunk_size_limit is deprecated, please specify chunk_size", DeprecationWarning, ) chunk_size = chunk_size_limit callback_manager = callback_manager or service_context.callback_manager if llm != "default": if llm_predictor is not None: raise ValueError("Cannot specify both llm and llm_predictor") llm = resolve_llm(llm) llm_predictor = LLMPredictor(llm=llm) llm_predictor = llm_predictor or service_context.llm_predictor if isinstance(llm_predictor, LLMPredictor): llm_predictor.llm.callback_manager = callback_manager if system_prompt: llm_predictor.system_prompt = system_prompt if query_wrapper_prompt: llm_predictor.query_wrapper_prompt = query_wrapper_prompt # NOTE: the embed_model isn't used in all indices # default to using the embed model passed from the service context if embed_model == "default": embed_model = service_context.embed_model embed_model = resolve_embed_model(embed_model) embed_model.callback_manager = callback_manager prompt_helper = prompt_helper or service_context.prompt_helper if context_window is not None or num_output is not None: prompt_helper = _get_default_prompt_helper( llm_metadata=llm_predictor.metadata, context_window=context_window, num_output=num_output, ) transformations = transformations or [] node_parser_found = False for transform in service_context.transformations: if isinstance(transform, NodeParser): node_parser_found = True node_parser = transform break if text_splitter is not None and node_parser is not None: raise ValueError("Cannot specify both text_splitter and node_parser") if not node_parser_found: node_parser = ( text_splitter # text splitter extends node parser or node_parser or _get_default_node_parser( chunk_size=chunk_size or DEFAULT_CHUNK_SIZE, chunk_overlap=chunk_overlap or SENTENCE_CHUNK_OVERLAP, callback_manager=callback_manager, ) ) transformations = transformations or service_context.transformations llama_logger = llama_logger or service_context.llama_logger return cls( llm_predictor=llm_predictor, embed_model=embed_model, prompt_helper=prompt_helper, transformations=transformations, llama_logger=llama_logger, # deprecated callback_manager=callback_manager, ) @property def llm(self) -> LLM: return self.llm_predictor.llm @property def node_parser(self) -> NodeParser: """Get the node parser.""" for transform in self.transformations: if isinstance(transform, NodeParser): return transform raise ValueError("No node parser found.") def to_dict(self) -> dict: """Convert service context to dict.""" llm_dict = self.llm_predictor.llm.to_dict() llm_predictor_dict = self.llm_predictor.to_dict() embed_model_dict = self.embed_model.to_dict() prompt_helper_dict = self.prompt_helper.to_dict() tranform_list_dict = [x.to_dict() for x in self.transformations] return ServiceContextData( llm=llm_dict, llm_predictor=llm_predictor_dict, prompt_helper=prompt_helper_dict, embed_model=embed_model_dict, transformations=tranform_list_dict, ).dict() @classmethod def from_dict(cls, data: dict) -> "ServiceContext": from llama_index.core.embeddings.loading import load_embed_model from llama_index.core.extractors.loading import load_extractor from llama_index.core.node_parser.loading import load_parser from llama_index.core.service_context_elements.llm_predictor import ( load_predictor, ) service_context_data = ServiceContextData.parse_obj(data) llm_predictor = load_predictor(service_context_data.llm_predictor) embed_model = load_embed_model(service_context_data.embed_model) prompt_helper = PromptHelper.from_dict(service_context_data.prompt_helper) transformations: List[TransformComponent] = [] for transform in service_context_data.transformations: try: transformations.append(load_parser(transform)) except ValueError: transformations.append(load_extractor(transform)) return cls.from_defaults( llm_predictor=llm_predictor, prompt_helper=prompt_helper, embed_model=embed_model, transformations=transformations, ) def set_global_service_context(service_context: Optional[ServiceContext]) -> None: """Helper function to set the global service context.""" llama_index.core.global_service_context = service_context if service_context is not None: from llama_index.core.settings import Settings Settings.llm = service_context.llm Settings.embed_model = service_context.embed_model Settings.prompt_helper = service_context.prompt_helper Settings.transformations = service_context.transformations Settings.node_parser = service_context.node_parser Settings.callback_manager = service_context.callback_manager
[ "llama_index.core.llms.utils.resolve_llm", "llama_index.core.indices.prompt_helper.PromptHelper.from_llm_metadata", "llama_index.core.indices.prompt_helper.PromptHelper.from_dict", "llama_index.core.embeddings.utils.resolve_embed_model", "llama_index.core.embeddings.loading.load_embed_model", "llama_index.core.service_context_elements.llm_predictor.LLMPredictor", "llama_index.core.callbacks.base.CallbackManager", "llama_index.core.node_parser.loading.load_parser", "llama_index.core.extractors.loading.load_extractor", "llama_index.core.service_context_elements.llama_logger.LlamaLogger", "llama_index.core.service_context_elements.llm_predictor.load_predictor" ]
[((1138, 1165), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1155, 1165), False, 'import logging\n'), ((1940, 1997), 'llama_index.core.indices.prompt_helper.PromptHelper.from_llm_metadata', 'PromptHelper.from_llm_metadata', ([], {'llm_metadata': 'llm_metadata'}), '(llm_metadata=llm_metadata)\n', (1970, 1997), False, 'from llama_index.core.indices.prompt_helper import PromptHelper\n'), ((2817, 2947), 'deprecated.deprecated', 'deprecated', ([], {'version': '"""0.10.0"""', 'reason': '"""ServiceContext is deprecated, please use `llama_index.settings.Settings` instead."""'}), "(version='0.10.0', reason=\n 'ServiceContext is deprecated, please use `llama_index.settings.Settings` instead.'\n )\n", (2827, 2947), False, 'from deprecated import deprecated\n'), ((5458, 5486), 'typing.cast', 'cast', (['EmbedType', 'embed_model'], {}), '(EmbedType, embed_model)\n', (5462, 5486), False, 'from typing import Any, List, Optional, cast\n'), ((7915, 7947), 'llama_index.core.embeddings.utils.resolve_embed_model', 'resolve_embed_model', (['embed_model'], {}), '(embed_model)\n', (7934, 7947), False, 'from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model\n'), ((10364, 10392), 'typing.cast', 'cast', (['EmbedType', 'embed_model'], {}), '(EmbedType, embed_model)\n', (10368, 10392), False, 'from typing import Any, List, Optional, cast\n'), ((11608, 11640), 'llama_index.core.embeddings.utils.resolve_embed_model', 'resolve_embed_model', (['embed_model'], {}), '(embed_model)\n', (11627, 11640), False, 'from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model\n'), ((14844, 14894), 'llama_index.core.service_context_elements.llm_predictor.load_predictor', 'load_predictor', (['service_context_data.llm_predictor'], {}), '(service_context_data.llm_predictor)\n', (14858, 14894), False, 'from llama_index.core.service_context_elements.llm_predictor import load_predictor\n'), ((14918, 14968), 'llama_index.core.embeddings.loading.load_embed_model', 'load_embed_model', (['service_context_data.embed_model'], {}), '(service_context_data.embed_model)\n', (14934, 14968), False, 'from llama_index.core.embeddings.loading import load_embed_model\n'), ((14994, 15052), 'llama_index.core.indices.prompt_helper.PromptHelper.from_dict', 'PromptHelper.from_dict', (['service_context_data.prompt_helper'], {}), '(service_context_data.prompt_helper)\n', (15016, 15052), False, 'from llama_index.core.indices.prompt_helper import PromptHelper\n'), ((6659, 6678), 'llama_index.core.callbacks.base.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (6674, 6678), False, 'from llama_index.core.callbacks.base import CallbackManager\n'), ((6846, 6862), 'llama_index.core.llms.utils.resolve_llm', 'resolve_llm', (['llm'], {}), '(llm)\n', (6857, 6862), False, 'from llama_index.core.llms.utils import LLMType, resolve_llm\n'), ((7294, 7360), 'llama_index.core.service_context_elements.llm_predictor.LLMPredictor', 'LLMPredictor', ([], {'llm': 'llm', 'pydantic_program_mode': 'pydantic_program_mode'}), '(llm=llm, pydantic_program_mode=pydantic_program_mode)\n', (7306, 7360), False, 'from llama_index.core.service_context_elements.llm_predictor import LLMPredictor, BaseLLMPredictor\n'), ((8823, 8836), 'llama_index.core.service_context_elements.llama_logger.LlamaLogger', 'LlamaLogger', ([], {}), '()\n', (8834, 8836), False, 'from llama_index.core.service_context_elements.llama_logger import LlamaLogger\n'), ((10903, 10919), 'llama_index.core.llms.utils.resolve_llm', 'resolve_llm', (['llm'], {}), '(llm)\n', (10914, 10919), False, 'from llama_index.core.llms.utils import LLMType, resolve_llm\n'), ((10948, 10969), 'llama_index.core.service_context_elements.llm_predictor.LLMPredictor', 'LLMPredictor', ([], {'llm': 'llm'}), '(llm=llm)\n', (10960, 10969), False, 'from llama_index.core.service_context_elements.llm_predictor import LLMPredictor, BaseLLMPredictor\n'), ((1539, 1556), 'llama_index.core.callbacks.base.CallbackManager', 'CallbackManager', ([], {}), '()\n', (1554, 1556), False, 'from llama_index.core.callbacks.base import CallbackManager\n'), ((15228, 15250), 'llama_index.core.node_parser.loading.load_parser', 'load_parser', (['transform'], {}), '(transform)\n', (15239, 15250), False, 'from llama_index.core.node_parser.loading import load_parser\n'), ((15322, 15347), 'llama_index.core.extractors.loading.load_extractor', 'load_extractor', (['transform'], {}), '(transform)\n', (15336, 15347), False, 'from llama_index.core.extractors.loading import load_extractor\n')]
import logging from dataclasses import dataclass from typing import Any, List, Optional, cast from deprecated import deprecated import llama_index.core from llama_index.core.bridge.pydantic import BaseModel from llama_index.core.callbacks.base import CallbackManager from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.indices.prompt_helper import PromptHelper from llama_index.core.service_context_elements.llm_predictor import ( LLMPredictor, BaseLLMPredictor, ) from llama_index.core.base.llms.types import LLMMetadata from llama_index.core.llms.llm import LLM from llama_index.core.llms.utils import LLMType, resolve_llm from llama_index.core.service_context_elements.llama_logger import LlamaLogger from llama_index.core.node_parser.interface import NodeParser, TextSplitter from llama_index.core.node_parser.text.sentence import ( DEFAULT_CHUNK_SIZE, SENTENCE_CHUNK_OVERLAP, SentenceSplitter, ) from llama_index.core.prompts.base import BasePromptTemplate from llama_index.core.schema import TransformComponent from llama_index.core.types import PydanticProgramMode logger = logging.getLogger(__name__) def _get_default_node_parser( chunk_size: int = DEFAULT_CHUNK_SIZE, chunk_overlap: int = SENTENCE_CHUNK_OVERLAP, callback_manager: Optional[CallbackManager] = None, ) -> NodeParser: """Get default node parser.""" return SentenceSplitter( chunk_size=chunk_size, chunk_overlap=chunk_overlap, callback_manager=callback_manager or CallbackManager(), ) def _get_default_prompt_helper( llm_metadata: LLMMetadata, context_window: Optional[int] = None, num_output: Optional[int] = None, ) -> PromptHelper: """Get default prompt helper.""" if context_window is not None: llm_metadata.context_window = context_window if num_output is not None: llm_metadata.num_output = num_output return PromptHelper.from_llm_metadata(llm_metadata=llm_metadata) class ServiceContextData(BaseModel): llm: dict llm_predictor: dict prompt_helper: dict embed_model: dict transformations: List[dict] @dataclass class ServiceContext: """Service Context container. The service context container is a utility container for LlamaIndex index and query classes. It contains the following: - llm_predictor: BaseLLMPredictor - prompt_helper: PromptHelper - embed_model: BaseEmbedding - node_parser: NodeParser - llama_logger: LlamaLogger (deprecated) - callback_manager: CallbackManager """ llm_predictor: BaseLLMPredictor prompt_helper: PromptHelper embed_model: BaseEmbedding transformations: List[TransformComponent] llama_logger: LlamaLogger callback_manager: CallbackManager @classmethod @deprecated( version="0.10.0", reason="ServiceContext is deprecated, please use `llama_index.settings.Settings` instead.", ) def from_defaults( cls, llm_predictor: Optional[BaseLLMPredictor] = None, llm: Optional[LLMType] = "default", prompt_helper: Optional[PromptHelper] = None, embed_model: Optional[Any] = "default", node_parser: Optional[NodeParser] = None, text_splitter: Optional[TextSplitter] = None, transformations: Optional[List[TransformComponent]] = None, llama_logger: Optional[LlamaLogger] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, query_wrapper_prompt: Optional[BasePromptTemplate] = None, # pydantic program mode (used if output_cls is specified) pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, # node parser kwargs chunk_size: Optional[int] = None, chunk_overlap: Optional[int] = None, # prompt helper kwargs context_window: Optional[int] = None, num_output: Optional[int] = None, # deprecated kwargs chunk_size_limit: Optional[int] = None, ) -> "ServiceContext": """Create a ServiceContext from defaults. If an argument is specified, then use the argument value provided for that parameter. If an argument is not specified, then use the default value. You can change the base defaults by setting llama_index.global_service_context to a ServiceContext object with your desired settings. Args: llm_predictor (Optional[BaseLLMPredictor]): LLMPredictor prompt_helper (Optional[PromptHelper]): PromptHelper embed_model (Optional[BaseEmbedding]): BaseEmbedding or "local" (use local model) node_parser (Optional[NodeParser]): NodeParser llama_logger (Optional[LlamaLogger]): LlamaLogger (deprecated) chunk_size (Optional[int]): chunk_size callback_manager (Optional[CallbackManager]): CallbackManager system_prompt (Optional[str]): System-wide prompt to be prepended to all input prompts, used to guide system "decision making" query_wrapper_prompt (Optional[BasePromptTemplate]): A format to wrap passed-in input queries. Deprecated Args: chunk_size_limit (Optional[int]): renamed to chunk_size """ from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model embed_model = cast(EmbedType, embed_model) if chunk_size_limit is not None and chunk_size is None: logger.warning( "chunk_size_limit is deprecated, please specify chunk_size instead" ) chunk_size = chunk_size_limit if llama_index.core.global_service_context is not None: return cls.from_service_context( llama_index.core.global_service_context, llm=llm, llm_predictor=llm_predictor, prompt_helper=prompt_helper, embed_model=embed_model, node_parser=node_parser, text_splitter=text_splitter, llama_logger=llama_logger, callback_manager=callback_manager, context_window=context_window, chunk_size=chunk_size, chunk_size_limit=chunk_size_limit, chunk_overlap=chunk_overlap, num_output=num_output, system_prompt=system_prompt, query_wrapper_prompt=query_wrapper_prompt, transformations=transformations, ) callback_manager = callback_manager or CallbackManager([]) if llm != "default": if llm_predictor is not None: raise ValueError("Cannot specify both llm and llm_predictor") llm = resolve_llm(llm) llm.system_prompt = llm.system_prompt or system_prompt llm.query_wrapper_prompt = llm.query_wrapper_prompt or query_wrapper_prompt llm.pydantic_program_mode = ( llm.pydantic_program_mode or pydantic_program_mode ) if llm_predictor is not None: print("LLMPredictor is deprecated, please use LLM instead.") llm_predictor = llm_predictor or LLMPredictor( llm=llm, pydantic_program_mode=pydantic_program_mode ) if isinstance(llm_predictor, LLMPredictor): llm_predictor.llm.callback_manager = callback_manager if system_prompt: llm_predictor.system_prompt = system_prompt if query_wrapper_prompt: llm_predictor.query_wrapper_prompt = query_wrapper_prompt # NOTE: the embed_model isn't used in all indices # NOTE: embed model should be a transformation, but the way the service # context works, we can't put in there yet. embed_model = resolve_embed_model(embed_model) embed_model.callback_manager = callback_manager prompt_helper = prompt_helper or _get_default_prompt_helper( llm_metadata=llm_predictor.metadata, context_window=context_window, num_output=num_output, ) if text_splitter is not None and node_parser is not None: raise ValueError("Cannot specify both text_splitter and node_parser") node_parser = ( text_splitter # text splitter extends node parser or node_parser or _get_default_node_parser( chunk_size=chunk_size or DEFAULT_CHUNK_SIZE, chunk_overlap=chunk_overlap or SENTENCE_CHUNK_OVERLAP, callback_manager=callback_manager, ) ) transformations = transformations or [node_parser] llama_logger = llama_logger or LlamaLogger() return cls( llm_predictor=llm_predictor, embed_model=embed_model, prompt_helper=prompt_helper, transformations=transformations, llama_logger=llama_logger, # deprecated callback_manager=callback_manager, ) @classmethod def from_service_context( cls, service_context: "ServiceContext", llm_predictor: Optional[BaseLLMPredictor] = None, llm: Optional[LLMType] = "default", prompt_helper: Optional[PromptHelper] = None, embed_model: Optional[Any] = "default", node_parser: Optional[NodeParser] = None, text_splitter: Optional[TextSplitter] = None, transformations: Optional[List[TransformComponent]] = None, llama_logger: Optional[LlamaLogger] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, query_wrapper_prompt: Optional[BasePromptTemplate] = None, # node parser kwargs chunk_size: Optional[int] = None, chunk_overlap: Optional[int] = None, # prompt helper kwargs context_window: Optional[int] = None, num_output: Optional[int] = None, # deprecated kwargs chunk_size_limit: Optional[int] = None, ) -> "ServiceContext": """Instantiate a new service context using a previous as the defaults.""" from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model embed_model = cast(EmbedType, embed_model) if chunk_size_limit is not None and chunk_size is None: logger.warning( "chunk_size_limit is deprecated, please specify chunk_size", DeprecationWarning, ) chunk_size = chunk_size_limit callback_manager = callback_manager or service_context.callback_manager if llm != "default": if llm_predictor is not None: raise ValueError("Cannot specify both llm and llm_predictor") llm = resolve_llm(llm) llm_predictor = LLMPredictor(llm=llm) llm_predictor = llm_predictor or service_context.llm_predictor if isinstance(llm_predictor, LLMPredictor): llm_predictor.llm.callback_manager = callback_manager if system_prompt: llm_predictor.system_prompt = system_prompt if query_wrapper_prompt: llm_predictor.query_wrapper_prompt = query_wrapper_prompt # NOTE: the embed_model isn't used in all indices # default to using the embed model passed from the service context if embed_model == "default": embed_model = service_context.embed_model embed_model = resolve_embed_model(embed_model) embed_model.callback_manager = callback_manager prompt_helper = prompt_helper or service_context.prompt_helper if context_window is not None or num_output is not None: prompt_helper = _get_default_prompt_helper( llm_metadata=llm_predictor.metadata, context_window=context_window, num_output=num_output, ) transformations = transformations or [] node_parser_found = False for transform in service_context.transformations: if isinstance(transform, NodeParser): node_parser_found = True node_parser = transform break if text_splitter is not None and node_parser is not None: raise ValueError("Cannot specify both text_splitter and node_parser") if not node_parser_found: node_parser = ( text_splitter # text splitter extends node parser or node_parser or _get_default_node_parser( chunk_size=chunk_size or DEFAULT_CHUNK_SIZE, chunk_overlap=chunk_overlap or SENTENCE_CHUNK_OVERLAP, callback_manager=callback_manager, ) ) transformations = transformations or service_context.transformations llama_logger = llama_logger or service_context.llama_logger return cls( llm_predictor=llm_predictor, embed_model=embed_model, prompt_helper=prompt_helper, transformations=transformations, llama_logger=llama_logger, # deprecated callback_manager=callback_manager, ) @property def llm(self) -> LLM: return self.llm_predictor.llm @property def node_parser(self) -> NodeParser: """Get the node parser.""" for transform in self.transformations: if isinstance(transform, NodeParser): return transform raise ValueError("No node parser found.") def to_dict(self) -> dict: """Convert service context to dict.""" llm_dict = self.llm_predictor.llm.to_dict() llm_predictor_dict = self.llm_predictor.to_dict() embed_model_dict = self.embed_model.to_dict() prompt_helper_dict = self.prompt_helper.to_dict() tranform_list_dict = [x.to_dict() for x in self.transformations] return ServiceContextData( llm=llm_dict, llm_predictor=llm_predictor_dict, prompt_helper=prompt_helper_dict, embed_model=embed_model_dict, transformations=tranform_list_dict, ).dict() @classmethod def from_dict(cls, data: dict) -> "ServiceContext": from llama_index.core.embeddings.loading import load_embed_model from llama_index.core.extractors.loading import load_extractor from llama_index.core.node_parser.loading import load_parser from llama_index.core.service_context_elements.llm_predictor import ( load_predictor, ) service_context_data = ServiceContextData.parse_obj(data) llm_predictor = load_predictor(service_context_data.llm_predictor) embed_model = load_embed_model(service_context_data.embed_model) prompt_helper = PromptHelper.from_dict(service_context_data.prompt_helper) transformations: List[TransformComponent] = [] for transform in service_context_data.transformations: try: transformations.append(load_parser(transform)) except ValueError: transformations.append(load_extractor(transform)) return cls.from_defaults( llm_predictor=llm_predictor, prompt_helper=prompt_helper, embed_model=embed_model, transformations=transformations, ) def set_global_service_context(service_context: Optional[ServiceContext]) -> None: """Helper function to set the global service context.""" llama_index.core.global_service_context = service_context if service_context is not None: from llama_index.core.settings import Settings Settings.llm = service_context.llm Settings.embed_model = service_context.embed_model Settings.prompt_helper = service_context.prompt_helper Settings.transformations = service_context.transformations Settings.node_parser = service_context.node_parser Settings.callback_manager = service_context.callback_manager
[ "llama_index.core.llms.utils.resolve_llm", "llama_index.core.indices.prompt_helper.PromptHelper.from_llm_metadata", "llama_index.core.indices.prompt_helper.PromptHelper.from_dict", "llama_index.core.embeddings.utils.resolve_embed_model", "llama_index.core.embeddings.loading.load_embed_model", "llama_index.core.service_context_elements.llm_predictor.LLMPredictor", "llama_index.core.callbacks.base.CallbackManager", "llama_index.core.node_parser.loading.load_parser", "llama_index.core.extractors.loading.load_extractor", "llama_index.core.service_context_elements.llama_logger.LlamaLogger", "llama_index.core.service_context_elements.llm_predictor.load_predictor" ]
[((1138, 1165), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1155, 1165), False, 'import logging\n'), ((1940, 1997), 'llama_index.core.indices.prompt_helper.PromptHelper.from_llm_metadata', 'PromptHelper.from_llm_metadata', ([], {'llm_metadata': 'llm_metadata'}), '(llm_metadata=llm_metadata)\n', (1970, 1997), False, 'from llama_index.core.indices.prompt_helper import PromptHelper\n'), ((2817, 2947), 'deprecated.deprecated', 'deprecated', ([], {'version': '"""0.10.0"""', 'reason': '"""ServiceContext is deprecated, please use `llama_index.settings.Settings` instead."""'}), "(version='0.10.0', reason=\n 'ServiceContext is deprecated, please use `llama_index.settings.Settings` instead.'\n )\n", (2827, 2947), False, 'from deprecated import deprecated\n'), ((5458, 5486), 'typing.cast', 'cast', (['EmbedType', 'embed_model'], {}), '(EmbedType, embed_model)\n', (5462, 5486), False, 'from typing import Any, List, Optional, cast\n'), ((7915, 7947), 'llama_index.core.embeddings.utils.resolve_embed_model', 'resolve_embed_model', (['embed_model'], {}), '(embed_model)\n', (7934, 7947), False, 'from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model\n'), ((10364, 10392), 'typing.cast', 'cast', (['EmbedType', 'embed_model'], {}), '(EmbedType, embed_model)\n', (10368, 10392), False, 'from typing import Any, List, Optional, cast\n'), ((11608, 11640), 'llama_index.core.embeddings.utils.resolve_embed_model', 'resolve_embed_model', (['embed_model'], {}), '(embed_model)\n', (11627, 11640), False, 'from llama_index.core.embeddings.utils import EmbedType, resolve_embed_model\n'), ((14844, 14894), 'llama_index.core.service_context_elements.llm_predictor.load_predictor', 'load_predictor', (['service_context_data.llm_predictor'], {}), '(service_context_data.llm_predictor)\n', (14858, 14894), False, 'from llama_index.core.service_context_elements.llm_predictor import load_predictor\n'), ((14918, 14968), 'llama_index.core.embeddings.loading.load_embed_model', 'load_embed_model', (['service_context_data.embed_model'], {}), '(service_context_data.embed_model)\n', (14934, 14968), False, 'from llama_index.core.embeddings.loading import load_embed_model\n'), ((14994, 15052), 'llama_index.core.indices.prompt_helper.PromptHelper.from_dict', 'PromptHelper.from_dict', (['service_context_data.prompt_helper'], {}), '(service_context_data.prompt_helper)\n', (15016, 15052), False, 'from llama_index.core.indices.prompt_helper import PromptHelper\n'), ((6659, 6678), 'llama_index.core.callbacks.base.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (6674, 6678), False, 'from llama_index.core.callbacks.base import CallbackManager\n'), ((6846, 6862), 'llama_index.core.llms.utils.resolve_llm', 'resolve_llm', (['llm'], {}), '(llm)\n', (6857, 6862), False, 'from llama_index.core.llms.utils import LLMType, resolve_llm\n'), ((7294, 7360), 'llama_index.core.service_context_elements.llm_predictor.LLMPredictor', 'LLMPredictor', ([], {'llm': 'llm', 'pydantic_program_mode': 'pydantic_program_mode'}), '(llm=llm, pydantic_program_mode=pydantic_program_mode)\n', (7306, 7360), False, 'from llama_index.core.service_context_elements.llm_predictor import LLMPredictor, BaseLLMPredictor\n'), ((8823, 8836), 'llama_index.core.service_context_elements.llama_logger.LlamaLogger', 'LlamaLogger', ([], {}), '()\n', (8834, 8836), False, 'from llama_index.core.service_context_elements.llama_logger import LlamaLogger\n'), ((10903, 10919), 'llama_index.core.llms.utils.resolve_llm', 'resolve_llm', (['llm'], {}), '(llm)\n', (10914, 10919), False, 'from llama_index.core.llms.utils import LLMType, resolve_llm\n'), ((10948, 10969), 'llama_index.core.service_context_elements.llm_predictor.LLMPredictor', 'LLMPredictor', ([], {'llm': 'llm'}), '(llm=llm)\n', (10960, 10969), False, 'from llama_index.core.service_context_elements.llm_predictor import LLMPredictor, BaseLLMPredictor\n'), ((1539, 1556), 'llama_index.core.callbacks.base.CallbackManager', 'CallbackManager', ([], {}), '()\n', (1554, 1556), False, 'from llama_index.core.callbacks.base import CallbackManager\n'), ((15228, 15250), 'llama_index.core.node_parser.loading.load_parser', 'load_parser', (['transform'], {}), '(transform)\n', (15239, 15250), False, 'from llama_index.core.node_parser.loading import load_parser\n'), ((15322, 15347), 'llama_index.core.extractors.loading.load_extractor', 'load_extractor', (['transform'], {}), '(transform)\n', (15336, 15347), False, 'from llama_index.core.extractors.loading import load_extractor\n')]
from typing import List, Optional import fsspec from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.schema import BaseNode from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc from llama_index.core.storage.kvstore import ( SimpleKVStore as SimpleCache, ) from llama_index.core.storage.kvstore.types import ( BaseKVStore as BaseCache, ) DEFAULT_CACHE_NAME = "llama_cache" class IngestionCache(BaseModel): class Config: arbitrary_types_allowed = True nodes_key = "nodes" collection: str = Field( default=DEFAULT_CACHE_NAME, description="Collection name of the cache." ) cache: BaseCache = Field(default_factory=SimpleCache, description="Cache to use.") # TODO: add async get/put methods? def put( self, key: str, nodes: List[BaseNode], collection: Optional[str] = None ) -> None: """Put a value into the cache.""" collection = collection or self.collection val = {self.nodes_key: [doc_to_json(node) for node in nodes]} self.cache.put(key, val, collection=collection) def get( self, key: str, collection: Optional[str] = None ) -> Optional[List[BaseNode]]: """Get a value from the cache.""" collection = collection or self.collection node_dicts = self.cache.get(key, collection=collection) if node_dicts is None: return None return [json_to_doc(node_dict) for node_dict in node_dicts[self.nodes_key]] def clear(self, collection: Optional[str] = None) -> None: """Clear the cache.""" collection = collection or self.collection data = self.cache.get_all(collection=collection) for key in data: self.cache.delete(key, collection=collection) def persist( self, persist_path: str, fs: Optional[fsspec.AbstractFileSystem] = None ) -> None: """Persist the cache to a directory, if possible.""" if isinstance(self.cache, SimpleCache): self.cache.persist(persist_path, fs=fs) else: print("Warning: skipping persist, only needed for SimpleCache.") @classmethod def from_persist_path( cls, persist_path: str, collection: str = DEFAULT_CACHE_NAME, fs: Optional[fsspec.AbstractFileSystem] = None, ) -> "IngestionCache": """Create a IngestionCache from a persist directory.""" return cls( collection=collection, cache=SimpleCache.from_persist_path(persist_path, fs=fs), ) __all__ = ["SimpleCache", "BaseCache"]
[ "llama_index.core.storage.kvstore.SimpleKVStore.from_persist_path", "llama_index.core.bridge.pydantic.Field", "llama_index.core.storage.docstore.utils.json_to_doc", "llama_index.core.storage.docstore.utils.doc_to_json" ]
[((577, 655), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_CACHE_NAME', 'description': '"""Collection name of the cache."""'}), "(default=DEFAULT_CACHE_NAME, description='Collection name of the cache.')\n", (582, 655), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((693, 756), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'SimpleCache', 'description': '"""Cache to use."""'}), "(default_factory=SimpleCache, description='Cache to use.')\n", (698, 756), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1461, 1483), 'llama_index.core.storage.docstore.utils.json_to_doc', 'json_to_doc', (['node_dict'], {}), '(node_dict)\n', (1472, 1483), False, 'from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc\n'), ((1031, 1048), 'llama_index.core.storage.docstore.utils.doc_to_json', 'doc_to_json', (['node'], {}), '(node)\n', (1042, 1048), False, 'from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc\n'), ((2531, 2581), 'llama_index.core.storage.kvstore.SimpleKVStore.from_persist_path', 'SimpleCache.from_persist_path', (['persist_path'], {'fs': 'fs'}), '(persist_path, fs=fs)\n', (2560, 2581), True, 'from llama_index.core.storage.kvstore import SimpleKVStore as SimpleCache\n')]
from typing import List, Optional import fsspec from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.schema import BaseNode from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc from llama_index.core.storage.kvstore import ( SimpleKVStore as SimpleCache, ) from llama_index.core.storage.kvstore.types import ( BaseKVStore as BaseCache, ) DEFAULT_CACHE_NAME = "llama_cache" class IngestionCache(BaseModel): class Config: arbitrary_types_allowed = True nodes_key = "nodes" collection: str = Field( default=DEFAULT_CACHE_NAME, description="Collection name of the cache." ) cache: BaseCache = Field(default_factory=SimpleCache, description="Cache to use.") # TODO: add async get/put methods? def put( self, key: str, nodes: List[BaseNode], collection: Optional[str] = None ) -> None: """Put a value into the cache.""" collection = collection or self.collection val = {self.nodes_key: [doc_to_json(node) for node in nodes]} self.cache.put(key, val, collection=collection) def get( self, key: str, collection: Optional[str] = None ) -> Optional[List[BaseNode]]: """Get a value from the cache.""" collection = collection or self.collection node_dicts = self.cache.get(key, collection=collection) if node_dicts is None: return None return [json_to_doc(node_dict) for node_dict in node_dicts[self.nodes_key]] def clear(self, collection: Optional[str] = None) -> None: """Clear the cache.""" collection = collection or self.collection data = self.cache.get_all(collection=collection) for key in data: self.cache.delete(key, collection=collection) def persist( self, persist_path: str, fs: Optional[fsspec.AbstractFileSystem] = None ) -> None: """Persist the cache to a directory, if possible.""" if isinstance(self.cache, SimpleCache): self.cache.persist(persist_path, fs=fs) else: print("Warning: skipping persist, only needed for SimpleCache.") @classmethod def from_persist_path( cls, persist_path: str, collection: str = DEFAULT_CACHE_NAME, fs: Optional[fsspec.AbstractFileSystem] = None, ) -> "IngestionCache": """Create a IngestionCache from a persist directory.""" return cls( collection=collection, cache=SimpleCache.from_persist_path(persist_path, fs=fs), ) __all__ = ["SimpleCache", "BaseCache"]
[ "llama_index.core.storage.kvstore.SimpleKVStore.from_persist_path", "llama_index.core.bridge.pydantic.Field", "llama_index.core.storage.docstore.utils.json_to_doc", "llama_index.core.storage.docstore.utils.doc_to_json" ]
[((577, 655), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_CACHE_NAME', 'description': '"""Collection name of the cache."""'}), "(default=DEFAULT_CACHE_NAME, description='Collection name of the cache.')\n", (582, 655), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((693, 756), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'SimpleCache', 'description': '"""Cache to use."""'}), "(default_factory=SimpleCache, description='Cache to use.')\n", (698, 756), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1461, 1483), 'llama_index.core.storage.docstore.utils.json_to_doc', 'json_to_doc', (['node_dict'], {}), '(node_dict)\n', (1472, 1483), False, 'from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc\n'), ((1031, 1048), 'llama_index.core.storage.docstore.utils.doc_to_json', 'doc_to_json', (['node'], {}), '(node)\n', (1042, 1048), False, 'from llama_index.core.storage.docstore.utils import doc_to_json, json_to_doc\n'), ((2531, 2581), 'llama_index.core.storage.kvstore.SimpleKVStore.from_persist_path', 'SimpleCache.from_persist_path', (['persist_path'], {'fs': 'fs'}), '(persist_path, fs=fs)\n', (2560, 2581), True, 'from llama_index.core.storage.kvstore import SimpleKVStore as SimpleCache\n')]
"""Base object types.""" import pickle import warnings from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.core.query_pipeline.query_component import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.legacy.indices.base import BaseIndex from llama_index.legacy.indices.vector_store.base import VectorStoreIndex from llama_index.legacy.objects.base_node_mapping import ( DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping, ) from llama_index.legacy.schema import QueryType from llama_index.legacy.storage.storage_context import ( DEFAULT_PERSIST_DIR, StorageContext, ) OT = TypeVar("OT") class ObjectRetriever(ChainableMixin, Generic[OT]): """Object retriever.""" def __init__( self, retriever: BaseRetriever, object_node_mapping: BaseObjectNodeMapping[OT] ): self._retriever = retriever self._object_node_mapping = object_node_mapping @property def retriever(self) -> BaseRetriever: """Retriever.""" return self._retriever def retrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = self._retriever.retrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] async def aretrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = await self._retriever.aretrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" return ObjectRetrieverComponent(retriever=self) class ObjectRetrieverComponent(QueryComponent): """Object retriever component.""" retriever: ObjectRetriever = Field(..., description="Retriever.") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" self.retriever.retriever.callback_manager = callback_manager def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" # make sure input is a string input["input"] = validate_and_convert_stringable(input["input"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" output = self.retriever.retrieve(kwargs["input"]) return {"output": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" output = await self.retriever.aretrieve(kwargs["input"]) return {"output": output} @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys({"input"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class ObjectIndex(Generic[OT]): """Object index.""" def __init__( self, index: BaseIndex, object_node_mapping: BaseObjectNodeMapping ) -> None: self._index = index self._object_node_mapping = object_node_mapping @classmethod def from_objects( cls, objects: Sequence[OT], object_mapping: Optional[BaseObjectNodeMapping] = None, index_cls: Type[BaseIndex] = VectorStoreIndex, **index_kwargs: Any, ) -> "ObjectIndex": if object_mapping is None: object_mapping = SimpleObjectNodeMapping.from_objects(objects) nodes = object_mapping.to_nodes(objects) index = index_cls(nodes, **index_kwargs) return cls(index, object_mapping) def insert_object(self, obj: Any) -> None: self._object_node_mapping.add_object(obj) node = self._object_node_mapping.to_node(obj) self._index.insert_nodes([node]) def as_retriever(self, **kwargs: Any) -> ObjectRetriever: return ObjectRetriever( retriever=self._index.as_retriever(**kwargs), object_node_mapping=self._object_node_mapping, ) def as_node_retriever(self, **kwargs: Any) -> BaseRetriever: return self._index.as_retriever(**kwargs) def persist( self, persist_dir: str = DEFAULT_PERSIST_DIR, obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME, ) -> None: # try to persist object node mapping try: self._object_node_mapping.persist( persist_dir=persist_dir, obj_node_mapping_fname=obj_node_mapping_fname ) except (NotImplementedError, pickle.PickleError) as err: warnings.warn( ( "Unable to persist ObjectNodeMapping. You will need to " "reconstruct the same object node mapping to build this ObjectIndex" ), stacklevel=2, ) self._index._storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls, persist_dir: str = DEFAULT_PERSIST_DIR, object_node_mapping: Optional[BaseObjectNodeMapping] = None, ) -> "ObjectIndex": from llama_index.legacy.indices import load_index_from_storage storage_context = StorageContext.from_defaults(persist_dir=persist_dir) index = load_index_from_storage(storage_context) if object_node_mapping: return cls(index=index, object_node_mapping=object_node_mapping) else: # try to load object_node_mapping # assume SimpleObjectNodeMapping for simplicity as its only subclass # that supports this method try: object_node_mapping = SimpleObjectNodeMapping.from_persist_dir( persist_dir=persist_dir ) except Exception as err: raise Exception( "Unable to load from persist dir. The object_node_mapping cannot be loaded." ) from err else: return cls(index=index, object_node_mapping=object_node_mapping)
[ "llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys", "llama_index.legacy.indices.load_index_from_storage", "llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys", "llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects", "llama_index.legacy.storage.storage_context.StorageContext.from_defaults", "llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable" ]
[((925, 938), 'typing.TypeVar', 'TypeVar', (['"""OT"""'], {}), "('OT')\n", (932, 938), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n'), ((2060, 2096), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Retriever."""'}), "(..., description='Retriever.')\n", (2065, 2096), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2549, 2596), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['input']"], {}), "(input['input'])\n", (2580, 2596), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3083, 3113), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'input'}"], {}), "({'input'})\n", (3102, 3113), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3212, 3244), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (3232, 3244), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((5600, 5653), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (5628, 5653), False, 'from llama_index.legacy.storage.storage_context import DEFAULT_PERSIST_DIR, StorageContext\n'), ((5670, 5710), 'llama_index.legacy.indices.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (5693, 5710), False, 'from llama_index.legacy.indices import load_index_from_storage\n'), ((3816, 3861), 'llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects', 'SimpleObjectNodeMapping.from_objects', (['objects'], {}), '(objects)\n', (3852, 3861), False, 'from llama_index.legacy.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n'), ((4972, 5133), 'warnings.warn', 'warnings.warn', (['"""Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex"""'], {'stacklevel': '(2)'}), "(\n 'Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex'\n , stacklevel=2)\n", (4985, 5133), False, 'import warnings\n'), ((6056, 6121), 'llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir', 'SimpleObjectNodeMapping.from_persist_dir', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (6096, 6121), False, 'from llama_index.legacy.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n')]
"""Base object types.""" import pickle import warnings from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks.base import CallbackManager from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.core.query_pipeline.query_component import ( ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable, ) from llama_index.legacy.indices.base import BaseIndex from llama_index.legacy.indices.vector_store.base import VectorStoreIndex from llama_index.legacy.objects.base_node_mapping import ( DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping, ) from llama_index.legacy.schema import QueryType from llama_index.legacy.storage.storage_context import ( DEFAULT_PERSIST_DIR, StorageContext, ) OT = TypeVar("OT") class ObjectRetriever(ChainableMixin, Generic[OT]): """Object retriever.""" def __init__( self, retriever: BaseRetriever, object_node_mapping: BaseObjectNodeMapping[OT] ): self._retriever = retriever self._object_node_mapping = object_node_mapping @property def retriever(self) -> BaseRetriever: """Retriever.""" return self._retriever def retrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = self._retriever.retrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] async def aretrieve(self, str_or_query_bundle: QueryType) -> List[OT]: nodes = await self._retriever.aretrieve(str_or_query_bundle) return [self._object_node_mapping.from_node(node.node) for node in nodes] def _as_query_component(self, **kwargs: Any) -> QueryComponent: """As query component.""" return ObjectRetrieverComponent(retriever=self) class ObjectRetrieverComponent(QueryComponent): """Object retriever component.""" retriever: ObjectRetriever = Field(..., description="Retriever.") class Config: arbitrary_types_allowed = True def set_callback_manager(self, callback_manager: CallbackManager) -> None: """Set callback manager.""" self.retriever.retriever.callback_manager = callback_manager def _validate_component_inputs(self, input: Dict[str, Any]) -> Dict[str, Any]: """Validate component inputs during run_component.""" # make sure input is a string input["input"] = validate_and_convert_stringable(input["input"]) return input def _run_component(self, **kwargs: Any) -> Any: """Run component.""" output = self.retriever.retrieve(kwargs["input"]) return {"output": output} async def _arun_component(self, **kwargs: Any) -> Any: """Run component (async).""" output = await self.retriever.aretrieve(kwargs["input"]) return {"output": output} @property def input_keys(self) -> InputKeys: """Input keys.""" return InputKeys.from_keys({"input"}) @property def output_keys(self) -> OutputKeys: """Output keys.""" return OutputKeys.from_keys({"output"}) class ObjectIndex(Generic[OT]): """Object index.""" def __init__( self, index: BaseIndex, object_node_mapping: BaseObjectNodeMapping ) -> None: self._index = index self._object_node_mapping = object_node_mapping @classmethod def from_objects( cls, objects: Sequence[OT], object_mapping: Optional[BaseObjectNodeMapping] = None, index_cls: Type[BaseIndex] = VectorStoreIndex, **index_kwargs: Any, ) -> "ObjectIndex": if object_mapping is None: object_mapping = SimpleObjectNodeMapping.from_objects(objects) nodes = object_mapping.to_nodes(objects) index = index_cls(nodes, **index_kwargs) return cls(index, object_mapping) def insert_object(self, obj: Any) -> None: self._object_node_mapping.add_object(obj) node = self._object_node_mapping.to_node(obj) self._index.insert_nodes([node]) def as_retriever(self, **kwargs: Any) -> ObjectRetriever: return ObjectRetriever( retriever=self._index.as_retriever(**kwargs), object_node_mapping=self._object_node_mapping, ) def as_node_retriever(self, **kwargs: Any) -> BaseRetriever: return self._index.as_retriever(**kwargs) def persist( self, persist_dir: str = DEFAULT_PERSIST_DIR, obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME, ) -> None: # try to persist object node mapping try: self._object_node_mapping.persist( persist_dir=persist_dir, obj_node_mapping_fname=obj_node_mapping_fname ) except (NotImplementedError, pickle.PickleError) as err: warnings.warn( ( "Unable to persist ObjectNodeMapping. You will need to " "reconstruct the same object node mapping to build this ObjectIndex" ), stacklevel=2, ) self._index._storage_context.persist(persist_dir=persist_dir) @classmethod def from_persist_dir( cls, persist_dir: str = DEFAULT_PERSIST_DIR, object_node_mapping: Optional[BaseObjectNodeMapping] = None, ) -> "ObjectIndex": from llama_index.legacy.indices import load_index_from_storage storage_context = StorageContext.from_defaults(persist_dir=persist_dir) index = load_index_from_storage(storage_context) if object_node_mapping: return cls(index=index, object_node_mapping=object_node_mapping) else: # try to load object_node_mapping # assume SimpleObjectNodeMapping for simplicity as its only subclass # that supports this method try: object_node_mapping = SimpleObjectNodeMapping.from_persist_dir( persist_dir=persist_dir ) except Exception as err: raise Exception( "Unable to load from persist dir. The object_node_mapping cannot be loaded." ) from err else: return cls(index=index, object_node_mapping=object_node_mapping)
[ "llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys", "llama_index.legacy.indices.load_index_from_storage", "llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys", "llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects", "llama_index.legacy.storage.storage_context.StorageContext.from_defaults", "llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable" ]
[((925, 938), 'typing.TypeVar', 'TypeVar', (['"""OT"""'], {}), "('OT')\n", (932, 938), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar\n'), ((2060, 2096), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Retriever."""'}), "(..., description='Retriever.')\n", (2065, 2096), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2549, 2596), 'llama_index.legacy.core.query_pipeline.query_component.validate_and_convert_stringable', 'validate_and_convert_stringable', (["input['input']"], {}), "(input['input'])\n", (2580, 2596), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3083, 3113), 'llama_index.legacy.core.query_pipeline.query_component.InputKeys.from_keys', 'InputKeys.from_keys', (["{'input'}"], {}), "({'input'})\n", (3102, 3113), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((3212, 3244), 'llama_index.legacy.core.query_pipeline.query_component.OutputKeys.from_keys', 'OutputKeys.from_keys', (["{'output'}"], {}), "({'output'})\n", (3232, 3244), False, 'from llama_index.legacy.core.query_pipeline.query_component import ChainableMixin, InputKeys, OutputKeys, QueryComponent, validate_and_convert_stringable\n'), ((5600, 5653), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (5628, 5653), False, 'from llama_index.legacy.storage.storage_context import DEFAULT_PERSIST_DIR, StorageContext\n'), ((5670, 5710), 'llama_index.legacy.indices.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (5693, 5710), False, 'from llama_index.legacy.indices import load_index_from_storage\n'), ((3816, 3861), 'llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_objects', 'SimpleObjectNodeMapping.from_objects', (['objects'], {}), '(objects)\n', (3852, 3861), False, 'from llama_index.legacy.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n'), ((4972, 5133), 'warnings.warn', 'warnings.warn', (['"""Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex"""'], {'stacklevel': '(2)'}), "(\n 'Unable to persist ObjectNodeMapping. You will need to reconstruct the same object node mapping to build this ObjectIndex'\n , stacklevel=2)\n", (4985, 5133), False, 'import warnings\n'), ((6056, 6121), 'llama_index.legacy.objects.base_node_mapping.SimpleObjectNodeMapping.from_persist_dir', 'SimpleObjectNodeMapping.from_persist_dir', ([], {'persist_dir': 'persist_dir'}), '(persist_dir=persist_dir)\n', (6096, 6121), False, 'from llama_index.legacy.objects.base_node_mapping import DEFAULT_PERSIST_FNAME, BaseObjectNodeMapping, SimpleObjectNodeMapping\n')]
"""Base reader class.""" from abc import ABC from typing import TYPE_CHECKING, Any, Dict, Iterable, List if TYPE_CHECKING: from llama_index.legacy.bridge.langchain import Document as LCDocument from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.schema import BaseComponent, Document class BaseReader(ABC): """Utilities for loading data from a directory.""" def lazy_load_data(self, *args: Any, **load_kwargs: Any) -> Iterable[Document]: """Load data from the input directory lazily.""" raise NotImplementedError( f"{self.__class__.__name__} does not provide lazy_load_data method currently" ) def load_data(self, *args: Any, **load_kwargs: Any) -> List[Document]: """Load data from the input directory.""" return list(self.lazy_load_data(*args, **load_kwargs)) def load_langchain_documents(self, **load_kwargs: Any) -> List["LCDocument"]: """Load data in LangChain document format.""" docs = self.load_data(**load_kwargs) return [d.to_langchain_format() for d in docs] class BasePydanticReader(BaseReader, BaseComponent): """Serialiable Data Loader with Pydatnic.""" is_remote: bool = Field( default=False, description="Whether the data is loaded from a remote API or a local file.", ) class Config: arbitrary_types_allowed = True class ReaderConfig(BaseComponent): """Represents a reader and it's input arguments.""" reader: BasePydanticReader = Field(..., description="Reader to use.") reader_args: List[Any] = Field(default_factory=list, description="Reader args.") reader_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Reader kwargs." ) class Config: arbitrary_types_allowed = True @classmethod def class_name(cls) -> str: """Get the name identifier of the class.""" return "ReaderConfig" def to_dict(self, **kwargs: Any) -> Dict[str, Any]: """Convert the class to a dictionary.""" return { "loader": self.reader.to_dict(**kwargs), "reader_args": self.reader_args, "reader_kwargs": self.reader_kwargs, "class_name": self.class_name(), } def read(self) -> List[Document]: """Call the loader with the given arguments.""" return self.reader.load_data(*self.reader_args, **self.reader_kwargs)
[ "llama_index.legacy.bridge.pydantic.Field" ]
[((1225, 1327), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether the data is loaded from a remote API or a local file."""'}), "(default=False, description=\n 'Whether the data is loaded from a remote API or a local file.')\n", (1230, 1327), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1531, 1571), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Reader to use."""'}), "(..., description='Reader to use.')\n", (1536, 1571), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1601, 1656), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'list', 'description': '"""Reader args."""'}), "(default_factory=list, description='Reader args.')\n", (1606, 1656), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1693, 1750), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Reader kwargs."""'}), "(default_factory=dict, description='Reader kwargs.')\n", (1698, 1750), False, 'from llama_index.legacy.bridge.pydantic import Field\n')]
"""Base reader class.""" from abc import ABC from typing import TYPE_CHECKING, Any, Dict, Iterable, List if TYPE_CHECKING: from llama_index.legacy.bridge.langchain import Document as LCDocument from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.schema import BaseComponent, Document class BaseReader(ABC): """Utilities for loading data from a directory.""" def lazy_load_data(self, *args: Any, **load_kwargs: Any) -> Iterable[Document]: """Load data from the input directory lazily.""" raise NotImplementedError( f"{self.__class__.__name__} does not provide lazy_load_data method currently" ) def load_data(self, *args: Any, **load_kwargs: Any) -> List[Document]: """Load data from the input directory.""" return list(self.lazy_load_data(*args, **load_kwargs)) def load_langchain_documents(self, **load_kwargs: Any) -> List["LCDocument"]: """Load data in LangChain document format.""" docs = self.load_data(**load_kwargs) return [d.to_langchain_format() for d in docs] class BasePydanticReader(BaseReader, BaseComponent): """Serialiable Data Loader with Pydatnic.""" is_remote: bool = Field( default=False, description="Whether the data is loaded from a remote API or a local file.", ) class Config: arbitrary_types_allowed = True class ReaderConfig(BaseComponent): """Represents a reader and it's input arguments.""" reader: BasePydanticReader = Field(..., description="Reader to use.") reader_args: List[Any] = Field(default_factory=list, description="Reader args.") reader_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Reader kwargs." ) class Config: arbitrary_types_allowed = True @classmethod def class_name(cls) -> str: """Get the name identifier of the class.""" return "ReaderConfig" def to_dict(self, **kwargs: Any) -> Dict[str, Any]: """Convert the class to a dictionary.""" return { "loader": self.reader.to_dict(**kwargs), "reader_args": self.reader_args, "reader_kwargs": self.reader_kwargs, "class_name": self.class_name(), } def read(self) -> List[Document]: """Call the loader with the given arguments.""" return self.reader.load_data(*self.reader_args, **self.reader_kwargs)
[ "llama_index.legacy.bridge.pydantic.Field" ]
[((1225, 1327), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether the data is loaded from a remote API or a local file."""'}), "(default=False, description=\n 'Whether the data is loaded from a remote API or a local file.')\n", (1230, 1327), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1531, 1571), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""Reader to use."""'}), "(..., description='Reader to use.')\n", (1536, 1571), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1601, 1656), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'list', 'description': '"""Reader args."""'}), "(default_factory=list, description='Reader args.')\n", (1606, 1656), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1693, 1750), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Reader kwargs."""'}), "(default_factory=dict, description='Reader kwargs.')\n", (1698, 1750), False, 'from llama_index.legacy.bridge.pydantic import Field\n')]
""" Portkey integration with Llama_index for enhanced monitoring. """ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.llms.generic_utils import ( chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.portkey_utils import ( IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode if TYPE_CHECKING: from portkey import ( LLMOptions, Modes, ModesLiteral, PortkeyResponse, ) DEFAULT_PORTKEY_MODEL = "gpt-3.5-turbo" class Portkey(CustomLLM): """_summary_. Args: LLM (_type_): _description_ """ mode: Optional[Union["Modes", "ModesLiteral"]] = Field( description="The mode for using the Portkey integration" ) model: Optional[str] = Field(default=DEFAULT_PORTKEY_MODEL) llm: "LLMOptions" = Field(description="LLM parameter", default_factory=dict) llms: List["LLMOptions"] = Field(description="LLM parameters", default_factory=list) _client: Any = PrivateAttr() def __init__( self, *, mode: Union["Modes", "ModesLiteral"], api_key: Optional[str] = None, base_url: Optional[str] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: """ Initialize a Portkey instance. Args: mode (Optional[Modes]): The mode for using the Portkey integration (default: Modes.SINGLE). api_key (Optional[str]): The API key to authenticate with Portkey. base_url (Optional[str]): The Base url to the self hosted rubeus \ (the opensource version of portkey) or any other self hosted server. """ try: import portkey except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc super().__init__( base_url=base_url, api_key=api_key, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) if api_key is not None: portkey.api_key = api_key if base_url is not None: portkey.base_url = base_url portkey.mode = mode self._client = portkey self.model = None self.mode = mode @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return generate_llm_metadata(self.llms[0]) def add_llms( self, llm_params: Union["LLMOptions", List["LLMOptions"]] ) -> "Portkey": """ Adds the specified LLM parameters to the list of LLMs. This may be used for fallbacks or load-balancing as specified in the mode. Args: llm_params (Union[LLMOptions, List[LLMOptions]]): A single LLM parameter \ set or a list of LLM parameter sets. Each set should be an instance of \ LLMOptions with the specified attributes. > provider: Optional[ProviderTypes] > model: str > temperature: float > max_tokens: Optional[int] > max_retries: int > trace_id: Optional[str] > cache_status: Optional[CacheType] > cache: Optional[bool] > metadata: Dict[str, Any] > weight: Optional[float] > **kwargs : Other additional parameters that are supported by \ LLMOptions in portkey-ai NOTE: User may choose to pass additional params as well. Returns: self """ try: from portkey import LLMOptions except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc if isinstance(llm_params, LLMOptions): llm_params = [llm_params] self.llms.extend(llm_params) if self.model is None: self.model = self.llms[0].model return self @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint for LLM.""" if self._is_chat_model: complete_fn = chat_to_completion_decorator(self._chat) else: complete_fn = self._complete return complete_fn(prompt, **kwargs) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if self._is_chat_model: chat_fn = self._chat else: chat_fn = completion_to_chat_decorator(self._complete) return chat_fn(messages, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Completion endpoint for LLM.""" if self._is_chat_model: complete_fn = stream_chat_to_completion_decorator(self._stream_chat) else: complete_fn = self._stream_complete return complete_fn(prompt, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if self._is_chat_model: stream_chat_fn = self._stream_chat else: stream_chat_fn = stream_completion_to_chat_decorator(self._stream_complete) return stream_chat_fn(messages, **kwargs) def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: try: from portkey import Config, Message except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc _messages = cast( List[Message], [{"role": i.role.value, "content": i.content} for i in messages], ) config = Config(llms=self.llms) response = self._client.ChatCompletions.create( messages=_messages, config=config ) self.llm = self._get_llm(response) message = response.choices[0].message return ChatResponse(message=message, raw=response) def _complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: try: from portkey import Config except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc config = Config(llms=self.llms) response = self._client.Completions.create(prompt=prompt, config=config) text = response.choices[0].text return CompletionResponse(text=text, raw=response) def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: try: from portkey import Config, Message except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc _messages = cast( List[Message], [{"role": i.role.value, "content": i.content} for i in messages], ) config = Config(llms=self.llms) response = self._client.ChatCompletions.create( messages=_messages, config=config, stream=True, **kwargs ) def gen() -> ChatResponseGen: content = "" function_call: Optional[dict] = {} for resp in response: if resp.choices is None: continue delta = resp.choices[0].delta role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta # ensure we do not add a blank function call if ( function_call and function_call.get("function_name", "") is None ): del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=resp, ) return gen() def _stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen: try: from portkey import Config except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc config = Config(llms=self.llms) response = self._client.Completions.create( prompt=prompt, config=config, stream=True, **kwargs ) def gen() -> CompletionResponseGen: text = "" for resp in response: delta = resp.choices[0].text or "" text += delta yield CompletionResponse( delta=delta, text=text, raw=resp, ) return gen() @property def _is_chat_model(self) -> bool: """Check if a given model is a chat-based language model. Returns: bool: True if the provided model is a chat-based language model, False otherwise. """ return is_chat_model(self.model or "") def _get_llm(self, response: "PortkeyResponse") -> "LLMOptions": return get_llm(response, self.llms)
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatResponse", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.llms.portkey_utils.is_chat_model", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.portkey_utils.generate_llm_metadata", "llama_index.legacy.llms.portkey_utils.get_llm" ]
[((1284, 1347), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The mode for using the Portkey integration"""'}), "(description='The mode for using the Portkey integration')\n", (1289, 1347), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1390, 1426), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_PORTKEY_MODEL'}), '(default=DEFAULT_PORTKEY_MODEL)\n', (1395, 1426), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1451, 1507), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""LLM parameter"""', 'default_factory': 'dict'}), "(description='LLM parameter', default_factory=dict)\n", (1456, 1507), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1540, 1597), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""LLM parameters"""', 'default_factory': 'list'}), "(description='LLM parameters', default_factory=list)\n", (1545, 1597), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1618, 1631), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1629, 1631), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5009, 5034), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5032, 5034), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5396, 5415), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5413, 5415), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5695, 5720), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5718, 5720), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6113, 6132), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6130, 6132), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3423, 3458), 'llama_index.legacy.llms.portkey_utils.generate_llm_metadata', 'generate_llm_metadata', (['self.llms[0]'], {}), '(self.llms[0])\n', (3444, 3458), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((6735, 6824), 'typing.cast', 'cast', (['List[Message]', "[{'role': i.role.value, 'content': i.content} for i in messages]"], {}), "(List[Message], [{'role': i.role.value, 'content': i.content} for i in\n messages])\n", (6739, 6824), False, 'from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast\n'), ((6873, 6895), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (6879, 6895), False, 'from portkey import Config\n'), ((7113, 7156), 'llama_index.legacy.core.llms.types.ChatResponse', 'ChatResponse', ([], {'message': 'message', 'raw': 'response'}), '(message=message, raw=response)\n', (7125, 7156), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((7399, 7421), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (7405, 7421), False, 'from portkey import Config\n'), ((7558, 7601), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'text', 'raw': 'response'}), '(text=text, raw=response)\n', (7576, 7601), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((7889, 7978), 'typing.cast', 'cast', (['List[Message]', "[{'role': i.role.value, 'content': i.content} for i in messages]"], {}), "(List[Message], [{'role': i.role.value, 'content': i.content} for i in\n messages])\n", (7893, 7978), False, 'from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast\n'), ((8027, 8049), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (8033, 8049), False, 'from portkey import Config\n'), ((10014, 10036), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (10020, 10036), False, 'from portkey import Config\n'), ((10791, 10822), 'llama_index.legacy.llms.portkey_utils.is_chat_model', 'is_chat_model', (["(self.model or '')"], {}), "(self.model or '')\n", (10804, 10822), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((10908, 10936), 'llama_index.legacy.llms.portkey_utils.get_llm', 'get_llm', (['response', 'self.llms'], {}), '(response, self.llms)\n', (10915, 10936), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((5249, 5289), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self._chat'], {}), '(self._chat)\n', (5277, 5289), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5601, 5645), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self._complete'], {}), '(self._complete)\n', (5629, 5645), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5945, 5999), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self._stream_chat'], {}), '(self._stream_chat)\n', (5980, 5999), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((6363, 6421), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self._stream_complete'], {}), '(self._stream_complete)\n', (6398, 6421), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((10367, 10419), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'delta': 'delta', 'text': 'text', 'raw': 'resp'}), '(delta=delta, text=text, raw=resp)\n', (10385, 10419), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((9478, 9554), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (9489, 9554), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n')]
""" Portkey integration with Llama_index for enhanced monitoring. """ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.llms.generic_utils import ( chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.portkey_utils import ( IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode if TYPE_CHECKING: from portkey import ( LLMOptions, Modes, ModesLiteral, PortkeyResponse, ) DEFAULT_PORTKEY_MODEL = "gpt-3.5-turbo" class Portkey(CustomLLM): """_summary_. Args: LLM (_type_): _description_ """ mode: Optional[Union["Modes", "ModesLiteral"]] = Field( description="The mode for using the Portkey integration" ) model: Optional[str] = Field(default=DEFAULT_PORTKEY_MODEL) llm: "LLMOptions" = Field(description="LLM parameter", default_factory=dict) llms: List["LLMOptions"] = Field(description="LLM parameters", default_factory=list) _client: Any = PrivateAttr() def __init__( self, *, mode: Union["Modes", "ModesLiteral"], api_key: Optional[str] = None, base_url: Optional[str] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: """ Initialize a Portkey instance. Args: mode (Optional[Modes]): The mode for using the Portkey integration (default: Modes.SINGLE). api_key (Optional[str]): The API key to authenticate with Portkey. base_url (Optional[str]): The Base url to the self hosted rubeus \ (the opensource version of portkey) or any other self hosted server. """ try: import portkey except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc super().__init__( base_url=base_url, api_key=api_key, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) if api_key is not None: portkey.api_key = api_key if base_url is not None: portkey.base_url = base_url portkey.mode = mode self._client = portkey self.model = None self.mode = mode @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return generate_llm_metadata(self.llms[0]) def add_llms( self, llm_params: Union["LLMOptions", List["LLMOptions"]] ) -> "Portkey": """ Adds the specified LLM parameters to the list of LLMs. This may be used for fallbacks or load-balancing as specified in the mode. Args: llm_params (Union[LLMOptions, List[LLMOptions]]): A single LLM parameter \ set or a list of LLM parameter sets. Each set should be an instance of \ LLMOptions with the specified attributes. > provider: Optional[ProviderTypes] > model: str > temperature: float > max_tokens: Optional[int] > max_retries: int > trace_id: Optional[str] > cache_status: Optional[CacheType] > cache: Optional[bool] > metadata: Dict[str, Any] > weight: Optional[float] > **kwargs : Other additional parameters that are supported by \ LLMOptions in portkey-ai NOTE: User may choose to pass additional params as well. Returns: self """ try: from portkey import LLMOptions except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc if isinstance(llm_params, LLMOptions): llm_params = [llm_params] self.llms.extend(llm_params) if self.model is None: self.model = self.llms[0].model return self @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint for LLM.""" if self._is_chat_model: complete_fn = chat_to_completion_decorator(self._chat) else: complete_fn = self._complete return complete_fn(prompt, **kwargs) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if self._is_chat_model: chat_fn = self._chat else: chat_fn = completion_to_chat_decorator(self._complete) return chat_fn(messages, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Completion endpoint for LLM.""" if self._is_chat_model: complete_fn = stream_chat_to_completion_decorator(self._stream_chat) else: complete_fn = self._stream_complete return complete_fn(prompt, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if self._is_chat_model: stream_chat_fn = self._stream_chat else: stream_chat_fn = stream_completion_to_chat_decorator(self._stream_complete) return stream_chat_fn(messages, **kwargs) def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: try: from portkey import Config, Message except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc _messages = cast( List[Message], [{"role": i.role.value, "content": i.content} for i in messages], ) config = Config(llms=self.llms) response = self._client.ChatCompletions.create( messages=_messages, config=config ) self.llm = self._get_llm(response) message = response.choices[0].message return ChatResponse(message=message, raw=response) def _complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: try: from portkey import Config except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc config = Config(llms=self.llms) response = self._client.Completions.create(prompt=prompt, config=config) text = response.choices[0].text return CompletionResponse(text=text, raw=response) def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: try: from portkey import Config, Message except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc _messages = cast( List[Message], [{"role": i.role.value, "content": i.content} for i in messages], ) config = Config(llms=self.llms) response = self._client.ChatCompletions.create( messages=_messages, config=config, stream=True, **kwargs ) def gen() -> ChatResponseGen: content = "" function_call: Optional[dict] = {} for resp in response: if resp.choices is None: continue delta = resp.choices[0].delta role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta # ensure we do not add a blank function call if ( function_call and function_call.get("function_name", "") is None ): del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=resp, ) return gen() def _stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen: try: from portkey import Config except ImportError as exc: raise ImportError(IMPORT_ERROR_MESSAGE) from exc config = Config(llms=self.llms) response = self._client.Completions.create( prompt=prompt, config=config, stream=True, **kwargs ) def gen() -> CompletionResponseGen: text = "" for resp in response: delta = resp.choices[0].text or "" text += delta yield CompletionResponse( delta=delta, text=text, raw=resp, ) return gen() @property def _is_chat_model(self) -> bool: """Check if a given model is a chat-based language model. Returns: bool: True if the provided model is a chat-based language model, False otherwise. """ return is_chat_model(self.model or "") def _get_llm(self, response: "PortkeyResponse") -> "LLMOptions": return get_llm(response, self.llms)
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatResponse", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.llms.portkey_utils.is_chat_model", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.portkey_utils.generate_llm_metadata", "llama_index.legacy.llms.portkey_utils.get_llm" ]
[((1284, 1347), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The mode for using the Portkey integration"""'}), "(description='The mode for using the Portkey integration')\n", (1289, 1347), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1390, 1426), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_PORTKEY_MODEL'}), '(default=DEFAULT_PORTKEY_MODEL)\n', (1395, 1426), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1451, 1507), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""LLM parameter"""', 'default_factory': 'dict'}), "(description='LLM parameter', default_factory=dict)\n", (1456, 1507), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1540, 1597), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""LLM parameters"""', 'default_factory': 'list'}), "(description='LLM parameters', default_factory=list)\n", (1545, 1597), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1618, 1631), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1629, 1631), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5009, 5034), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5032, 5034), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5396, 5415), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5413, 5415), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5695, 5720), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5718, 5720), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6113, 6132), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6130, 6132), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3423, 3458), 'llama_index.legacy.llms.portkey_utils.generate_llm_metadata', 'generate_llm_metadata', (['self.llms[0]'], {}), '(self.llms[0])\n', (3444, 3458), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((6735, 6824), 'typing.cast', 'cast', (['List[Message]', "[{'role': i.role.value, 'content': i.content} for i in messages]"], {}), "(List[Message], [{'role': i.role.value, 'content': i.content} for i in\n messages])\n", (6739, 6824), False, 'from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast\n'), ((6873, 6895), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (6879, 6895), False, 'from portkey import Config\n'), ((7113, 7156), 'llama_index.legacy.core.llms.types.ChatResponse', 'ChatResponse', ([], {'message': 'message', 'raw': 'response'}), '(message=message, raw=response)\n', (7125, 7156), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((7399, 7421), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (7405, 7421), False, 'from portkey import Config\n'), ((7558, 7601), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'text', 'raw': 'response'}), '(text=text, raw=response)\n', (7576, 7601), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((7889, 7978), 'typing.cast', 'cast', (['List[Message]', "[{'role': i.role.value, 'content': i.content} for i in messages]"], {}), "(List[Message], [{'role': i.role.value, 'content': i.content} for i in\n messages])\n", (7893, 7978), False, 'from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence, Union, cast\n'), ((8027, 8049), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (8033, 8049), False, 'from portkey import Config\n'), ((10014, 10036), 'portkey.Config', 'Config', ([], {'llms': 'self.llms'}), '(llms=self.llms)\n', (10020, 10036), False, 'from portkey import Config\n'), ((10791, 10822), 'llama_index.legacy.llms.portkey_utils.is_chat_model', 'is_chat_model', (["(self.model or '')"], {}), "(self.model or '')\n", (10804, 10822), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((10908, 10936), 'llama_index.legacy.llms.portkey_utils.get_llm', 'get_llm', (['response', 'self.llms'], {}), '(response, self.llms)\n', (10915, 10936), False, 'from llama_index.legacy.llms.portkey_utils import IMPORT_ERROR_MESSAGE, generate_llm_metadata, get_llm, is_chat_model\n'), ((5249, 5289), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self._chat'], {}), '(self._chat)\n', (5277, 5289), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5601, 5645), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self._complete'], {}), '(self._complete)\n', (5629, 5645), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5945, 5999), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self._stream_chat'], {}), '(self._stream_chat)\n', (5980, 5999), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((6363, 6421), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self._stream_complete'], {}), '(self._stream_complete)\n', (6398, 6421), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((10367, 10419), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'delta': 'delta', 'text': 'text', 'raw': 'resp'}), '(delta=delta, text=text, raw=resp)\n', (10385, 10419), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((9478, 9554), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (9489, 9554), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n')]
"""Query plan tool.""" from typing import Any, Dict, List, Optional from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.response_synthesizers import ( BaseSynthesizer, get_response_synthesizer, ) from llama_index.core.schema import NodeWithScore, TextNode from llama_index.core.tools.types import BaseTool, ToolMetadata, ToolOutput from llama_index.core.utils import print_text DEFAULT_NAME = "query_plan_tool" QUERYNODE_QUERY_STR_DESC = """\ Question we are asking. This is the query string that will be executed. \ """ QUERYNODE_TOOL_NAME_DESC = """\ Name of the tool to execute the `query_str`. \ Should NOT be specified if there are subquestions to be specified, in which \ case child_nodes should be nonempty instead.\ """ QUERYNODE_DEPENDENCIES_DESC = """\ List of sub-questions that need to be answered in order \ to answer the question given by `query_str`.\ Should be blank if there are no sub-questions to be specified, in which case \ `tool_name` is specified.\ """ class QueryNode(BaseModel): """Query node. A query node represents a query (query_str) that must be answered. It can either be answered by a tool (tool_name), or by a list of child nodes (child_nodes). The tool_name and child_nodes fields are mutually exclusive. """ # NOTE: inspired from https://github.com/jxnl/openai_function_call/pull/3/files id: int = Field(..., description="ID of the query node.") query_str: str = Field(..., description=QUERYNODE_QUERY_STR_DESC) tool_name: Optional[str] = Field( default=None, description="Name of the tool to execute the `query_str`." ) dependencies: List[int] = Field( default_factory=list, description=QUERYNODE_DEPENDENCIES_DESC ) class QueryPlan(BaseModel): """Query plan. Contains a list of QueryNode objects (which is a recursive object). Out of the list of QueryNode objects, one of them must be the root node. The root node is the one that isn't a dependency of any other node. """ nodes: List[QueryNode] = Field( ..., description="The original question we are asking.", ) DEFAULT_DESCRIPTION_PREFIX = """\ This is a query plan tool that takes in a list of tools and executes a \ query plan over these tools to answer a query. The query plan is a DAG of query nodes. Given a list of tool names and the query plan schema, you \ can choose to generate a query plan to answer a question. The tool names and descriptions are as follows: """ class QueryPlanTool(BaseTool): """Query plan tool. A tool that takes in a list of tools and executes a query plan. """ def __init__( self, query_engine_tools: List[BaseTool], response_synthesizer: BaseSynthesizer, name: str, description_prefix: str, ) -> None: """Initialize.""" self._query_tools_dict = {t.metadata.name: t for t in query_engine_tools} self._response_synthesizer = response_synthesizer self._name = name self._description_prefix = description_prefix @classmethod def from_defaults( cls, query_engine_tools: List[BaseTool], response_synthesizer: Optional[BaseSynthesizer] = None, name: Optional[str] = None, description_prefix: Optional[str] = None, ) -> "QueryPlanTool": """Initialize from defaults.""" name = name or DEFAULT_NAME description_prefix = description_prefix or DEFAULT_DESCRIPTION_PREFIX response_synthesizer = response_synthesizer or get_response_synthesizer() return cls( query_engine_tools=query_engine_tools, response_synthesizer=response_synthesizer, name=name, description_prefix=description_prefix, ) @property def metadata(self) -> ToolMetadata: """Metadata.""" tools_description = "\n\n".join( [ f"Tool Name: {tool.metadata.name}\n" + f"Tool Description: {tool.metadata.description} " for tool in self._query_tools_dict.values() ] ) # TODO: fill in description with query engine tools. description = f"""\ {self._description_prefix}\n\n {tools_description} """ return ToolMetadata(description, self._name, fn_schema=QueryPlan) def _execute_node( self, node: QueryNode, nodes_dict: Dict[int, QueryNode] ) -> ToolOutput: """Execute node.""" print_text(f"Executing node {node.json()}\n", color="blue") if len(node.dependencies) > 0: print_text( f"Executing {len(node.dependencies)} child nodes\n", color="pink" ) child_query_nodes: List[QueryNode] = [ nodes_dict[dep] for dep in node.dependencies ] # execute the child nodes first child_responses: List[ToolOutput] = [ self._execute_node(child, nodes_dict) for child in child_query_nodes ] # form the child Node/NodeWithScore objects child_nodes = [] for child_query_node, child_response in zip( child_query_nodes, child_responses ): node_text = ( f"Query: {child_query_node.query_str}\n" f"Response: {child_response!s}\n" ) child_node = TextNode(text=node_text) child_nodes.append(child_node) # use response synthesizer to combine results child_nodes_with_scores = [ NodeWithScore(node=n, score=1.0) for n in child_nodes ] response_obj = self._response_synthesizer.synthesize( query=node.query_str, nodes=child_nodes_with_scores, ) response = ToolOutput( content=str(response_obj), tool_name=node.query_str, raw_input={"query": node.query_str}, raw_output=response_obj, ) else: # this is a leaf request, execute the query string using the specified tool tool = self._query_tools_dict[node.tool_name] print_text(f"Selected Tool: {tool.metadata}\n", color="pink") response = tool(node.query_str) print_text( "Executed query, got response.\n" f"Query: {node.query_str}\n" f"Response: {response!s}\n", color="blue", ) return response def _find_root_nodes(self, nodes_dict: Dict[int, QueryNode]) -> List[QueryNode]: """Find root node.""" # the root node is the one that isn't a dependency of any other node node_counts = {node_id: 0 for node_id in nodes_dict} for node in nodes_dict.values(): for dep in node.dependencies: node_counts[dep] += 1 root_node_ids = [ node_id for node_id, count in node_counts.items() if count == 0 ] return [nodes_dict[node_id] for node_id in root_node_ids] def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput: """Call.""" # the kwargs represented as a JSON object # should be a QueryPlan object query_plan = QueryPlan(**kwargs) nodes_dict = {node.id: node for node in query_plan.nodes} root_nodes = self._find_root_nodes(nodes_dict) if len(root_nodes) > 1: raise ValueError("Query plan should have exactly one root node.") return self._execute_node(root_nodes[0], nodes_dict)
[ "llama_index.core.schema.TextNode", "llama_index.core.bridge.pydantic.Field", "llama_index.core.tools.types.ToolMetadata", "llama_index.core.schema.NodeWithScore", "llama_index.core.response_synthesizers.get_response_synthesizer", "llama_index.core.utils.print_text" ]
[((1418, 1465), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""ID of the query node."""'}), "(..., description='ID of the query node.')\n", (1423, 1465), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1487, 1535), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': 'QUERYNODE_QUERY_STR_DESC'}), '(..., description=QUERYNODE_QUERY_STR_DESC)\n', (1492, 1535), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1567, 1646), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Name of the tool to execute the `query_str`."""'}), "(default=None, description='Name of the tool to execute the `query_str`.')\n", (1572, 1646), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1691, 1759), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'list', 'description': 'QUERYNODE_DEPENDENCIES_DESC'}), '(default_factory=list, description=QUERYNODE_DEPENDENCIES_DESC)\n', (1696, 1759), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((2084, 2146), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""The original question we are asking."""'}), "(..., description='The original question we are asking.')\n", (2089, 2146), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((4353, 4411), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', (['description', 'self._name'], {'fn_schema': 'QueryPlan'}), '(description, self._name, fn_schema=QueryPlan)\n', (4365, 4411), False, 'from llama_index.core.tools.types import BaseTool, ToolMetadata, ToolOutput\n'), ((6429, 6549), 'llama_index.core.utils.print_text', 'print_text', (['f"""Executed query, got response.\nQuery: {node.query_str}\nResponse: {response!s}\n"""'], {'color': '"""blue"""'}), '(\n f"""Executed query, got response.\nQuery: {node.query_str}\nResponse: {response!s}\n"""\n , color=\'blue\')\n', (6439, 6549), False, 'from llama_index.core.utils import print_text\n'), ((3593, 3619), 'llama_index.core.response_synthesizers.get_response_synthesizer', 'get_response_synthesizer', ([], {}), '()\n', (3617, 3619), False, 'from llama_index.core.response_synthesizers import BaseSynthesizer, get_response_synthesizer\n'), ((6315, 6376), 'llama_index.core.utils.print_text', 'print_text', (['f"""Selected Tool: {tool.metadata}\n"""'], {'color': '"""pink"""'}), "(f'Selected Tool: {tool.metadata}\\n', color='pink')\n", (6325, 6376), False, 'from llama_index.core.utils import print_text\n'), ((5495, 5519), 'llama_index.core.schema.TextNode', 'TextNode', ([], {'text': 'node_text'}), '(text=node_text)\n', (5503, 5519), False, 'from llama_index.core.schema import NodeWithScore, TextNode\n'), ((5681, 5713), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'n', 'score': '(1.0)'}), '(node=n, score=1.0)\n', (5694, 5713), False, 'from llama_index.core.schema import NodeWithScore, TextNode\n')]
"""Query plan tool.""" from typing import Any, Dict, List, Optional from llama_index.core.bridge.pydantic import BaseModel, Field from llama_index.core.response_synthesizers import ( BaseSynthesizer, get_response_synthesizer, ) from llama_index.core.schema import NodeWithScore, TextNode from llama_index.core.tools.types import BaseTool, ToolMetadata, ToolOutput from llama_index.core.utils import print_text DEFAULT_NAME = "query_plan_tool" QUERYNODE_QUERY_STR_DESC = """\ Question we are asking. This is the query string that will be executed. \ """ QUERYNODE_TOOL_NAME_DESC = """\ Name of the tool to execute the `query_str`. \ Should NOT be specified if there are subquestions to be specified, in which \ case child_nodes should be nonempty instead.\ """ QUERYNODE_DEPENDENCIES_DESC = """\ List of sub-questions that need to be answered in order \ to answer the question given by `query_str`.\ Should be blank if there are no sub-questions to be specified, in which case \ `tool_name` is specified.\ """ class QueryNode(BaseModel): """Query node. A query node represents a query (query_str) that must be answered. It can either be answered by a tool (tool_name), or by a list of child nodes (child_nodes). The tool_name and child_nodes fields are mutually exclusive. """ # NOTE: inspired from https://github.com/jxnl/openai_function_call/pull/3/files id: int = Field(..., description="ID of the query node.") query_str: str = Field(..., description=QUERYNODE_QUERY_STR_DESC) tool_name: Optional[str] = Field( default=None, description="Name of the tool to execute the `query_str`." ) dependencies: List[int] = Field( default_factory=list, description=QUERYNODE_DEPENDENCIES_DESC ) class QueryPlan(BaseModel): """Query plan. Contains a list of QueryNode objects (which is a recursive object). Out of the list of QueryNode objects, one of them must be the root node. The root node is the one that isn't a dependency of any other node. """ nodes: List[QueryNode] = Field( ..., description="The original question we are asking.", ) DEFAULT_DESCRIPTION_PREFIX = """\ This is a query plan tool that takes in a list of tools and executes a \ query plan over these tools to answer a query. The query plan is a DAG of query nodes. Given a list of tool names and the query plan schema, you \ can choose to generate a query plan to answer a question. The tool names and descriptions are as follows: """ class QueryPlanTool(BaseTool): """Query plan tool. A tool that takes in a list of tools and executes a query plan. """ def __init__( self, query_engine_tools: List[BaseTool], response_synthesizer: BaseSynthesizer, name: str, description_prefix: str, ) -> None: """Initialize.""" self._query_tools_dict = {t.metadata.name: t for t in query_engine_tools} self._response_synthesizer = response_synthesizer self._name = name self._description_prefix = description_prefix @classmethod def from_defaults( cls, query_engine_tools: List[BaseTool], response_synthesizer: Optional[BaseSynthesizer] = None, name: Optional[str] = None, description_prefix: Optional[str] = None, ) -> "QueryPlanTool": """Initialize from defaults.""" name = name or DEFAULT_NAME description_prefix = description_prefix or DEFAULT_DESCRIPTION_PREFIX response_synthesizer = response_synthesizer or get_response_synthesizer() return cls( query_engine_tools=query_engine_tools, response_synthesizer=response_synthesizer, name=name, description_prefix=description_prefix, ) @property def metadata(self) -> ToolMetadata: """Metadata.""" tools_description = "\n\n".join( [ f"Tool Name: {tool.metadata.name}\n" + f"Tool Description: {tool.metadata.description} " for tool in self._query_tools_dict.values() ] ) # TODO: fill in description with query engine tools. description = f"""\ {self._description_prefix}\n\n {tools_description} """ return ToolMetadata(description, self._name, fn_schema=QueryPlan) def _execute_node( self, node: QueryNode, nodes_dict: Dict[int, QueryNode] ) -> ToolOutput: """Execute node.""" print_text(f"Executing node {node.json()}\n", color="blue") if len(node.dependencies) > 0: print_text( f"Executing {len(node.dependencies)} child nodes\n", color="pink" ) child_query_nodes: List[QueryNode] = [ nodes_dict[dep] for dep in node.dependencies ] # execute the child nodes first child_responses: List[ToolOutput] = [ self._execute_node(child, nodes_dict) for child in child_query_nodes ] # form the child Node/NodeWithScore objects child_nodes = [] for child_query_node, child_response in zip( child_query_nodes, child_responses ): node_text = ( f"Query: {child_query_node.query_str}\n" f"Response: {child_response!s}\n" ) child_node = TextNode(text=node_text) child_nodes.append(child_node) # use response synthesizer to combine results child_nodes_with_scores = [ NodeWithScore(node=n, score=1.0) for n in child_nodes ] response_obj = self._response_synthesizer.synthesize( query=node.query_str, nodes=child_nodes_with_scores, ) response = ToolOutput( content=str(response_obj), tool_name=node.query_str, raw_input={"query": node.query_str}, raw_output=response_obj, ) else: # this is a leaf request, execute the query string using the specified tool tool = self._query_tools_dict[node.tool_name] print_text(f"Selected Tool: {tool.metadata}\n", color="pink") response = tool(node.query_str) print_text( "Executed query, got response.\n" f"Query: {node.query_str}\n" f"Response: {response!s}\n", color="blue", ) return response def _find_root_nodes(self, nodes_dict: Dict[int, QueryNode]) -> List[QueryNode]: """Find root node.""" # the root node is the one that isn't a dependency of any other node node_counts = {node_id: 0 for node_id in nodes_dict} for node in nodes_dict.values(): for dep in node.dependencies: node_counts[dep] += 1 root_node_ids = [ node_id for node_id, count in node_counts.items() if count == 0 ] return [nodes_dict[node_id] for node_id in root_node_ids] def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput: """Call.""" # the kwargs represented as a JSON object # should be a QueryPlan object query_plan = QueryPlan(**kwargs) nodes_dict = {node.id: node for node in query_plan.nodes} root_nodes = self._find_root_nodes(nodes_dict) if len(root_nodes) > 1: raise ValueError("Query plan should have exactly one root node.") return self._execute_node(root_nodes[0], nodes_dict)
[ "llama_index.core.schema.TextNode", "llama_index.core.bridge.pydantic.Field", "llama_index.core.tools.types.ToolMetadata", "llama_index.core.schema.NodeWithScore", "llama_index.core.response_synthesizers.get_response_synthesizer", "llama_index.core.utils.print_text" ]
[((1418, 1465), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""ID of the query node."""'}), "(..., description='ID of the query node.')\n", (1423, 1465), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1487, 1535), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': 'QUERYNODE_QUERY_STR_DESC'}), '(..., description=QUERYNODE_QUERY_STR_DESC)\n', (1492, 1535), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1567, 1646), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""Name of the tool to execute the `query_str`."""'}), "(default=None, description='Name of the tool to execute the `query_str`.')\n", (1572, 1646), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((1691, 1759), 'llama_index.core.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'list', 'description': 'QUERYNODE_DEPENDENCIES_DESC'}), '(default_factory=list, description=QUERYNODE_DEPENDENCIES_DESC)\n', (1696, 1759), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((2084, 2146), 'llama_index.core.bridge.pydantic.Field', 'Field', (['...'], {'description': '"""The original question we are asking."""'}), "(..., description='The original question we are asking.')\n", (2089, 2146), False, 'from llama_index.core.bridge.pydantic import BaseModel, Field\n'), ((4353, 4411), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', (['description', 'self._name'], {'fn_schema': 'QueryPlan'}), '(description, self._name, fn_schema=QueryPlan)\n', (4365, 4411), False, 'from llama_index.core.tools.types import BaseTool, ToolMetadata, ToolOutput\n'), ((6429, 6549), 'llama_index.core.utils.print_text', 'print_text', (['f"""Executed query, got response.\nQuery: {node.query_str}\nResponse: {response!s}\n"""'], {'color': '"""blue"""'}), '(\n f"""Executed query, got response.\nQuery: {node.query_str}\nResponse: {response!s}\n"""\n , color=\'blue\')\n', (6439, 6549), False, 'from llama_index.core.utils import print_text\n'), ((3593, 3619), 'llama_index.core.response_synthesizers.get_response_synthesizer', 'get_response_synthesizer', ([], {}), '()\n', (3617, 3619), False, 'from llama_index.core.response_synthesizers import BaseSynthesizer, get_response_synthesizer\n'), ((6315, 6376), 'llama_index.core.utils.print_text', 'print_text', (['f"""Selected Tool: {tool.metadata}\n"""'], {'color': '"""pink"""'}), "(f'Selected Tool: {tool.metadata}\\n', color='pink')\n", (6325, 6376), False, 'from llama_index.core.utils import print_text\n'), ((5495, 5519), 'llama_index.core.schema.TextNode', 'TextNode', ([], {'text': 'node_text'}), '(text=node_text)\n', (5503, 5519), False, 'from llama_index.core.schema import NodeWithScore, TextNode\n'), ((5681, 5713), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'n', 'score': '(1.0)'}), '(node=n, score=1.0)\n', (5694, 5713), False, 'from llama_index.core.schema import NodeWithScore, TextNode\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( completion_to_chat_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.watsonx_utils import ( WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class WatsonX(LLM): """IBM WatsonX LLM.""" model_id: str = Field(description="The Model to use.") max_new_tokens: int = Field(description="The maximum number of tokens to generate.") temperature: float = Field(description="The temperature to use for sampling.") additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional Kwargs for the WatsonX model" ) model_info: Dict[str, Any] = Field( default_factory=dict, description="Details about the selected model" ) _model = PrivateAttr() def __init__( self, credentials: Dict[str, Any], model_id: Optional[str] = "ibm/mpt-7b-instruct2", project_id: Optional[str] = None, space_id: Optional[str] = None, max_new_tokens: Optional[int] = 512, temperature: Optional[float] = 0.1, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: """Initialize params.""" if model_id not in WATSONX_MODELS: raise ValueError( f"Model name {model_id} not found in {WATSONX_MODELS.keys()}" ) try: from ibm_watson_machine_learning.foundation_models.model import Model except ImportError as e: raise ImportError( "You must install the `ibm_watson_machine_learning` package to use WatsonX" "please `pip install ibm_watson_machine_learning`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) project_id = get_from_param_or_env_without_error( project_id, "IBM_WATSONX_PROJECT_ID" ) space_id = get_from_param_or_env_without_error(space_id, "IBM_WATSONX_SPACE_ID") if project_id is not None or space_id is not None: self._model = Model( model_id=model_id, credentials=credentials, project_id=project_id, space_id=space_id, ) else: raise ValueError( f"Did not find `project_id` or `space_id`, Please pass them as named parameters" f" or as environment variables, `IBM_WATSONX_PROJECT_ID` or `IBM_WATSONX_SPACE_ID`." ) super().__init__( model_id=model_id, temperature=temperature, max_new_tokens=max_new_tokens, additional_kwargs=additional_kwargs, model_info=self._model.get_details(), callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(self) -> str: """Get Class Name.""" return "WatsonX_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=watsonx_model_to_context_size(self.model_id), num_output=self.max_new_tokens, model_name=self.model_id, ) @property def sample_model_kwargs(self) -> Dict[str, Any]: """Get a sample of Model kwargs that a user can pass to the model.""" try: from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames except ImportError as e: raise ImportError( "You must install the `ibm_watson_machine_learning` package to use WatsonX" "please `pip install ibm_watson_machine_learning`" ) from e params = GenTextParamsMetaNames().get_example_values() params.pop("return_options") return params @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "max_new_tokens": self.max_new_tokens, "temperature": self.temperature, } return {**base_kwargs, **self.additional_kwargs} def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return {**self._model_kwargs, **kwargs} @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) response = self._model.generate_text(prompt=prompt, params=all_kwargs) return CompletionResponse(text=response) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) stream_response = self._model.generate_text_stream( prompt=prompt, params=all_kwargs ) def gen() -> CompletionResponseGen: content = "" for stream_delta in stream_response: content += stream_delta yield CompletionResponse(text=content, delta=stream_delta) return gen() @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: all_kwargs = self._get_all_kwargs(**kwargs) chat_fn = completion_to_chat_decorator(self.complete) return chat_fn(messages, **all_kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) chat_stream_fn = stream_completion_to_chat_decorator(self.stream_complete) return chat_stream_fn(messages, **all_kwargs) # Async Functions # IBM Watson Machine Learning Package currently does not have Support for Async calls async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise NotImplementedError async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: raise NotImplementedError async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError
[ "llama_index.legacy.llms.watsonx_utils.WATSONX_MODELS.keys", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.llms.watsonx_utils.watsonx_model_to_context_size" ]
[((968, 1006), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Model to use."""'}), "(description='The Model to use.')\n", (973, 1006), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1033, 1095), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1038, 1095), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1121, 1178), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1126, 1178), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1219, 1306), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional Kwargs for the WatsonX model"""'}), "(default_factory=dict, description=\n 'Additional Kwargs for the WatsonX model')\n", (1224, 1306), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1349, 1424), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Details about the selected model"""'}), "(default_factory=dict, description='Details about the selected model')\n", (1354, 1424), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1453, 1466), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1464, 1466), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5496, 5521), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5519, 5521), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5823, 5848), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5846, 5848), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6402, 6421), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6419, 6421), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6674, 6693), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6691, 6693), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2920, 2993), 'llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error', 'get_from_param_or_env_without_error', (['project_id', '"""IBM_WATSONX_PROJECT_ID"""'], {}), "(project_id, 'IBM_WATSONX_PROJECT_ID')\n", (2955, 2993), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((3035, 3104), 'llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error', 'get_from_param_or_env_without_error', (['space_id', '"""IBM_WATSONX_SPACE_ID"""'], {}), "(space_id, 'IBM_WATSONX_SPACE_ID')\n", (3070, 3104), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((5783, 5816), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response'}), '(text=response)\n', (5801, 5816), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((6576, 6619), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self.complete'], {}), '(self.complete)\n', (6604, 6619), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, stream_completion_to_chat_decorator\n'), ((6879, 6936), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self.stream_complete'], {}), '(self.stream_complete)\n', (6914, 6936), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, stream_completion_to_chat_decorator\n'), ((2878, 2897), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (2893, 2897), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((3191, 3286), 'ibm_watson_machine_learning.foundation_models.model.Model', 'Model', ([], {'model_id': 'model_id', 'credentials': 'credentials', 'project_id': 'project_id', 'space_id': 'space_id'}), '(model_id=model_id, credentials=credentials, project_id=project_id,\n space_id=space_id)\n', (3196, 3286), False, 'from ibm_watson_machine_learning.foundation_models.model import Model\n'), ((4376, 4420), 'llama_index.legacy.llms.watsonx_utils.watsonx_model_to_context_size', 'watsonx_model_to_context_size', (['self.model_id'], {}), '(self.model_id)\n', (4405, 4420), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((5020, 5044), 'ibm_watson_machine_learning.metanames.GenTextParamsMetaNames', 'GenTextParamsMetaNames', ([], {}), '()\n', (5042, 5044), False, 'from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames\n'), ((6321, 6373), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'content', 'delta': 'stream_delta'}), '(text=content, delta=stream_delta)\n', (6339, 6373), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((2400, 2421), 'llama_index.legacy.llms.watsonx_utils.WATSONX_MODELS.keys', 'WATSONX_MODELS.keys', ([], {}), '()\n', (2419, 2421), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( completion_to_chat_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.watsonx_utils import ( WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class WatsonX(LLM): """IBM WatsonX LLM.""" model_id: str = Field(description="The Model to use.") max_new_tokens: int = Field(description="The maximum number of tokens to generate.") temperature: float = Field(description="The temperature to use for sampling.") additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional Kwargs for the WatsonX model" ) model_info: Dict[str, Any] = Field( default_factory=dict, description="Details about the selected model" ) _model = PrivateAttr() def __init__( self, credentials: Dict[str, Any], model_id: Optional[str] = "ibm/mpt-7b-instruct2", project_id: Optional[str] = None, space_id: Optional[str] = None, max_new_tokens: Optional[int] = 512, temperature: Optional[float] = 0.1, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: """Initialize params.""" if model_id not in WATSONX_MODELS: raise ValueError( f"Model name {model_id} not found in {WATSONX_MODELS.keys()}" ) try: from ibm_watson_machine_learning.foundation_models.model import Model except ImportError as e: raise ImportError( "You must install the `ibm_watson_machine_learning` package to use WatsonX" "please `pip install ibm_watson_machine_learning`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) project_id = get_from_param_or_env_without_error( project_id, "IBM_WATSONX_PROJECT_ID" ) space_id = get_from_param_or_env_without_error(space_id, "IBM_WATSONX_SPACE_ID") if project_id is not None or space_id is not None: self._model = Model( model_id=model_id, credentials=credentials, project_id=project_id, space_id=space_id, ) else: raise ValueError( f"Did not find `project_id` or `space_id`, Please pass them as named parameters" f" or as environment variables, `IBM_WATSONX_PROJECT_ID` or `IBM_WATSONX_SPACE_ID`." ) super().__init__( model_id=model_id, temperature=temperature, max_new_tokens=max_new_tokens, additional_kwargs=additional_kwargs, model_info=self._model.get_details(), callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(self) -> str: """Get Class Name.""" return "WatsonX_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=watsonx_model_to_context_size(self.model_id), num_output=self.max_new_tokens, model_name=self.model_id, ) @property def sample_model_kwargs(self) -> Dict[str, Any]: """Get a sample of Model kwargs that a user can pass to the model.""" try: from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames except ImportError as e: raise ImportError( "You must install the `ibm_watson_machine_learning` package to use WatsonX" "please `pip install ibm_watson_machine_learning`" ) from e params = GenTextParamsMetaNames().get_example_values() params.pop("return_options") return params @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "max_new_tokens": self.max_new_tokens, "temperature": self.temperature, } return {**base_kwargs, **self.additional_kwargs} def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return {**self._model_kwargs, **kwargs} @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: all_kwargs = self._get_all_kwargs(**kwargs) response = self._model.generate_text(prompt=prompt, params=all_kwargs) return CompletionResponse(text=response) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) stream_response = self._model.generate_text_stream( prompt=prompt, params=all_kwargs ) def gen() -> CompletionResponseGen: content = "" for stream_delta in stream_response: content += stream_delta yield CompletionResponse(text=content, delta=stream_delta) return gen() @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: all_kwargs = self._get_all_kwargs(**kwargs) chat_fn = completion_to_chat_decorator(self.complete) return chat_fn(messages, **all_kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: all_kwargs = self._get_all_kwargs(**kwargs) chat_stream_fn = stream_completion_to_chat_decorator(self.stream_complete) return chat_stream_fn(messages, **all_kwargs) # Async Functions # IBM Watson Machine Learning Package currently does not have Support for Async calls async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise NotImplementedError async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: raise NotImplementedError async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError
[ "llama_index.legacy.llms.watsonx_utils.WATSONX_MODELS.keys", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.llms.watsonx_utils.watsonx_model_to_context_size" ]
[((968, 1006), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Model to use."""'}), "(description='The Model to use.')\n", (973, 1006), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1033, 1095), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1038, 1095), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1121, 1178), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1126, 1178), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1219, 1306), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional Kwargs for the WatsonX model"""'}), "(default_factory=dict, description=\n 'Additional Kwargs for the WatsonX model')\n", (1224, 1306), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1349, 1424), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Details about the selected model"""'}), "(default_factory=dict, description='Details about the selected model')\n", (1354, 1424), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1453, 1466), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1464, 1466), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5496, 5521), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5519, 5521), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5823, 5848), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5846, 5848), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6402, 6421), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6419, 6421), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6674, 6693), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6691, 6693), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2920, 2993), 'llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error', 'get_from_param_or_env_without_error', (['project_id', '"""IBM_WATSONX_PROJECT_ID"""'], {}), "(project_id, 'IBM_WATSONX_PROJECT_ID')\n", (2955, 2993), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((3035, 3104), 'llama_index.legacy.llms.watsonx_utils.get_from_param_or_env_without_error', 'get_from_param_or_env_without_error', (['space_id', '"""IBM_WATSONX_SPACE_ID"""'], {}), "(space_id, 'IBM_WATSONX_SPACE_ID')\n", (3070, 3104), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((5783, 5816), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response'}), '(text=response)\n', (5801, 5816), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((6576, 6619), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self.complete'], {}), '(self.complete)\n', (6604, 6619), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, stream_completion_to_chat_decorator\n'), ((6879, 6936), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self.stream_complete'], {}), '(self.stream_complete)\n', (6914, 6936), False, 'from llama_index.legacy.llms.generic_utils import completion_to_chat_decorator, stream_completion_to_chat_decorator\n'), ((2878, 2897), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (2893, 2897), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((3191, 3286), 'ibm_watson_machine_learning.foundation_models.model.Model', 'Model', ([], {'model_id': 'model_id', 'credentials': 'credentials', 'project_id': 'project_id', 'space_id': 'space_id'}), '(model_id=model_id, credentials=credentials, project_id=project_id,\n space_id=space_id)\n', (3196, 3286), False, 'from ibm_watson_machine_learning.foundation_models.model import Model\n'), ((4376, 4420), 'llama_index.legacy.llms.watsonx_utils.watsonx_model_to_context_size', 'watsonx_model_to_context_size', (['self.model_id'], {}), '(self.model_id)\n', (4405, 4420), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n'), ((5020, 5044), 'ibm_watson_machine_learning.metanames.GenTextParamsMetaNames', 'GenTextParamsMetaNames', ([], {}), '()\n', (5042, 5044), False, 'from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames\n'), ((6321, 6373), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'content', 'delta': 'stream_delta'}), '(text=content, delta=stream_delta)\n', (6339, 6373), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((2400, 2421), 'llama_index.legacy.llms.watsonx_utils.WATSONX_MODELS.keys', 'WATSONX_MODELS.keys', ([], {}), '()\n', (2419, 2421), False, 'from llama_index.legacy.llms.watsonx_utils import WATSONX_MODELS, get_from_param_or_env_without_error, watsonx_model_to_context_size\n')]
from typing import Any, Awaitable, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_TEMPERATURE from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.litellm_utils import ( acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode DEFAULT_LITELLM_MODEL = "gpt-3.5-turbo" class LiteLLM(LLM): model: str = Field( default=DEFAULT_LITELLM_MODEL, description=( "The LiteLLM model to use. " "For complete list of providers https://docs.litellm.ai/docs/providers" ), ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use during generation.", gte=0.0, lte=1.0, ) max_tokens: Optional[int] = Field( description="The maximum number of tokens to generate.", gt=0, ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the LLM API.", # for all inputs https://docs.litellm.ai/docs/completion/input ) max_retries: int = Field( default=10, description="The maximum number of API retries." ) def __init__( self, model: str = DEFAULT_LITELLM_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = None, additional_kwargs: Optional[Dict[str, Any]] = None, max_retries: int = 10, api_key: Optional[str] = None, api_type: Optional[str] = None, api_base: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: if "custom_llm_provider" in kwargs: if ( kwargs["custom_llm_provider"] != "ollama" and kwargs["custom_llm_provider"] != "vllm" ): # don't check keys for local models validate_litellm_api_key(api_key, api_type) else: # by default assume it's a hosted endpoint validate_litellm_api_key(api_key, api_type) additional_kwargs = additional_kwargs or {} if api_key is not None: additional_kwargs["api_key"] = api_key if api_type is not None: additional_kwargs["api_type"] = api_type if api_base is not None: additional_kwargs["api_base"] = api_base super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, max_retries=max_retries, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, **kwargs, ) def _get_model_name(self) -> str: model_name = self.model if "ft-" in model_name: # legacy fine-tuning model_name = model_name.split(":")[0] elif model_name.startswith("ft:"): model_name = model_name.split(":")[1] return model_name @classmethod def class_name(cls) -> str: return "litellm_llm" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=openai_modelname_to_contextsize(self._get_model_name()), num_output=self.max_tokens or -1, is_chat_model=True, is_function_calling_model=is_function_calling_model(self._get_model_name()), model_name=self.model, ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if self._is_chat_model: chat_fn = self._chat else: chat_fn = completion_to_chat_decorator(self._complete) return chat_fn(messages, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if self._is_chat_model: stream_chat_fn = self._stream_chat else: stream_chat_fn = stream_completion_to_chat_decorator(self._stream_complete) return stream_chat_fn(messages, **kwargs) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: # litellm assumes all llms are chat llms if self._is_chat_model: complete_fn = chat_to_completion_decorator(self._chat) else: complete_fn = self._complete return complete_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: if self._is_chat_model: stream_complete_fn = stream_chat_to_completion_decorator(self._stream_chat) else: stream_complete_fn = self._stream_complete return stream_complete_fn(prompt, **kwargs) @property def _is_chat_model(self) -> bool: # litellm assumes all llms are chat llms return True @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_tokens": self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) if "max_tokens" in all_kwargs and all_kwargs["max_tokens"] is None: all_kwargs.pop( "max_tokens" ) # don't send max_tokens == None, this throws errors for Non OpenAI providers response = completion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=False, **all_kwargs, ) message_dict = response["choices"][0]["message"] message = from_litellm_message(message_dict) return ChatResponse( message=message, raw=response, additional_kwargs=self._get_response_token_counts(response), ) def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) if "max_tokens" in all_kwargs and all_kwargs["max_tokens"] is None: all_kwargs.pop( "max_tokens" ) # don't send max_tokens == None, this throws errors for Non OpenAI providers def gen() -> ChatResponseGen: content = "" function_call: Optional[dict] = None for response in completion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=True, **all_kwargs, ): delta = response["choices"][0]["delta"] role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta ## ensure we do not add a blank function call if function_call.get("function_name", "") is None: del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=response, additional_kwargs=self._get_response_token_counts(response), ) return gen() def _complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: raise NotImplementedError("litellm assumes all llms are chat llms.") def _stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen: raise NotImplementedError("litellm assumes all llms are chat llms.") def _get_max_token_for_prompt(self, prompt: str) -> int: try: import tiktoken except ImportError: raise ImportError( "Please install tiktoken to use the max_tokens=None feature." ) context_window = self.metadata.context_window try: encoding = tiktoken.encoding_for_model(self._get_model_name()) except KeyError: encoding = encoding = tiktoken.get_encoding( "cl100k_base" ) # default to using cl10k_base tokens = encoding.encode(prompt) max_token = context_window - len(tokens) if max_token <= 0: raise ValueError( f"The prompt is too long for the model. " f"Please use a prompt that is less than {context_window} tokens." ) return max_token def _get_response_token_counts(self, raw_response: Any) -> dict: """Get the token usage reported by the response.""" if not isinstance(raw_response, dict): return {} usage = raw_response.get("usage", {}) return { "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), "total_tokens": usage.get("total_tokens", 0), } # ===== Async Endpoints ===== @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponse: achat_fn: Callable[..., Awaitable[ChatResponse]] if self._is_chat_model: achat_fn = self._achat else: achat_fn = acompletion_to_chat_decorator(self._acomplete) return await achat_fn(messages, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponseAsyncGen: astream_chat_fn: Callable[..., Awaitable[ChatResponseAsyncGen]] if self._is_chat_model: astream_chat_fn = self._astream_chat else: astream_chat_fn = astream_completion_to_chat_decorator( self._astream_complete ) return await astream_chat_fn(messages, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: if self._is_chat_model: acomplete_fn = achat_to_completion_decorator(self._achat) else: acomplete_fn = self._acomplete return await acomplete_fn(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: if self._is_chat_model: astream_complete_fn = astream_chat_to_completion_decorator( self._astream_chat ) else: astream_complete_fn = self._astream_complete return await astream_complete_fn(prompt, **kwargs) async def _achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) response = await acompletion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=False, **all_kwargs, ) message_dict = response["choices"][0]["message"] message = from_litellm_message(message_dict) return ChatResponse( message=message, raw=response, additional_kwargs=self._get_response_token_counts(response), ) async def _astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) async def gen() -> ChatResponseAsyncGen: content = "" function_call: Optional[dict] = None async for response in await acompletion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=True, **all_kwargs, ): delta = response["choices"][0]["delta"] role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta ## ensure we do not add a blank function call if function_call.get("function_name", "") is None: del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=response, additional_kwargs=self._get_response_token_counts(response), ) return gen() async def _acomplete(self, prompt: str, **kwargs: Any) -> CompletionResponse: raise NotImplementedError("litellm assumes all llms are chat llms.") async def _astream_complete( self, prompt: str, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError("litellm assumes all llms are chat llms.")
[ "llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.litellm_utils.completion_with_retry", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.acompletion_with_retry", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.litellm_utils.validate_litellm_api_key", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.llms.generic_utils.astream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.achat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.to_openai_message_dicts", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.generic_utils.acompletion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.from_litellm_message" ]
[((1378, 1535), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_LITELLM_MODEL', 'description': '"""The LiteLLM model to use. For complete list of providers https://docs.litellm.ai/docs/providers"""'}), "(default=DEFAULT_LITELLM_MODEL, description=\n 'The LiteLLM model to use. For complete list of providers https://docs.litellm.ai/docs/providers'\n )\n", (1383, 1535), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1613, 1727), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_TEMPERATURE', 'description': '"""The temperature to use during generation."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=DEFAULT_TEMPERATURE, description=\n 'The temperature to use during generation.', gte=0.0, lte=1.0)\n", (1618, 1727), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1794, 1862), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""', 'gt': '(0)'}), "(description='The maximum number of tokens to generate.', gt=0)\n", (1799, 1862), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1926, 2003), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the LLM API."""'}), "(default_factory=dict, description='Additional kwargs for the LLM API.')\n", (1931, 2003), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2121, 2188), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""'}), "(default=10, description='The maximum number of API retries.')\n", (2126, 2188), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((5024, 5043), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5041, 5043), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5323, 5342), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5340, 5342), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5688, 5713), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5711, 5713), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6082, 6107), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6105, 6107), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12053, 12072), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (12070, 12072), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12459, 12478), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (12476, 12478), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12967, 12992), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (12990, 12992), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13330, 13355), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13353, 13355), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7262, 7295), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (7285, 7295), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((7593, 7736), 'llama_index.legacy.llms.litellm_utils.completion_with_retry', 'completion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(False)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=False, **all_kwargs)\n', (7614, 7736), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((7878, 7912), 'llama_index.legacy.llms.litellm_utils.from_litellm_message', 'from_litellm_message', (['message_dict'], {}), '(message_dict)\n', (7898, 7912), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((8316, 8349), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (8339, 8349), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14006, 14039), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (14029, 14039), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14403, 14437), 'llama_index.legacy.llms.litellm_utils.from_litellm_message', 'from_litellm_message', (['message_dict'], {}), '(message_dict)\n', (14423, 14437), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14853, 14886), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (14876, 14886), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((3380, 3423), 'llama_index.legacy.llms.litellm_utils.validate_litellm_api_key', 'validate_litellm_api_key', (['api_key', 'api_type'], {}), '(api_key, api_type)\n', (3404, 3423), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((5229, 5273), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self._complete'], {}), '(self._complete)\n', (5257, 5273), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5573, 5631), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self._stream_complete'], {}), '(self._stream_complete)\n', (5608, 5631), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5934, 5974), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self._chat'], {}), '(self._chat)\n', (5962, 5974), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((6296, 6350), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self._stream_chat'], {}), '(self._stream_chat)\n', (6331, 6350), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((8768, 8910), 'llama_index.legacy.llms.litellm_utils.completion_with_retry', 'completion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(True)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=True, **all_kwargs)\n', (8789, 8910), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((12356, 12402), 'llama_index.legacy.llms.generic_utils.acompletion_to_chat_decorator', 'acompletion_to_chat_decorator', (['self._acomplete'], {}), '(self._acomplete)\n', (12385, 12402), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((12813, 12873), 'llama_index.legacy.llms.generic_utils.astream_completion_to_chat_decorator', 'astream_completion_to_chat_decorator', (['self._astream_complete'], {}), '(self._astream_complete)\n', (12849, 12873), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((13172, 13214), 'llama_index.legacy.llms.generic_utils.achat_to_completion_decorator', 'achat_to_completion_decorator', (['self._achat'], {}), '(self._achat)\n', (13201, 13214), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((13557, 13613), 'llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator', 'astream_chat_to_completion_decorator', (['self._astream_chat'], {}), '(self._astream_chat)\n', (13593, 13613), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((14117, 14261), 'llama_index.legacy.llms.litellm_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(False)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=False, **all_kwargs)\n', (14139, 14261), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((3266, 3309), 'llama_index.legacy.llms.litellm_utils.validate_litellm_api_key', 'validate_litellm_api_key', (['api_key', 'api_type'], {}), '(api_key, api_type)\n', (3290, 3309), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((11130, 11166), 'tiktoken.get_encoding', 'tiktoken.get_encoding', (['"""cl100k_base"""'], {}), "('cl100k_base')\n", (11151, 11166), False, 'import tiktoken\n'), ((15103, 15246), 'llama_index.legacy.llms.litellm_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(True)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=True, **all_kwargs)\n', (15125, 15246), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((9990, 10066), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (10001, 10066), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((16326, 16402), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (16337, 16402), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
from typing import Any, Awaitable, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_TEMPERATURE from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.generic_utils import ( achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator, ) from llama_index.legacy.llms.litellm_utils import ( acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode DEFAULT_LITELLM_MODEL = "gpt-3.5-turbo" class LiteLLM(LLM): model: str = Field( default=DEFAULT_LITELLM_MODEL, description=( "The LiteLLM model to use. " "For complete list of providers https://docs.litellm.ai/docs/providers" ), ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use during generation.", gte=0.0, lte=1.0, ) max_tokens: Optional[int] = Field( description="The maximum number of tokens to generate.", gt=0, ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the LLM API.", # for all inputs https://docs.litellm.ai/docs/completion/input ) max_retries: int = Field( default=10, description="The maximum number of API retries." ) def __init__( self, model: str = DEFAULT_LITELLM_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = None, additional_kwargs: Optional[Dict[str, Any]] = None, max_retries: int = 10, api_key: Optional[str] = None, api_type: Optional[str] = None, api_base: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: if "custom_llm_provider" in kwargs: if ( kwargs["custom_llm_provider"] != "ollama" and kwargs["custom_llm_provider"] != "vllm" ): # don't check keys for local models validate_litellm_api_key(api_key, api_type) else: # by default assume it's a hosted endpoint validate_litellm_api_key(api_key, api_type) additional_kwargs = additional_kwargs or {} if api_key is not None: additional_kwargs["api_key"] = api_key if api_type is not None: additional_kwargs["api_type"] = api_type if api_base is not None: additional_kwargs["api_base"] = api_base super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, max_retries=max_retries, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, **kwargs, ) def _get_model_name(self) -> str: model_name = self.model if "ft-" in model_name: # legacy fine-tuning model_name = model_name.split(":")[0] elif model_name.startswith("ft:"): model_name = model_name.split(":")[1] return model_name @classmethod def class_name(cls) -> str: return "litellm_llm" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=openai_modelname_to_contextsize(self._get_model_name()), num_output=self.max_tokens or -1, is_chat_model=True, is_function_calling_model=is_function_calling_model(self._get_model_name()), model_name=self.model, ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if self._is_chat_model: chat_fn = self._chat else: chat_fn = completion_to_chat_decorator(self._complete) return chat_fn(messages, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if self._is_chat_model: stream_chat_fn = self._stream_chat else: stream_chat_fn = stream_completion_to_chat_decorator(self._stream_complete) return stream_chat_fn(messages, **kwargs) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: # litellm assumes all llms are chat llms if self._is_chat_model: complete_fn = chat_to_completion_decorator(self._chat) else: complete_fn = self._complete return complete_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: if self._is_chat_model: stream_complete_fn = stream_chat_to_completion_decorator(self._stream_chat) else: stream_complete_fn = self._stream_complete return stream_complete_fn(prompt, **kwargs) @property def _is_chat_model(self) -> bool: # litellm assumes all llms are chat llms return True @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_tokens": self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) if "max_tokens" in all_kwargs and all_kwargs["max_tokens"] is None: all_kwargs.pop( "max_tokens" ) # don't send max_tokens == None, this throws errors for Non OpenAI providers response = completion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=False, **all_kwargs, ) message_dict = response["choices"][0]["message"] message = from_litellm_message(message_dict) return ChatResponse( message=message, raw=response, additional_kwargs=self._get_response_token_counts(response), ) def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) if "max_tokens" in all_kwargs and all_kwargs["max_tokens"] is None: all_kwargs.pop( "max_tokens" ) # don't send max_tokens == None, this throws errors for Non OpenAI providers def gen() -> ChatResponseGen: content = "" function_call: Optional[dict] = None for response in completion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=True, **all_kwargs, ): delta = response["choices"][0]["delta"] role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta ## ensure we do not add a blank function call if function_call.get("function_name", "") is None: del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=response, additional_kwargs=self._get_response_token_counts(response), ) return gen() def _complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: raise NotImplementedError("litellm assumes all llms are chat llms.") def _stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen: raise NotImplementedError("litellm assumes all llms are chat llms.") def _get_max_token_for_prompt(self, prompt: str) -> int: try: import tiktoken except ImportError: raise ImportError( "Please install tiktoken to use the max_tokens=None feature." ) context_window = self.metadata.context_window try: encoding = tiktoken.encoding_for_model(self._get_model_name()) except KeyError: encoding = encoding = tiktoken.get_encoding( "cl100k_base" ) # default to using cl10k_base tokens = encoding.encode(prompt) max_token = context_window - len(tokens) if max_token <= 0: raise ValueError( f"The prompt is too long for the model. " f"Please use a prompt that is less than {context_window} tokens." ) return max_token def _get_response_token_counts(self, raw_response: Any) -> dict: """Get the token usage reported by the response.""" if not isinstance(raw_response, dict): return {} usage = raw_response.get("usage", {}) return { "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), "total_tokens": usage.get("total_tokens", 0), } # ===== Async Endpoints ===== @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponse: achat_fn: Callable[..., Awaitable[ChatResponse]] if self._is_chat_model: achat_fn = self._achat else: achat_fn = acompletion_to_chat_decorator(self._acomplete) return await achat_fn(messages, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any, ) -> ChatResponseAsyncGen: astream_chat_fn: Callable[..., Awaitable[ChatResponseAsyncGen]] if self._is_chat_model: astream_chat_fn = self._astream_chat else: astream_chat_fn = astream_completion_to_chat_decorator( self._astream_complete ) return await astream_chat_fn(messages, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: if self._is_chat_model: acomplete_fn = achat_to_completion_decorator(self._achat) else: acomplete_fn = self._acomplete return await acomplete_fn(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: if self._is_chat_model: astream_complete_fn = astream_chat_to_completion_decorator( self._astream_chat ) else: astream_complete_fn = self._astream_complete return await astream_complete_fn(prompt, **kwargs) async def _achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) response = await acompletion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=False, **all_kwargs, ) message_dict = response["choices"][0]["message"] message = from_litellm_message(message_dict) return ChatResponse( message=message, raw=response, additional_kwargs=self._get_response_token_counts(response), ) async def _astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: if not self._is_chat_model: raise ValueError("This model is not a chat model.") message_dicts = to_openai_message_dicts(messages) all_kwargs = self._get_all_kwargs(**kwargs) async def gen() -> ChatResponseAsyncGen: content = "" function_call: Optional[dict] = None async for response in await acompletion_with_retry( is_chat_model=self._is_chat_model, max_retries=self.max_retries, messages=message_dicts, stream=True, **all_kwargs, ): delta = response["choices"][0]["delta"] role = delta.get("role", "assistant") content_delta = delta.get("content", "") or "" content += content_delta function_call_delta = delta.get("function_call", None) if function_call_delta is not None: if function_call is None: function_call = function_call_delta ## ensure we do not add a blank function call if function_call.get("function_name", "") is None: del function_call["function_name"] else: function_call["arguments"] += function_call_delta["arguments"] additional_kwargs = {} if function_call is not None: additional_kwargs["function_call"] = function_call yield ChatResponse( message=ChatMessage( role=role, content=content, additional_kwargs=additional_kwargs, ), delta=content_delta, raw=response, additional_kwargs=self._get_response_token_counts(response), ) return gen() async def _acomplete(self, prompt: str, **kwargs: Any) -> CompletionResponse: raise NotImplementedError("litellm assumes all llms are chat llms.") async def _astream_complete( self, prompt: str, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError("litellm assumes all llms are chat llms.")
[ "llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.litellm_utils.completion_with_retry", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.acompletion_with_retry", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.litellm_utils.validate_litellm_api_key", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.llms.generic_utils.astream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.achat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.to_openai_message_dicts", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.generic_utils.acompletion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.litellm_utils.from_litellm_message" ]
[((1378, 1535), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_LITELLM_MODEL', 'description': '"""The LiteLLM model to use. For complete list of providers https://docs.litellm.ai/docs/providers"""'}), "(default=DEFAULT_LITELLM_MODEL, description=\n 'The LiteLLM model to use. For complete list of providers https://docs.litellm.ai/docs/providers'\n )\n", (1383, 1535), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1613, 1727), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_TEMPERATURE', 'description': '"""The temperature to use during generation."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=DEFAULT_TEMPERATURE, description=\n 'The temperature to use during generation.', gte=0.0, lte=1.0)\n", (1618, 1727), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1794, 1862), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""', 'gt': '(0)'}), "(description='The maximum number of tokens to generate.', gt=0)\n", (1799, 1862), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1926, 2003), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the LLM API."""'}), "(default_factory=dict, description='Additional kwargs for the LLM API.')\n", (1931, 2003), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((2121, 2188), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""'}), "(default=10, description='The maximum number of API retries.')\n", (2126, 2188), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((5024, 5043), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5041, 5043), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5323, 5342), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5340, 5342), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((5688, 5713), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (5711, 5713), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6082, 6107), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6105, 6107), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12053, 12072), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (12070, 12072), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12459, 12478), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (12476, 12478), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((12967, 12992), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (12990, 12992), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((13330, 13355), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (13353, 13355), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7262, 7295), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (7285, 7295), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((7593, 7736), 'llama_index.legacy.llms.litellm_utils.completion_with_retry', 'completion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(False)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=False, **all_kwargs)\n', (7614, 7736), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((7878, 7912), 'llama_index.legacy.llms.litellm_utils.from_litellm_message', 'from_litellm_message', (['message_dict'], {}), '(message_dict)\n', (7898, 7912), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((8316, 8349), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (8339, 8349), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14006, 14039), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (14029, 14039), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14403, 14437), 'llama_index.legacy.llms.litellm_utils.from_litellm_message', 'from_litellm_message', (['message_dict'], {}), '(message_dict)\n', (14423, 14437), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((14853, 14886), 'llama_index.legacy.llms.litellm_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (14876, 14886), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((3380, 3423), 'llama_index.legacy.llms.litellm_utils.validate_litellm_api_key', 'validate_litellm_api_key', (['api_key', 'api_type'], {}), '(api_key, api_type)\n', (3404, 3423), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((5229, 5273), 'llama_index.legacy.llms.generic_utils.completion_to_chat_decorator', 'completion_to_chat_decorator', (['self._complete'], {}), '(self._complete)\n', (5257, 5273), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5573, 5631), 'llama_index.legacy.llms.generic_utils.stream_completion_to_chat_decorator', 'stream_completion_to_chat_decorator', (['self._stream_complete'], {}), '(self._stream_complete)\n', (5608, 5631), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((5934, 5974), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self._chat'], {}), '(self._chat)\n', (5962, 5974), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((6296, 6350), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self._stream_chat'], {}), '(self._stream_chat)\n', (6331, 6350), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((8768, 8910), 'llama_index.legacy.llms.litellm_utils.completion_with_retry', 'completion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(True)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=True, **all_kwargs)\n', (8789, 8910), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((12356, 12402), 'llama_index.legacy.llms.generic_utils.acompletion_to_chat_decorator', 'acompletion_to_chat_decorator', (['self._acomplete'], {}), '(self._acomplete)\n', (12385, 12402), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((12813, 12873), 'llama_index.legacy.llms.generic_utils.astream_completion_to_chat_decorator', 'astream_completion_to_chat_decorator', (['self._astream_complete'], {}), '(self._astream_complete)\n', (12849, 12873), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((13172, 13214), 'llama_index.legacy.llms.generic_utils.achat_to_completion_decorator', 'achat_to_completion_decorator', (['self._achat'], {}), '(self._achat)\n', (13201, 13214), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((13557, 13613), 'llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator', 'astream_chat_to_completion_decorator', (['self._astream_chat'], {}), '(self._astream_chat)\n', (13593, 13613), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, acompletion_to_chat_decorator, astream_chat_to_completion_decorator, astream_completion_to_chat_decorator, chat_to_completion_decorator, completion_to_chat_decorator, stream_chat_to_completion_decorator, stream_completion_to_chat_decorator\n'), ((14117, 14261), 'llama_index.legacy.llms.litellm_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(False)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=False, **all_kwargs)\n', (14139, 14261), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((3266, 3309), 'llama_index.legacy.llms.litellm_utils.validate_litellm_api_key', 'validate_litellm_api_key', (['api_key', 'api_type'], {}), '(api_key, api_type)\n', (3290, 3309), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((11130, 11166), 'tiktoken.get_encoding', 'tiktoken.get_encoding', (['"""cl100k_base"""'], {}), "('cl100k_base')\n", (11151, 11166), False, 'import tiktoken\n'), ((15103, 15246), 'llama_index.legacy.llms.litellm_utils.acompletion_with_retry', 'acompletion_with_retry', ([], {'is_chat_model': 'self._is_chat_model', 'max_retries': 'self.max_retries', 'messages': 'message_dicts', 'stream': '(True)'}), '(is_chat_model=self._is_chat_model, max_retries=self.\n max_retries, messages=message_dicts, stream=True, **all_kwargs)\n', (15125, 15246), False, 'from llama_index.legacy.llms.litellm_utils import acompletion_with_retry, completion_with_retry, from_litellm_message, is_function_calling_model, openai_modelname_to_contextsize, to_openai_message_dicts, validate_litellm_api_key\n'), ((9990, 10066), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (10001, 10066), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((16326, 16402), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content', 'additional_kwargs': 'additional_kwargs'}), '(role=role, content=content, additional_kwargs=additional_kwargs)\n', (16337, 16402), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset("MiniTruthfulQADataset", "./data") # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 322), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MiniTruthfulQADataset"""', '"""./data"""'], {}), "('MiniTruthfulQADataset', './data')\n", (287, 322), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((367, 419), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (398, 419), False, 'from llama_index.core import VectorStoreIndex\n'), ((512, 561), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack"""'], {}), "('RagEvaluatorPack', './pack')\n", (531, 561), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1412, 1436), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1434, 1436), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset("MiniTruthfulQADataset", "./data") # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 322), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MiniTruthfulQADataset"""', '"""./data"""'], {}), "('MiniTruthfulQADataset', './data')\n", (287, 322), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((367, 419), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (398, 419), False, 'from llama_index.core import VectorStoreIndex\n'), ((512, 561), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack"""'], {}), "('RagEvaluatorPack', './pack')\n", (531, 561), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1412, 1436), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1434, 1436), False, 'import asyncio\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_TEMPERATURE # from mistralai.models.chat_completion import ChatMessage from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.generic_utils import ( achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.mistralai_utils import ( mistralai_modelname_to_contextsize, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode DEFAULT_MISTRALAI_MODEL = "mistral-tiny" DEFAULT_MISTRALAI_ENDPOINT = "https://api.mistral.ai" DEFAULT_MISTRALAI_MAX_TOKENS = 512 class MistralAI(LLM): model: str = Field( default=DEFAULT_MISTRALAI_MODEL, description="The mistralai model to use." ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use for sampling.", gte=0.0, lte=1.0, ) max_tokens: int = Field( default=DEFAULT_MISTRALAI_MAX_TOKENS, description="The maximum number of tokens to generate.", gt=0, ) timeout: float = Field( default=120, description="The timeout to use in seconds.", gte=0 ) max_retries: int = Field( default=5, description="The maximum number of API retries.", gte=0 ) safe_mode: bool = Field( default=False, description="The parameter to enforce guardrails in chat generations.", ) random_seed: str = Field( default=None, description="The random seed to use for sampling." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the MistralAI API." ) _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() def __init__( self, model: str = DEFAULT_MISTRALAI_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MISTRALAI_MAX_TOKENS, timeout: int = 120, max_retries: int = 5, safe_mode: bool = False, random_seed: Optional[int] = None, api_key: Optional[str] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from mistralai.async_client import MistralAsyncClient from mistralai.client import MistralClient except ImportError as e: raise ImportError( "You must install the `mistralai` package to use mistralai." "Please `pip install mistralai`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) api_key = get_from_param_or_env("api_key", api_key, "MISTRAL_API_KEY", "") if not api_key: raise ValueError( "You must provide an API key to use mistralai. " "You can either pass it in as an argument or set it `MISTRAL_API_KEY`." ) self._client = MistralClient( api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout=timeout, max_retries=max_retries, ) self._aclient = MistralAsyncClient( api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout=timeout, max_retries=max_retries, ) super().__init__( temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, timeout=timeout, max_retries=max_retries, safe_mode=safe_mode, random_seed=random_seed, model=model, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "MistralAI_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=mistralai_modelname_to_contextsize(self.model), num_output=self.max_tokens, is_chat_model=True, model_name=self.model, safe_mode=self.safe_mode, random_seed=self.random_seed, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_tokens": self.max_tokens, "random_seed": self.random_seed, "safe_mode": self.safe_mode, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=x.role, content=x.content) for x in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = self._client.chat(messages=messages, **all_kwargs) return ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, content=response.choices[0].message.content ), raw=dict(response), ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: complete_fn = chat_to_completion_decorator(self.chat) return complete_fn(prompt, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=message.role, content=message.content) for message in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = self._client.chat_stream(messages=messages, **all_kwargs) def gen() -> ChatResponseGen: content = "" role = MessageRole.ASSISTANT for chunk in response: content_delta = chunk.choices[0].delta.content if content_delta is None: continue content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=chunk, ) return gen() @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: stream_complete_fn = stream_chat_to_completion_decorator(self.stream_chat) return stream_complete_fn(prompt, **kwargs) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=message.role, content=message.content) for message in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = await self._aclient.chat(messages=messages, **all_kwargs) return ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, content=response.choices[0].message.content ), raw=dict(response), ) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: acomplete_fn = achat_to_completion_decorator(self.achat) return await acomplete_fn(prompt, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=x.role, content=x.content) for x in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = await self._aclient.chat_stream(messages=messages, **all_kwargs) async def gen() -> ChatResponseAsyncGen: content = "" role = MessageRole.ASSISTANT async for chunk in response: content_delta = chunk.choices[0].delta.content if content_delta is None: continue content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=chunk, ) return gen() @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: astream_complete_fn = astream_chat_to_completion_decorator(self.astream_chat) return await astream_complete_fn(prompt, **kwargs)
[ "llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.get_from_param_or_env", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.mistralai_utils.mistralai_modelname_to_contextsize", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.llms.generic_utils.achat_to_completion_decorator", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator" ]
[((1271, 1357), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_MISTRALAI_MODEL', 'description': '"""The mistralai model to use."""'}), "(default=DEFAULT_MISTRALAI_MODEL, description=\n 'The mistralai model to use.')\n", (1276, 1357), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1392, 1501), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_TEMPERATURE', 'description': '"""The temperature to use for sampling."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=DEFAULT_TEMPERATURE, description=\n 'The temperature to use for sampling.', gte=0.0, lte=1.0)\n", (1397, 1501), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1558, 1669), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_MISTRALAI_MAX_TOKENS', 'description': '"""The maximum number of tokens to generate."""', 'gt': '(0)'}), "(default=DEFAULT_MISTRALAI_MAX_TOKENS, description=\n 'The maximum number of tokens to generate.', gt=0)\n", (1563, 1669), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1718, 1789), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(120)', 'description': '"""The timeout to use in seconds."""', 'gte': '(0)'}), "(default=120, description='The timeout to use in seconds.', gte=0)\n", (1723, 1789), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1827, 1900), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(5)', 'description': '"""The maximum number of API retries."""', 'gte': '(0)'}), "(default=5, description='The maximum number of API retries.', gte=0)\n", (1832, 1900), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1937, 2034), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""The parameter to enforce guardrails in chat generations."""'}), "(default=False, description=\n 'The parameter to enforce guardrails in chat generations.')\n", (1942, 2034), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2076, 2147), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""The random seed to use for sampling."""'}), "(default=None, description='The random seed to use for sampling.')\n", (2081, 2147), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2202, 2290), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the MistralAI API."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the MistralAI API.')\n", (2207, 2290), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2320, 2333), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2331, 2333), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2354, 2367), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2365, 2367), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5957, 5976), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5974, 5976), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6632, 6657), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6655, 6657), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6884, 6903), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6901, 6903), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7946, 7971), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7969, 7971), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8236, 8255), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8253, 8255), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8969, 8994), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8992, 8994), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9238, 9257), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9255, 9257), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((10306, 10331), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (10329, 10331), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3684, 3748), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_key"""', 'api_key', '"""MISTRAL_API_KEY"""', '""""""'], {}), "('api_key', api_key, 'MISTRAL_API_KEY', '')\n", (3705, 3748), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((3995, 4109), 'mistralai.client.MistralClient', 'MistralClient', ([], {'api_key': 'api_key', 'endpoint': 'DEFAULT_MISTRALAI_ENDPOINT', 'timeout': 'timeout', 'max_retries': 'max_retries'}), '(api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout\n =timeout, max_retries=max_retries)\n', (4008, 4109), False, 'from mistralai.client import MistralClient\n'), ((4188, 4306), 'mistralai.async_client.MistralAsyncClient', 'MistralAsyncClient', ([], {'api_key': 'api_key', 'endpoint': 'DEFAULT_MISTRALAI_ENDPOINT', 'timeout': 'timeout', 'max_retries': 'max_retries'}), '(api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT,\n timeout=timeout, max_retries=max_retries)\n', (4206, 4306), False, 'from mistralai.async_client import MistralAsyncClient\n'), ((6793, 6832), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self.chat'], {}), '(self.chat)\n', (6821, 6832), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((8124, 8177), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self.stream_chat'], {}), '(self.stream_chat)\n', (8159, 8177), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((9138, 9179), 'llama_index.legacy.llms.generic_utils.achat_to_completion_decorator', 'achat_to_completion_decorator', (['self.achat'], {}), '(self.achat)\n', (9167, 9179), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((10497, 10552), 'llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator', 'astream_chat_to_completion_decorator', (['self.astream_chat'], {}), '(self.astream_chat)\n', (10533, 10552), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((3645, 3664), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (3660, 3664), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((6217, 6268), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'x.role', 'content': 'x.content'}), '(role=x.role, content=x.content)\n', (6236, 6268), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((7168, 7231), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'message.role', 'content': 'message.content'}), '(role=message.role, content=message.content)\n', (7187, 7231), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((8517, 8580), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'message.role', 'content': 'message.content'}), '(role=message.role, content=message.content)\n', (8536, 8580), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((9534, 9585), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'x.role', 'content': 'x.content'}), '(role=x.role, content=x.content)\n', (9553, 9585), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((5163, 5209), 'llama_index.legacy.llms.mistralai_utils.mistralai_modelname_to_contextsize', 'mistralai_modelname_to_contextsize', (['self.model'], {}), '(self.model)\n', (5197, 5209), False, 'from llama_index.legacy.llms.mistralai_utils import mistralai_modelname_to_contextsize\n'), ((6468, 6557), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.choices[0].message.content'}), '(role=MessageRole.ASSISTANT, content=response.choices[0].message\n .content)\n', (6479, 6557), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((8805, 8894), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.choices[0].message.content'}), '(role=MessageRole.ASSISTANT, content=response.choices[0].message\n .content)\n', (8816, 8894), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((7787, 7826), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (7798, 7826), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((10147, 10186), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (10158, 10186), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_TEMPERATURE # from mistralai.models.chat_completion import ChatMessage from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.generic_utils import ( achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.llms.mistralai_utils import ( mistralai_modelname_to_contextsize, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode DEFAULT_MISTRALAI_MODEL = "mistral-tiny" DEFAULT_MISTRALAI_ENDPOINT = "https://api.mistral.ai" DEFAULT_MISTRALAI_MAX_TOKENS = 512 class MistralAI(LLM): model: str = Field( default=DEFAULT_MISTRALAI_MODEL, description="The mistralai model to use." ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use for sampling.", gte=0.0, lte=1.0, ) max_tokens: int = Field( default=DEFAULT_MISTRALAI_MAX_TOKENS, description="The maximum number of tokens to generate.", gt=0, ) timeout: float = Field( default=120, description="The timeout to use in seconds.", gte=0 ) max_retries: int = Field( default=5, description="The maximum number of API retries.", gte=0 ) safe_mode: bool = Field( default=False, description="The parameter to enforce guardrails in chat generations.", ) random_seed: str = Field( default=None, description="The random seed to use for sampling." ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the MistralAI API." ) _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() def __init__( self, model: str = DEFAULT_MISTRALAI_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MISTRALAI_MAX_TOKENS, timeout: int = 120, max_retries: int = 5, safe_mode: bool = False, random_seed: Optional[int] = None, api_key: Optional[str] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from mistralai.async_client import MistralAsyncClient from mistralai.client import MistralClient except ImportError as e: raise ImportError( "You must install the `mistralai` package to use mistralai." "Please `pip install mistralai`" ) from e additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) api_key = get_from_param_or_env("api_key", api_key, "MISTRAL_API_KEY", "") if not api_key: raise ValueError( "You must provide an API key to use mistralai. " "You can either pass it in as an argument or set it `MISTRAL_API_KEY`." ) self._client = MistralClient( api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout=timeout, max_retries=max_retries, ) self._aclient = MistralAsyncClient( api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout=timeout, max_retries=max_retries, ) super().__init__( temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, timeout=timeout, max_retries=max_retries, safe_mode=safe_mode, random_seed=random_seed, model=model, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "MistralAI_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=mistralai_modelname_to_contextsize(self.model), num_output=self.max_tokens, is_chat_model=True, model_name=self.model, safe_mode=self.safe_mode, random_seed=self.random_seed, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_tokens": self.max_tokens, "random_seed": self.random_seed, "safe_mode": self.safe_mode, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=x.role, content=x.content) for x in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = self._client.chat(messages=messages, **all_kwargs) return ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, content=response.choices[0].message.content ), raw=dict(response), ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: complete_fn = chat_to_completion_decorator(self.chat) return complete_fn(prompt, **kwargs) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=message.role, content=message.content) for message in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = self._client.chat_stream(messages=messages, **all_kwargs) def gen() -> ChatResponseGen: content = "" role = MessageRole.ASSISTANT for chunk in response: content_delta = chunk.choices[0].delta.content if content_delta is None: continue content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=chunk, ) return gen() @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: stream_complete_fn = stream_chat_to_completion_decorator(self.stream_chat) return stream_complete_fn(prompt, **kwargs) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=message.role, content=message.content) for message in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = await self._aclient.chat(messages=messages, **all_kwargs) return ChatResponse( message=ChatMessage( role=MessageRole.ASSISTANT, content=response.choices[0].message.content ), raw=dict(response), ) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: acomplete_fn = achat_to_completion_decorator(self.achat) return await acomplete_fn(prompt, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: # convert messages to mistral ChatMessage from mistralai.client import ChatMessage as mistral_chatmessage messages = [ mistral_chatmessage(role=x.role, content=x.content) for x in messages ] all_kwargs = self._get_all_kwargs(**kwargs) response = await self._aclient.chat_stream(messages=messages, **all_kwargs) async def gen() -> ChatResponseAsyncGen: content = "" role = MessageRole.ASSISTANT async for chunk in response: content_delta = chunk.choices[0].delta.content if content_delta is None: continue content += content_delta yield ChatResponse( message=ChatMessage(role=role, content=content), delta=content_delta, raw=chunk, ) return gen() @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: astream_complete_fn = astream_chat_to_completion_decorator(self.astream_chat) return await astream_complete_fn(prompt, **kwargs)
[ "llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.get_from_param_or_env", "llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.mistralai_utils.mistralai_modelname_to_contextsize", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.llms.generic_utils.achat_to_completion_decorator", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator" ]
[((1271, 1357), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_MISTRALAI_MODEL', 'description': '"""The mistralai model to use."""'}), "(default=DEFAULT_MISTRALAI_MODEL, description=\n 'The mistralai model to use.')\n", (1276, 1357), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1392, 1501), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_TEMPERATURE', 'description': '"""The temperature to use for sampling."""', 'gte': '(0.0)', 'lte': '(1.0)'}), "(default=DEFAULT_TEMPERATURE, description=\n 'The temperature to use for sampling.', gte=0.0, lte=1.0)\n", (1397, 1501), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1558, 1669), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_MISTRALAI_MAX_TOKENS', 'description': '"""The maximum number of tokens to generate."""', 'gt': '(0)'}), "(default=DEFAULT_MISTRALAI_MAX_TOKENS, description=\n 'The maximum number of tokens to generate.', gt=0)\n", (1563, 1669), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1718, 1789), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(120)', 'description': '"""The timeout to use in seconds."""', 'gte': '(0)'}), "(default=120, description='The timeout to use in seconds.', gte=0)\n", (1723, 1789), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1827, 1900), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(5)', 'description': '"""The maximum number of API retries."""', 'gte': '(0)'}), "(default=5, description='The maximum number of API retries.', gte=0)\n", (1832, 1900), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1937, 2034), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""The parameter to enforce guardrails in chat generations."""'}), "(default=False, description=\n 'The parameter to enforce guardrails in chat generations.')\n", (1942, 2034), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2076, 2147), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'None', 'description': '"""The random seed to use for sampling."""'}), "(default=None, description='The random seed to use for sampling.')\n", (2081, 2147), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2202, 2290), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the MistralAI API."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the MistralAI API.')\n", (2207, 2290), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2320, 2333), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2331, 2333), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2354, 2367), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2365, 2367), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5957, 5976), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (5974, 5976), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6632, 6657), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6655, 6657), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6884, 6903), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6901, 6903), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7946, 7971), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7969, 7971), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8236, 8255), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (8253, 8255), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8969, 8994), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8992, 8994), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9238, 9257), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9255, 9257), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((10306, 10331), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (10329, 10331), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3684, 3748), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_key"""', 'api_key', '"""MISTRAL_API_KEY"""', '""""""'], {}), "('api_key', api_key, 'MISTRAL_API_KEY', '')\n", (3705, 3748), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((3995, 4109), 'mistralai.client.MistralClient', 'MistralClient', ([], {'api_key': 'api_key', 'endpoint': 'DEFAULT_MISTRALAI_ENDPOINT', 'timeout': 'timeout', 'max_retries': 'max_retries'}), '(api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT, timeout\n =timeout, max_retries=max_retries)\n', (4008, 4109), False, 'from mistralai.client import MistralClient\n'), ((4188, 4306), 'mistralai.async_client.MistralAsyncClient', 'MistralAsyncClient', ([], {'api_key': 'api_key', 'endpoint': 'DEFAULT_MISTRALAI_ENDPOINT', 'timeout': 'timeout', 'max_retries': 'max_retries'}), '(api_key=api_key, endpoint=DEFAULT_MISTRALAI_ENDPOINT,\n timeout=timeout, max_retries=max_retries)\n', (4206, 4306), False, 'from mistralai.async_client import MistralAsyncClient\n'), ((6793, 6832), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self.chat'], {}), '(self.chat)\n', (6821, 6832), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((8124, 8177), 'llama_index.legacy.llms.generic_utils.stream_chat_to_completion_decorator', 'stream_chat_to_completion_decorator', (['self.stream_chat'], {}), '(self.stream_chat)\n', (8159, 8177), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((9138, 9179), 'llama_index.legacy.llms.generic_utils.achat_to_completion_decorator', 'achat_to_completion_decorator', (['self.achat'], {}), '(self.achat)\n', (9167, 9179), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((10497, 10552), 'llama_index.legacy.llms.generic_utils.astream_chat_to_completion_decorator', 'astream_chat_to_completion_decorator', (['self.astream_chat'], {}), '(self.astream_chat)\n', (10533, 10552), False, 'from llama_index.legacy.llms.generic_utils import achat_to_completion_decorator, astream_chat_to_completion_decorator, chat_to_completion_decorator, get_from_param_or_env, stream_chat_to_completion_decorator\n'), ((3645, 3664), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (3660, 3664), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((6217, 6268), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'x.role', 'content': 'x.content'}), '(role=x.role, content=x.content)\n', (6236, 6268), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((7168, 7231), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'message.role', 'content': 'message.content'}), '(role=message.role, content=message.content)\n', (7187, 7231), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((8517, 8580), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'message.role', 'content': 'message.content'}), '(role=message.role, content=message.content)\n', (8536, 8580), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((9534, 9585), 'mistralai.client.ChatMessage', 'mistral_chatmessage', ([], {'role': 'x.role', 'content': 'x.content'}), '(role=x.role, content=x.content)\n', (9553, 9585), True, 'from mistralai.client import ChatMessage as mistral_chatmessage\n'), ((5163, 5209), 'llama_index.legacy.llms.mistralai_utils.mistralai_modelname_to_contextsize', 'mistralai_modelname_to_contextsize', (['self.model'], {}), '(self.model)\n', (5197, 5209), False, 'from llama_index.legacy.llms.mistralai_utils import mistralai_modelname_to_contextsize\n'), ((6468, 6557), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.choices[0].message.content'}), '(role=MessageRole.ASSISTANT, content=response.choices[0].message\n .content)\n', (6479, 6557), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((8805, 8894), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'MessageRole.ASSISTANT', 'content': 'response.choices[0].message.content'}), '(role=MessageRole.ASSISTANT, content=response.choices[0].message\n .content)\n', (8816, 8894), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((7787, 7826), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (7798, 7826), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n'), ((10147, 10186), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'role': 'role', 'content': 'content'}), '(role=role, content=content)\n', (10158, 10186), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, MessageRole\n')]
"""Base index classes.""" import logging from abc import ABC, abstractmethod from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast from llama_index.legacy.chat_engine.types import BaseChatEngine, ChatMode from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.data_structs.data_structs import IndexStruct from llama_index.legacy.ingestion import run_transformations from llama_index.legacy.schema import BaseNode, Document, IndexNode from llama_index.legacy.service_context import ServiceContext from llama_index.legacy.storage.docstore.types import BaseDocumentStore, RefDocInfo from llama_index.legacy.storage.storage_context import StorageContext IS = TypeVar("IS", bound=IndexStruct) IndexType = TypeVar("IndexType", bound="BaseIndex") logger = logging.getLogger(__name__) class BaseIndex(Generic[IS], ABC): """Base LlamaIndex. Args: nodes (List[Node]): List of nodes to index show_progress (bool): Whether to show tqdm progress bars. Defaults to False. service_context (ServiceContext): Service context container (contains components like LLM, Embeddings, etc.). """ 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, service_context: Optional[ServiceContext] = None, show_progress: bool = False, **kwargs: Any, ) -> None: """Initialize with parameters.""" 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._service_context = service_context or ServiceContext.from_defaults() self._storage_context = storage_context or StorageContext.from_defaults() 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 objects = objects or [] self._object_map = {} for obj in objects: self._object_map[obj.index_id] = obj.obj obj.obj = None # clear the object avoid serialization issues with self._service_context.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) @classmethod def from_documents( cls: Type[IndexType], documents: Sequence[Document], storage_context: Optional[StorageContext] = None, service_context: Optional[ServiceContext] = None, show_progress: bool = False, **kwargs: Any, ) -> IndexType: """Create index from documents. Args: documents (Optional[Sequence[BaseDocument]]): List of documents to build the index from. """ storage_context = storage_context or StorageContext.from_defaults() service_context = service_context or ServiceContext.from_defaults() docstore = storage_context.docstore with service_context.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 service_context.transformations, show_progress=show_progress, **kwargs, ) return cls( nodes=nodes, storage_context=storage_context, service_context=service_context, show_progress=show_progress, **kwargs, ) @property def index_struct(self) -> IS: """Get the index struct.""" return self._index_struct @property def index_id(self) -> str: """Get the index struct.""" return self._index_struct.index_id def set_index_id(self, index_id: str) -> None: """Set the index id. NOTE: if you decide to set the index_id on the index_struct manually, you will need to explicitly call `add_index_struct` on the `index_store` to update the index store. Args: index_id (str): Index id to set. """ # 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: """Get the docstore corresponding to the index.""" return self._docstore @property def service_context(self) -> 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: """Build the index from nodes.""" def build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IS: """Build the index from nodes.""" 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: """Index-specific logic for inserting nodes to the index struct.""" def insert_nodes(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None: """Insert nodes.""" with self._service_context.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: """Insert a document.""" with self._service_context.callback_manager.as_trace("insert"): nodes = run_transformations( [document], self._service_context.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: """Delete a node.""" def delete_nodes( self, node_ids: List[str], delete_from_docstore: bool = False, **delete_kwargs: Any, ) -> None: """Delete a list of nodes from the index. Args: doc_ids (List[str]): A list of doc_ids from the nodes to delete """ 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: """Delete a document from the index. All nodes in the index related to the index will be deleted. Args: doc_id (str): A doc_id of the ingested document """ 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: """Delete a document and it's nodes by using 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: """Update a document and it's corresponding nodes. This is equivalent to deleting the document and then inserting it again. Args: document (Union[BaseDocument, BaseIndex]): document to update insert_kwargs (Dict): kwargs to pass to insert delete_kwargs (Dict): kwargs to pass to delete """ 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: """Update a document and it's corresponding nodes. This is equivalent to deleting the document and then inserting it again. Args: document (Union[BaseDocument, BaseIndex]): document to update insert_kwargs (Dict): kwargs to pass to insert delete_kwargs (Dict): kwargs to pass to delete """ with self._service_context.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]: """Refresh an index with documents that have changed. This allows users to save LLM and Embedding model calls, while only updating documents that have any changes in text or metadata. It will also insert any documents that previously were not stored. """ 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]: """Refresh an index with documents that have changed. This allows users to save LLM and Embedding model calls, while only updating documents that have any changes in text or metadata. It will also insert any documents that previously were not stored. """ with self._service_context.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]: """Retrieve a dict mapping of ingested documents and their nodes+metadata.""" ... @abstractmethod def as_retriever(self, **kwargs: Any) -> BaseRetriever: ... def as_query_engine(self, **kwargs: Any) -> BaseQueryEngine: # NOTE: lazy import from llama_index.legacy.query_engine.retriever_query_engine import ( RetrieverQueryEngine, ) retriever = self.as_retriever(**kwargs) kwargs["retriever"] = retriever if "service_context" not in kwargs: kwargs["service_context"] = self._service_context return RetrieverQueryEngine.from_args(**kwargs) def as_chat_engine( self, chat_mode: ChatMode = ChatMode.BEST, **kwargs: Any ) -> BaseChatEngine: query_engine = self.as_query_engine(**kwargs) if "service_context" not in kwargs: kwargs["service_context"] = self._service_context # 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.legacy.agent import AgentRunner from llama_index.legacy.tools.query_engine import QueryEngineTool # get LLM service_context = cast(ServiceContext, kwargs["service_context"]) llm = service_context.llm # 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.legacy.chat_engine import CondenseQuestionChatEngine return CondenseQuestionChatEngine.from_defaults( query_engine=query_engine, **kwargs, ) elif chat_mode == ChatMode.CONTEXT: from llama_index.legacy.chat_engine import ContextChatEngine return ContextChatEngine.from_defaults( retriever=self.as_retriever(**kwargs), **kwargs, ) elif chat_mode == ChatMode.CONDENSE_PLUS_CONTEXT: from llama_index.legacy.chat_engine import CondensePlusContextChatEngine return CondensePlusContextChatEngine.from_defaults( retriever=self.as_retriever(**kwargs), **kwargs, ) elif chat_mode == ChatMode.SIMPLE: from llama_index.legacy.chat_engine import SimpleChatEngine return SimpleChatEngine.from_defaults( **kwargs, ) else: raise ValueError(f"Unknown chat mode: {chat_mode}") # legacy BaseGPTIndex = BaseIndex
[ "llama_index.legacy.query_engine.retriever_query_engine.RetrieverQueryEngine.from_args", "llama_index.legacy.chat_engine.CondenseQuestionChatEngine.from_defaults", "llama_index.legacy.tools.query_engine.QueryEngineTool.from_defaults", "llama_index.legacy.chat_engine.SimpleChatEngine.from_defaults", "llama_index.legacy.service_context.ServiceContext.from_defaults", "llama_index.legacy.storage.storage_context.StorageContext.from_defaults", "llama_index.legacy.agent.AgentRunner.from_llm", "llama_index.legacy.ingestion.run_transformations" ]
[((793, 825), 'typing.TypeVar', 'TypeVar', (['"""IS"""'], {'bound': 'IndexStruct'}), "('IS', bound=IndexStruct)\n", (800, 825), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((838, 877), 'typing.TypeVar', 'TypeVar', (['"""IndexType"""'], {'bound': '"""BaseIndex"""'}), "('IndexType', bound='BaseIndex')\n", (845, 877), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((888, 915), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (905, 915), False, 'import logging\n'), ((13757, 13797), 'llama_index.legacy.query_engine.retriever_query_engine.RetrieverQueryEngine.from_args', 'RetrieverQueryEngine.from_args', ([], {}), '(**kwargs)\n', (13787, 13797), False, 'from llama_index.legacy.query_engine.retriever_query_engine import RetrieverQueryEngine\n'), ((2626, 2656), 'llama_index.legacy.service_context.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {}), '()\n', (2654, 2656), False, 'from llama_index.legacy.service_context import ServiceContext\n'), ((2708, 2738), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {}), '()\n', (2736, 2738), False, 'from llama_index.legacy.storage.storage_context import StorageContext\n'), ((4137, 4167), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {}), '()\n', (4165, 4167), False, 'from llama_index.legacy.storage.storage_context import StorageContext\n'), ((4213, 4243), 'llama_index.legacy.service_context.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {}), '()\n', (4241, 4243), False, 'from llama_index.legacy.service_context import ServiceContext\n'), ((4493, 4599), 'llama_index.legacy.ingestion.run_transformations', 'run_transformations', (['documents', 'service_context.transformations'], {'show_progress': 'show_progress'}), '(documents, service_context.transformations,\n show_progress=show_progress, **kwargs)\n', (4512, 4599), False, 'from llama_index.legacy.ingestion import run_transformations\n'), ((7604, 7713), 'llama_index.legacy.ingestion.run_transformations', 'run_transformations', (['[document]', 'self._service_context.transformations'], {'show_progress': 'self._show_progress'}), '([document], self._service_context.transformations,\n show_progress=self._show_progress)\n', (7623, 7713), False, 'from llama_index.legacy.ingestion import run_transformations\n'), ((14470, 14517), 'typing.cast', 'cast', (['ServiceContext', "kwargs['service_context']"], {}), "(ServiceContext, kwargs['service_context'])\n", (14474, 14517), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((14632, 14688), 'llama_index.legacy.tools.query_engine.QueryEngineTool.from_defaults', 'QueryEngineTool.from_defaults', ([], {'query_engine': 'query_engine'}), '(query_engine=query_engine)\n', (14661, 14688), False, 'from llama_index.legacy.tools.query_engine import QueryEngineTool\n'), ((14709, 14775), 'llama_index.legacy.agent.AgentRunner.from_llm', 'AgentRunner.from_llm', ([], {'tools': '[query_engine_tool]', 'llm': 'llm'}), '(tools=[query_engine_tool], llm=llm, **kwargs)\n', (14729, 14775), False, 'from llama_index.legacy.agent import AgentRunner\n'), ((14963, 15040), 'llama_index.legacy.chat_engine.CondenseQuestionChatEngine.from_defaults', 'CondenseQuestionChatEngine.from_defaults', ([], {'query_engine': 'query_engine'}), '(query_engine=query_engine, **kwargs)\n', (15003, 15040), False, 'from llama_index.legacy.chat_engine import CondenseQuestionChatEngine\n'), ((15793, 15833), 'llama_index.legacy.chat_engine.SimpleChatEngine.from_defaults', 'SimpleChatEngine.from_defaults', ([], {}), '(**kwargs)\n', (15823, 15833), False, 'from llama_index.legacy.chat_engine import SimpleChatEngine\n')]
"""Base index classes.""" import logging from abc import ABC, abstractmethod from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast from llama_index.legacy.chat_engine.types import BaseChatEngine, ChatMode from llama_index.legacy.core.base_query_engine import BaseQueryEngine from llama_index.legacy.core.base_retriever import BaseRetriever from llama_index.legacy.data_structs.data_structs import IndexStruct from llama_index.legacy.ingestion import run_transformations from llama_index.legacy.schema import BaseNode, Document, IndexNode from llama_index.legacy.service_context import ServiceContext from llama_index.legacy.storage.docstore.types import BaseDocumentStore, RefDocInfo from llama_index.legacy.storage.storage_context import StorageContext IS = TypeVar("IS", bound=IndexStruct) IndexType = TypeVar("IndexType", bound="BaseIndex") logger = logging.getLogger(__name__) class BaseIndex(Generic[IS], ABC): """Base LlamaIndex. Args: nodes (List[Node]): List of nodes to index show_progress (bool): Whether to show tqdm progress bars. Defaults to False. service_context (ServiceContext): Service context container (contains components like LLM, Embeddings, etc.). """ 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, service_context: Optional[ServiceContext] = None, show_progress: bool = False, **kwargs: Any, ) -> None: """Initialize with parameters.""" 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._service_context = service_context or ServiceContext.from_defaults() self._storage_context = storage_context or StorageContext.from_defaults() 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 objects = objects or [] self._object_map = {} for obj in objects: self._object_map[obj.index_id] = obj.obj obj.obj = None # clear the object avoid serialization issues with self._service_context.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) @classmethod def from_documents( cls: Type[IndexType], documents: Sequence[Document], storage_context: Optional[StorageContext] = None, service_context: Optional[ServiceContext] = None, show_progress: bool = False, **kwargs: Any, ) -> IndexType: """Create index from documents. Args: documents (Optional[Sequence[BaseDocument]]): List of documents to build the index from. """ storage_context = storage_context or StorageContext.from_defaults() service_context = service_context or ServiceContext.from_defaults() docstore = storage_context.docstore with service_context.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 service_context.transformations, show_progress=show_progress, **kwargs, ) return cls( nodes=nodes, storage_context=storage_context, service_context=service_context, show_progress=show_progress, **kwargs, ) @property def index_struct(self) -> IS: """Get the index struct.""" return self._index_struct @property def index_id(self) -> str: """Get the index struct.""" return self._index_struct.index_id def set_index_id(self, index_id: str) -> None: """Set the index id. NOTE: if you decide to set the index_id on the index_struct manually, you will need to explicitly call `add_index_struct` on the `index_store` to update the index store. Args: index_id (str): Index id to set. """ # 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: """Get the docstore corresponding to the index.""" return self._docstore @property def service_context(self) -> 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: """Build the index from nodes.""" def build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IS: """Build the index from nodes.""" 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: """Index-specific logic for inserting nodes to the index struct.""" def insert_nodes(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None: """Insert nodes.""" with self._service_context.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: """Insert a document.""" with self._service_context.callback_manager.as_trace("insert"): nodes = run_transformations( [document], self._service_context.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: """Delete a node.""" def delete_nodes( self, node_ids: List[str], delete_from_docstore: bool = False, **delete_kwargs: Any, ) -> None: """Delete a list of nodes from the index. Args: doc_ids (List[str]): A list of doc_ids from the nodes to delete """ 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: """Delete a document from the index. All nodes in the index related to the index will be deleted. Args: doc_id (str): A doc_id of the ingested document """ 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: """Delete a document and it's nodes by using 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: """Update a document and it's corresponding nodes. This is equivalent to deleting the document and then inserting it again. Args: document (Union[BaseDocument, BaseIndex]): document to update insert_kwargs (Dict): kwargs to pass to insert delete_kwargs (Dict): kwargs to pass to delete """ 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: """Update a document and it's corresponding nodes. This is equivalent to deleting the document and then inserting it again. Args: document (Union[BaseDocument, BaseIndex]): document to update insert_kwargs (Dict): kwargs to pass to insert delete_kwargs (Dict): kwargs to pass to delete """ with self._service_context.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]: """Refresh an index with documents that have changed. This allows users to save LLM and Embedding model calls, while only updating documents that have any changes in text or metadata. It will also insert any documents that previously were not stored. """ 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]: """Refresh an index with documents that have changed. This allows users to save LLM and Embedding model calls, while only updating documents that have any changes in text or metadata. It will also insert any documents that previously were not stored. """ with self._service_context.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]: """Retrieve a dict mapping of ingested documents and their nodes+metadata.""" ... @abstractmethod def as_retriever(self, **kwargs: Any) -> BaseRetriever: ... def as_query_engine(self, **kwargs: Any) -> BaseQueryEngine: # NOTE: lazy import from llama_index.legacy.query_engine.retriever_query_engine import ( RetrieverQueryEngine, ) retriever = self.as_retriever(**kwargs) kwargs["retriever"] = retriever if "service_context" not in kwargs: kwargs["service_context"] = self._service_context return RetrieverQueryEngine.from_args(**kwargs) def as_chat_engine( self, chat_mode: ChatMode = ChatMode.BEST, **kwargs: Any ) -> BaseChatEngine: query_engine = self.as_query_engine(**kwargs) if "service_context" not in kwargs: kwargs["service_context"] = self._service_context # 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.legacy.agent import AgentRunner from llama_index.legacy.tools.query_engine import QueryEngineTool # get LLM service_context = cast(ServiceContext, kwargs["service_context"]) llm = service_context.llm # 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.legacy.chat_engine import CondenseQuestionChatEngine return CondenseQuestionChatEngine.from_defaults( query_engine=query_engine, **kwargs, ) elif chat_mode == ChatMode.CONTEXT: from llama_index.legacy.chat_engine import ContextChatEngine return ContextChatEngine.from_defaults( retriever=self.as_retriever(**kwargs), **kwargs, ) elif chat_mode == ChatMode.CONDENSE_PLUS_CONTEXT: from llama_index.legacy.chat_engine import CondensePlusContextChatEngine return CondensePlusContextChatEngine.from_defaults( retriever=self.as_retriever(**kwargs), **kwargs, ) elif chat_mode == ChatMode.SIMPLE: from llama_index.legacy.chat_engine import SimpleChatEngine return SimpleChatEngine.from_defaults( **kwargs, ) else: raise ValueError(f"Unknown chat mode: {chat_mode}") # legacy BaseGPTIndex = BaseIndex
[ "llama_index.legacy.query_engine.retriever_query_engine.RetrieverQueryEngine.from_args", "llama_index.legacy.chat_engine.CondenseQuestionChatEngine.from_defaults", "llama_index.legacy.tools.query_engine.QueryEngineTool.from_defaults", "llama_index.legacy.chat_engine.SimpleChatEngine.from_defaults", "llama_index.legacy.service_context.ServiceContext.from_defaults", "llama_index.legacy.storage.storage_context.StorageContext.from_defaults", "llama_index.legacy.agent.AgentRunner.from_llm", "llama_index.legacy.ingestion.run_transformations" ]
[((793, 825), 'typing.TypeVar', 'TypeVar', (['"""IS"""'], {'bound': 'IndexStruct'}), "('IS', bound=IndexStruct)\n", (800, 825), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((838, 877), 'typing.TypeVar', 'TypeVar', (['"""IndexType"""'], {'bound': '"""BaseIndex"""'}), "('IndexType', bound='BaseIndex')\n", (845, 877), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((888, 915), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (905, 915), False, 'import logging\n'), ((13757, 13797), 'llama_index.legacy.query_engine.retriever_query_engine.RetrieverQueryEngine.from_args', 'RetrieverQueryEngine.from_args', ([], {}), '(**kwargs)\n', (13787, 13797), False, 'from llama_index.legacy.query_engine.retriever_query_engine import RetrieverQueryEngine\n'), ((2626, 2656), 'llama_index.legacy.service_context.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {}), '()\n', (2654, 2656), False, 'from llama_index.legacy.service_context import ServiceContext\n'), ((2708, 2738), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {}), '()\n', (2736, 2738), False, 'from llama_index.legacy.storage.storage_context import StorageContext\n'), ((4137, 4167), 'llama_index.legacy.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {}), '()\n', (4165, 4167), False, 'from llama_index.legacy.storage.storage_context import StorageContext\n'), ((4213, 4243), 'llama_index.legacy.service_context.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {}), '()\n', (4241, 4243), False, 'from llama_index.legacy.service_context import ServiceContext\n'), ((4493, 4599), 'llama_index.legacy.ingestion.run_transformations', 'run_transformations', (['documents', 'service_context.transformations'], {'show_progress': 'show_progress'}), '(documents, service_context.transformations,\n show_progress=show_progress, **kwargs)\n', (4512, 4599), False, 'from llama_index.legacy.ingestion import run_transformations\n'), ((7604, 7713), 'llama_index.legacy.ingestion.run_transformations', 'run_transformations', (['[document]', 'self._service_context.transformations'], {'show_progress': 'self._show_progress'}), '([document], self._service_context.transformations,\n show_progress=self._show_progress)\n', (7623, 7713), False, 'from llama_index.legacy.ingestion import run_transformations\n'), ((14470, 14517), 'typing.cast', 'cast', (['ServiceContext', "kwargs['service_context']"], {}), "(ServiceContext, kwargs['service_context'])\n", (14474, 14517), False, 'from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar, cast\n'), ((14632, 14688), 'llama_index.legacy.tools.query_engine.QueryEngineTool.from_defaults', 'QueryEngineTool.from_defaults', ([], {'query_engine': 'query_engine'}), '(query_engine=query_engine)\n', (14661, 14688), False, 'from llama_index.legacy.tools.query_engine import QueryEngineTool\n'), ((14709, 14775), 'llama_index.legacy.agent.AgentRunner.from_llm', 'AgentRunner.from_llm', ([], {'tools': '[query_engine_tool]', 'llm': 'llm'}), '(tools=[query_engine_tool], llm=llm, **kwargs)\n', (14729, 14775), False, 'from llama_index.legacy.agent import AgentRunner\n'), ((14963, 15040), 'llama_index.legacy.chat_engine.CondenseQuestionChatEngine.from_defaults', 'CondenseQuestionChatEngine.from_defaults', ([], {'query_engine': 'query_engine'}), '(query_engine=query_engine, **kwargs)\n', (15003, 15040), False, 'from llama_index.legacy.chat_engine import CondenseQuestionChatEngine\n'), ((15793, 15833), 'llama_index.legacy.chat_engine.SimpleChatEngine.from_defaults', 'SimpleChatEngine.from_defaults', ([], {}), '(**kwargs)\n', (15823, 15833), False, 'from llama_index.legacy.chat_engine import SimpleChatEngine\n')]
import json from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import ( DEFAULT_TEMPERATURE, ) from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.bedrock_utils import ( BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider, ) from llama_index.legacy.llms.generic_utils import ( completion_response_to_chat_response, stream_completion_response_to_chat_response, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Bedrock(LLM): model: str = Field(description="The modelId of the Bedrock model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_tokens: int = Field(description="The maximum number of tokens to generate.") context_size: int = Field("The maximum number of tokens available for input.") profile_name: Optional[str] = Field( description="The name of aws profile to use. If not given, then the default profile is used." ) aws_access_key_id: Optional[str] = Field( description="AWS Access Key ID to use", exclude=True ) aws_secret_access_key: Optional[str] = Field( description="AWS Secret Access Key to use", exclude=True ) aws_session_token: Optional[str] = Field( description="AWS Session Token to use", exclude=True ) region_name: Optional[str] = Field( description="AWS region name to use. Uses region configured in AWS CLI if not passed", exclude=True, ) botocore_session: Optional[Any] = Field( description="Use this Botocore session instead of creating a new default one.", exclude=True, ) botocore_config: Optional[Any] = Field( description="Custom configuration object to use instead of the default generated one.", exclude=True, ) max_retries: int = Field( default=10, description="The maximum number of API retries.", gt=0 ) timeout: float = Field( default=60.0, description="The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts.", ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the bedrock invokeModel request.", ) _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() _provider: Provider = PrivateAttr() def __init__( self, model: str, temperature: Optional[float] = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = 512, context_size: Optional[int] = None, profile_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, region_name: Optional[str] = None, botocore_session: Optional[Any] = None, client: Optional[Any] = None, timeout: Optional[float] = 60.0, max_retries: Optional[int] = 10, botocore_config: Optional[Any] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: if context_size is None and model not in BEDROCK_FOUNDATION_LLMS: raise ValueError( "`context_size` argument not provided and" "model provided refers to a non-foundation model." " Please specify the context_size" ) session_kwargs = { "profile_name": profile_name, "region_name": region_name, "aws_access_key_id": aws_access_key_id, "aws_secret_access_key": aws_secret_access_key, "aws_session_token": aws_session_token, "botocore_session": botocore_session, } config = None try: import boto3 from botocore.config import Config config = ( Config( retries={"max_attempts": max_retries, "mode": "standard"}, connect_timeout=timeout, read_timeout=timeout, ) if botocore_config is None else botocore_config ) session = boto3.Session(**session_kwargs) except ImportError: raise ImportError( "boto3 package not found, install with" "'pip install boto3'" ) # Prior to general availability, custom boto3 wheel files were # distributed that used the bedrock service to invokeModel. # This check prevents any services still using those wheel files # from breaking if client is not None: self._client = client elif "bedrock-runtime" in session.get_available_services(): self._client = session.client("bedrock-runtime", config=config) else: self._client = session.client("bedrock", config=config) additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) context_size = context_size or BEDROCK_FOUNDATION_LLMS[model] self._provider = get_provider(model) messages_to_prompt = messages_to_prompt or self._provider.messages_to_prompt completion_to_prompt = ( completion_to_prompt or self._provider.completion_to_prompt ) super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, context_size=context_size, profile_name=profile_name, timeout=timeout, max_retries=max_retries, botocore_config=config, additional_kwargs=additional_kwargs, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: """Get class name.""" return "Bedrock_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=self.context_size, num_output=self.max_tokens, is_chat_model=self.model in CHAT_ONLY_MODELS, model_name=self.model, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, self._provider.max_tokens_key: self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: if not formatted: prompt = self.completion_to_prompt(prompt) all_kwargs = self._get_all_kwargs(**kwargs) request_body = self._provider.get_request_body(prompt, all_kwargs) request_body_str = json.dumps(request_body) response = completion_with_retry( client=self._client, model=self.model, request_body=request_body_str, max_retries=self.max_retries, **all_kwargs, )["body"].read() response = json.loads(response) return CompletionResponse( text=self._provider.get_text_from_response(response), raw=response ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: if self.model in BEDROCK_FOUNDATION_LLMS and self.model not in STREAMING_MODELS: raise ValueError(f"Model {self.model} does not support streaming") if not formatted: prompt = self.completion_to_prompt(prompt) all_kwargs = self._get_all_kwargs(**kwargs) request_body = self._provider.get_request_body(prompt, all_kwargs) request_body_str = json.dumps(request_body) response = completion_with_retry( client=self._client, model=self.model, request_body=request_body_str, max_retries=self.max_retries, stream=True, **all_kwargs, )["body"] def gen() -> CompletionResponseGen: content = "" for r in response: r = json.loads(r["chunk"]["bytes"]) content_delta = self._provider.get_text_from_stream_response(r) content += content_delta yield CompletionResponse(text=content, delta=content_delta, raw=r) return gen() @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, formatted=True, **kwargs) return completion_response_to_chat_response(completion_response) def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: prompt = self.messages_to_prompt(messages) completion_response = self.stream_complete(prompt, formatted=True, **kwargs) return stream_completion_response_to_chat_response(completion_response) async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: """Chat asynchronously.""" # TODO: do synchronous chat for now return self.chat(messages, **kwargs) async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise NotImplementedError async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.llms.bedrock_utils.completion_with_retry", "llama_index.legacy.llms.generic_utils.completion_response_to_chat_response", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.bedrock_utils.get_provider" ]
[((1084, 1145), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The modelId of the Bedrock model to use."""'}), "(description='The modelId of the Bedrock model to use.')\n", (1089, 1145), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1171, 1228), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1176, 1228), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1251, 1313), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1256, 1313), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1338, 1396), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['"""The maximum number of tokens available for input."""'], {}), "('The maximum number of tokens available for input.')\n", (1343, 1396), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1431, 1541), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The name of aws profile to use. If not given, then the default profile is used."""'}), "(description=\n 'The name of aws profile to use. If not given, then the default profile is used.'\n )\n", (1436, 1541), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1585, 1644), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Access Key ID to use"""', 'exclude': '(True)'}), "(description='AWS Access Key ID to use', exclude=True)\n", (1590, 1644), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1702, 1765), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Secret Access Key to use"""', 'exclude': '(True)'}), "(description='AWS Secret Access Key to use', exclude=True)\n", (1707, 1765), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1819, 1878), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Session Token to use"""', 'exclude': '(True)'}), "(description='AWS Session Token to use', exclude=True)\n", (1824, 1878), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1926, 2041), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS region name to use. Uses region configured in AWS CLI if not passed"""', 'exclude': '(True)'}), "(description=\n 'AWS region name to use. Uses region configured in AWS CLI if not passed',\n exclude=True)\n", (1931, 2041), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2094, 2202), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Use this Botocore session instead of creating a new default one."""', 'exclude': '(True)'}), "(description=\n 'Use this Botocore session instead of creating a new default one.',\n exclude=True)\n", (2099, 2202), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2254, 2370), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Custom configuration object to use instead of the default generated one."""', 'exclude': '(True)'}), "(description=\n 'Custom configuration object to use instead of the default generated one.',\n exclude=True)\n", (2259, 2370), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2408, 2481), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""', 'gt': '(0)'}), "(default=10, description='The maximum number of API retries.', gt=0)\n", (2413, 2481), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2517, 2665), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(60.0)', 'description': '"""The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts."""'}), "(default=60.0, description=\n 'The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts.'\n )\n", (2522, 2665), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2719, 2821), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the bedrock invokeModel request."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the bedrock invokeModel request.')\n", (2724, 2821), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2860, 2873), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2871, 2873), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2894, 2907), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2905, 2907), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2934, 2947), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2945, 2947), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((7807, 7832), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7830, 7832), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8617, 8642), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8640, 8642), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9840, 9859), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9857, 9859), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6106, 6125), 'llama_index.legacy.llms.bedrock_utils.get_provider', 'get_provider', (['model'], {}), '(model)\n', (6118, 6125), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((7158, 7304), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_size', 'num_output': 'self.max_tokens', 'is_chat_model': '(self.model in CHAT_ONLY_MODELS)', 'model_name': 'self.model'}), '(context_window=self.context_size, num_output=self.max_tokens,\n is_chat_model=self.model in CHAT_ONLY_MODELS, model_name=self.model)\n', (7169, 7304), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((8181, 8205), 'json.dumps', 'json.dumps', (['request_body'], {}), '(request_body)\n', (8191, 8205), False, 'import json\n'), ((8466, 8486), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (8476, 8486), False, 'import json\n'), ((9171, 9195), 'json.dumps', 'json.dumps', (['request_body'], {}), '(request_body)\n', (9181, 9195), False, 'import json\n'), ((10088, 10145), 'llama_index.legacy.llms.generic_utils.completion_response_to_chat_response', 'completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (10124, 10145), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((10406, 10470), 'llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response', 'stream_completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (10449, 10470), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((5180, 5211), 'boto3.Session', 'boto3.Session', ([], {}), '(**session_kwargs)\n', (5193, 5211), False, 'import boto3\n'), ((5991, 6010), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (6006, 6010), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((9215, 9368), 'llama_index.legacy.llms.bedrock_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'model': 'self.model', 'request_body': 'request_body_str', 'max_retries': 'self.max_retries', 'stream': '(True)'}), '(client=self._client, model=self.model, request_body=\n request_body_str, max_retries=self.max_retries, stream=True, **all_kwargs)\n', (9236, 9368), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((4872, 4988), 'botocore.config.Config', 'Config', ([], {'retries': "{'max_attempts': max_retries, 'mode': 'standard'}", 'connect_timeout': 'timeout', 'read_timeout': 'timeout'}), "(retries={'max_attempts': max_retries, 'mode': 'standard'},\n connect_timeout=timeout, read_timeout=timeout)\n", (4878, 4988), False, 'from botocore.config import Config\n'), ((9576, 9607), 'json.loads', 'json.loads', (["r['chunk']['bytes']"], {}), "(r['chunk']['bytes'])\n", (9586, 9607), False, 'import json\n'), ((8225, 8365), 'llama_index.legacy.llms.bedrock_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'model': 'self.model', 'request_body': 'request_body_str', 'max_retries': 'self.max_retries'}), '(client=self._client, model=self.model, request_body=\n request_body_str, max_retries=self.max_retries, **all_kwargs)\n', (8246, 8365), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((9751, 9811), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'content', 'delta': 'content_delta', 'raw': 'r'}), '(text=content, delta=content_delta, raw=r)\n', (9769, 9811), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
import json from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import ( DEFAULT_TEMPERATURE, ) from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.bedrock_utils import ( BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider, ) from llama_index.legacy.llms.generic_utils import ( completion_response_to_chat_response, stream_completion_response_to_chat_response, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class Bedrock(LLM): model: str = Field(description="The modelId of the Bedrock model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_tokens: int = Field(description="The maximum number of tokens to generate.") context_size: int = Field("The maximum number of tokens available for input.") profile_name: Optional[str] = Field( description="The name of aws profile to use. If not given, then the default profile is used." ) aws_access_key_id: Optional[str] = Field( description="AWS Access Key ID to use", exclude=True ) aws_secret_access_key: Optional[str] = Field( description="AWS Secret Access Key to use", exclude=True ) aws_session_token: Optional[str] = Field( description="AWS Session Token to use", exclude=True ) region_name: Optional[str] = Field( description="AWS region name to use. Uses region configured in AWS CLI if not passed", exclude=True, ) botocore_session: Optional[Any] = Field( description="Use this Botocore session instead of creating a new default one.", exclude=True, ) botocore_config: Optional[Any] = Field( description="Custom configuration object to use instead of the default generated one.", exclude=True, ) max_retries: int = Field( default=10, description="The maximum number of API retries.", gt=0 ) timeout: float = Field( default=60.0, description="The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts.", ) additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the bedrock invokeModel request.", ) _client: Any = PrivateAttr() _aclient: Any = PrivateAttr() _provider: Provider = PrivateAttr() def __init__( self, model: str, temperature: Optional[float] = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = 512, context_size: Optional[int] = None, profile_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, region_name: Optional[str] = None, botocore_session: Optional[Any] = None, client: Optional[Any] = None, timeout: Optional[float] = 60.0, max_retries: Optional[int] = 10, botocore_config: Optional[Any] = None, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: if context_size is None and model not in BEDROCK_FOUNDATION_LLMS: raise ValueError( "`context_size` argument not provided and" "model provided refers to a non-foundation model." " Please specify the context_size" ) session_kwargs = { "profile_name": profile_name, "region_name": region_name, "aws_access_key_id": aws_access_key_id, "aws_secret_access_key": aws_secret_access_key, "aws_session_token": aws_session_token, "botocore_session": botocore_session, } config = None try: import boto3 from botocore.config import Config config = ( Config( retries={"max_attempts": max_retries, "mode": "standard"}, connect_timeout=timeout, read_timeout=timeout, ) if botocore_config is None else botocore_config ) session = boto3.Session(**session_kwargs) except ImportError: raise ImportError( "boto3 package not found, install with" "'pip install boto3'" ) # Prior to general availability, custom boto3 wheel files were # distributed that used the bedrock service to invokeModel. # This check prevents any services still using those wheel files # from breaking if client is not None: self._client = client elif "bedrock-runtime" in session.get_available_services(): self._client = session.client("bedrock-runtime", config=config) else: self._client = session.client("bedrock", config=config) additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) context_size = context_size or BEDROCK_FOUNDATION_LLMS[model] self._provider = get_provider(model) messages_to_prompt = messages_to_prompt or self._provider.messages_to_prompt completion_to_prompt = ( completion_to_prompt or self._provider.completion_to_prompt ) super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, context_size=context_size, profile_name=profile_name, timeout=timeout, max_retries=max_retries, botocore_config=config, additional_kwargs=additional_kwargs, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: """Get class name.""" return "Bedrock_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=self.context_size, num_output=self.max_tokens, is_chat_model=self.model in CHAT_ONLY_MODELS, model_name=self.model, ) @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "temperature": self.temperature, self._provider.max_tokens_key: self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } def _get_all_kwargs(self, **kwargs: Any) -> Dict[str, Any]: return { **self._model_kwargs, **kwargs, } @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: if not formatted: prompt = self.completion_to_prompt(prompt) all_kwargs = self._get_all_kwargs(**kwargs) request_body = self._provider.get_request_body(prompt, all_kwargs) request_body_str = json.dumps(request_body) response = completion_with_retry( client=self._client, model=self.model, request_body=request_body_str, max_retries=self.max_retries, **all_kwargs, )["body"].read() response = json.loads(response) return CompletionResponse( text=self._provider.get_text_from_response(response), raw=response ) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: if self.model in BEDROCK_FOUNDATION_LLMS and self.model not in STREAMING_MODELS: raise ValueError(f"Model {self.model} does not support streaming") if not formatted: prompt = self.completion_to_prompt(prompt) all_kwargs = self._get_all_kwargs(**kwargs) request_body = self._provider.get_request_body(prompt, all_kwargs) request_body_str = json.dumps(request_body) response = completion_with_retry( client=self._client, model=self.model, request_body=request_body_str, max_retries=self.max_retries, stream=True, **all_kwargs, )["body"] def gen() -> CompletionResponseGen: content = "" for r in response: r = json.loads(r["chunk"]["bytes"]) content_delta = self._provider.get_text_from_stream_response(r) content += content_delta yield CompletionResponse(text=content, delta=content_delta, raw=r) return gen() @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, formatted=True, **kwargs) return completion_response_to_chat_response(completion_response) def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: prompt = self.messages_to_prompt(messages) completion_response = self.stream_complete(prompt, formatted=True, **kwargs) return stream_completion_response_to_chat_response(completion_response) async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: """Chat asynchronously.""" # TODO: do synchronous chat for now return self.chat(messages, **kwargs) async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: raise NotImplementedError async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.llms.bedrock_utils.completion_with_retry", "llama_index.legacy.llms.generic_utils.completion_response_to_chat_response", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.core.llms.types.CompletionResponse", "llama_index.legacy.llms.bedrock_utils.get_provider" ]
[((1084, 1145), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The modelId of the Bedrock model to use."""'}), "(description='The modelId of the Bedrock model to use.')\n", (1089, 1145), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1171, 1228), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (1176, 1228), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1251, 1313), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1256, 1313), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1338, 1396), 'llama_index.legacy.bridge.pydantic.Field', 'Field', (['"""The maximum number of tokens available for input."""'], {}), "('The maximum number of tokens available for input.')\n", (1343, 1396), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1431, 1541), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The name of aws profile to use. If not given, then the default profile is used."""'}), "(description=\n 'The name of aws profile to use. If not given, then the default profile is used.'\n )\n", (1436, 1541), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1585, 1644), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Access Key ID to use"""', 'exclude': '(True)'}), "(description='AWS Access Key ID to use', exclude=True)\n", (1590, 1644), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1702, 1765), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Secret Access Key to use"""', 'exclude': '(True)'}), "(description='AWS Secret Access Key to use', exclude=True)\n", (1707, 1765), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1819, 1878), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS Session Token to use"""', 'exclude': '(True)'}), "(description='AWS Session Token to use', exclude=True)\n", (1824, 1878), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1926, 2041), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""AWS region name to use. Uses region configured in AWS CLI if not passed"""', 'exclude': '(True)'}), "(description=\n 'AWS region name to use. Uses region configured in AWS CLI if not passed',\n exclude=True)\n", (1931, 2041), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2094, 2202), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Use this Botocore session instead of creating a new default one."""', 'exclude': '(True)'}), "(description=\n 'Use this Botocore session instead of creating a new default one.',\n exclude=True)\n", (2099, 2202), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2254, 2370), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Custom configuration object to use instead of the default generated one."""', 'exclude': '(True)'}), "(description=\n 'Custom configuration object to use instead of the default generated one.',\n exclude=True)\n", (2259, 2370), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2408, 2481), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(10)', 'description': '"""The maximum number of API retries."""', 'gt': '(0)'}), "(default=10, description='The maximum number of API retries.', gt=0)\n", (2413, 2481), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2517, 2665), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(60.0)', 'description': '"""The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts."""'}), "(default=60.0, description=\n 'The timeout for the Bedrock API request in seconds. It will be used for both connect and read timeouts.'\n )\n", (2522, 2665), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2719, 2821), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the bedrock invokeModel request."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the bedrock invokeModel request.')\n", (2724, 2821), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2860, 2873), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2871, 2873), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2894, 2907), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2905, 2907), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((2934, 2947), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (2945, 2947), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((7807, 7832), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7830, 7832), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((8617, 8642), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (8640, 8642), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((9840, 9859), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9857, 9859), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6106, 6125), 'llama_index.legacy.llms.bedrock_utils.get_provider', 'get_provider', (['model'], {}), '(model)\n', (6118, 6125), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((7158, 7304), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_size', 'num_output': 'self.max_tokens', 'is_chat_model': '(self.model in CHAT_ONLY_MODELS)', 'model_name': 'self.model'}), '(context_window=self.context_size, num_output=self.max_tokens,\n is_chat_model=self.model in CHAT_ONLY_MODELS, model_name=self.model)\n', (7169, 7304), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((8181, 8205), 'json.dumps', 'json.dumps', (['request_body'], {}), '(request_body)\n', (8191, 8205), False, 'import json\n'), ((8466, 8486), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (8476, 8486), False, 'import json\n'), ((9171, 9195), 'json.dumps', 'json.dumps', (['request_body'], {}), '(request_body)\n', (9181, 9195), False, 'import json\n'), ((10088, 10145), 'llama_index.legacy.llms.generic_utils.completion_response_to_chat_response', 'completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (10124, 10145), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((10406, 10470), 'llama_index.legacy.llms.generic_utils.stream_completion_response_to_chat_response', 'stream_completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (10449, 10470), False, 'from llama_index.legacy.llms.generic_utils import completion_response_to_chat_response, stream_completion_response_to_chat_response\n'), ((5180, 5211), 'boto3.Session', 'boto3.Session', ([], {}), '(**session_kwargs)\n', (5193, 5211), False, 'import boto3\n'), ((5991, 6010), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (6006, 6010), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((9215, 9368), 'llama_index.legacy.llms.bedrock_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'model': 'self.model', 'request_body': 'request_body_str', 'max_retries': 'self.max_retries', 'stream': '(True)'}), '(client=self._client, model=self.model, request_body=\n request_body_str, max_retries=self.max_retries, stream=True, **all_kwargs)\n', (9236, 9368), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((4872, 4988), 'botocore.config.Config', 'Config', ([], {'retries': "{'max_attempts': max_retries, 'mode': 'standard'}", 'connect_timeout': 'timeout', 'read_timeout': 'timeout'}), "(retries={'max_attempts': max_retries, 'mode': 'standard'},\n connect_timeout=timeout, read_timeout=timeout)\n", (4878, 4988), False, 'from botocore.config import Config\n'), ((9576, 9607), 'json.loads', 'json.loads', (["r['chunk']['bytes']"], {}), "(r['chunk']['bytes'])\n", (9586, 9607), False, 'import json\n'), ((8225, 8365), 'llama_index.legacy.llms.bedrock_utils.completion_with_retry', 'completion_with_retry', ([], {'client': 'self._client', 'model': 'self.model', 'request_body': 'request_body_str', 'max_retries': 'self.max_retries'}), '(client=self._client, model=self.model, request_body=\n request_body_str, max_retries=self.max_retries, **all_kwargs)\n', (8246, 8365), False, 'from llama_index.legacy.llms.bedrock_utils import BEDROCK_FOUNDATION_LLMS, CHAT_ONLY_MODELS, STREAMING_MODELS, Provider, completion_with_retry, get_provider\n'), ((9751, 9811), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'content', 'delta': 'content_delta', 'raw': 'r'}), '(text=content, delta=content_delta, raw=r)\n', (9769, 9811), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "BraintrustCodaHelpDeskDataset", "./braintrust_codahdd" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 344), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""BraintrustCodaHelpDeskDataset"""', '"""./braintrust_codahdd"""'], {}), "('BraintrustCodaHelpDeskDataset', './braintrust_codahdd')\n", (287, 344), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((403, 455), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (434, 455), False, 'from llama_index.core import VectorStoreIndex\n'), ((548, 603), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (567, 603), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1454, 1478), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1476, 1478), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "BraintrustCodaHelpDeskDataset", "./braintrust_codahdd" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 344), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""BraintrustCodaHelpDeskDataset"""', '"""./braintrust_codahdd"""'], {}), "('BraintrustCodaHelpDeskDataset', './braintrust_codahdd')\n", (287, 344), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((403, 455), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (434, 455), False, 'from llama_index.core import VectorStoreIndex\n'), ((548, 603), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (567, 603), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1454, 1478), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1476, 1478), False, 'import asyncio\n')]
from typing import Any, Dict, Optional from llama_index.legacy.bridge.pydantic import Field from llama_index.legacy.constants import ( DEFAULT_NUM_OUTPUTS, DEFAULT_TEMPERATURE, ) from llama_index.legacy.core.llms.types import LLMMetadata from llama_index.legacy.llms.generic_utils import get_from_param_or_env from llama_index.legacy.llms.openai_like import OpenAILike DEFAULT_API_BASE = "https://router.neutrinoapp.com/api/llm-router" DEFAULT_ROUTER = "default" MAX_CONTEXT_WINDOW = 200000 class Neutrino(OpenAILike): model: str = Field( description="The Neutrino router to use. See https://docs.neutrinoapp.com/router for details." ) context_window: int = Field( default=MAX_CONTEXT_WINDOW, description="The maximum number of context tokens for the model. Defaults to the largest supported model (Claude).", gt=0, ) is_chat_model: bool = Field( default=True, description=LLMMetadata.__fields__["is_chat_model"].field_info.description, ) def __init__( self, model: Optional[str] = None, router: str = DEFAULT_ROUTER, temperature: float = DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_NUM_OUTPUTS, additional_kwargs: Optional[Dict[str, Any]] = None, max_retries: int = 5, api_base: Optional[str] = DEFAULT_API_BASE, api_key: Optional[str] = None, **kwargs: Any, ) -> None: additional_kwargs = additional_kwargs or {} api_base = get_from_param_or_env("api_base", api_base, "NEUTRINO_API_BASE") api_key = get_from_param_or_env("api_key", api_key, "NEUTRINO_API_KEY") model = model or router super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, api_base=api_base, api_key=api_key, additional_kwargs=additional_kwargs, max_retries=max_retries, **kwargs, ) @classmethod def class_name(cls) -> str: return "Neutrino_LLM"
[ "llama_index.legacy.llms.generic_utils.get_from_param_or_env", "llama_index.legacy.bridge.pydantic.Field" ]
[((548, 659), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Neutrino router to use. See https://docs.neutrinoapp.com/router for details."""'}), "(description=\n 'The Neutrino router to use. See https://docs.neutrinoapp.com/router for details.'\n )\n", (553, 659), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((690, 856), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'MAX_CONTEXT_WINDOW', 'description': '"""The maximum number of context tokens for the model. Defaults to the largest supported model (Claude)."""', 'gt': '(0)'}), "(default=MAX_CONTEXT_WINDOW, description=\n 'The maximum number of context tokens for the model. Defaults to the largest supported model (Claude).'\n , gt=0)\n", (695, 856), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((904, 1004), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(True)', 'description': "LLMMetadata.__fields__['is_chat_model'].field_info.description"}), "(default=True, description=LLMMetadata.__fields__['is_chat_model'].\n field_info.description)\n", (909, 1004), False, 'from llama_index.legacy.bridge.pydantic import Field\n'), ((1519, 1583), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_base"""', 'api_base', '"""NEUTRINO_API_BASE"""'], {}), "('api_base', api_base, 'NEUTRINO_API_BASE')\n", (1540, 1583), False, 'from llama_index.legacy.llms.generic_utils import get_from_param_or_env\n'), ((1602, 1663), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_key"""', 'api_key', '"""NEUTRINO_API_KEY"""'], {}), "('api_key', api_key, 'NEUTRINO_API_KEY')\n", (1623, 1663), False, 'from llama_index.legacy.llms.generic_utils import get_from_param_or_env\n')]
"""Tree-based index.""" from enum import Enum from typing import Any, Dict, Optional, Sequence, Union from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.embeddings.base import BaseEmbedding # from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder from llama_index.core.indices.tree.inserter import TreeIndexInserter from llama_index.core.llms.llm import LLM from llama_index.core.prompts import BasePromptTemplate from llama_index.core.prompts.default_prompts import ( DEFAULT_INSERT_PROMPT, DEFAULT_SUMMARY_PROMPT, ) from llama_index.core.schema import BaseNode, IndexNode from llama_index.core.service_context import ServiceContext from llama_index.core.settings import ( Settings, embed_model_from_settings_or_context, llm_from_settings_or_context, ) from llama_index.core.storage.docstore.types import RefDocInfo class TreeRetrieverMode(str, Enum): SELECT_LEAF = "select_leaf" SELECT_LEAF_EMBEDDING = "select_leaf_embedding" ALL_LEAF = "all_leaf" ROOT = "root" REQUIRE_TREE_MODES = { TreeRetrieverMode.SELECT_LEAF, TreeRetrieverMode.SELECT_LEAF_EMBEDDING, TreeRetrieverMode.ROOT, } class TreeIndex(BaseIndex[IndexGraph]): """Tree Index. The tree index is a tree-structured index, where each node is a summary of the children nodes. During index construction, the tree is constructed in a bottoms-up fashion until we end up with a set of root_nodes. There are a few different options during query time (see :ref:`Ref-Query`). The main option is to traverse down the tree from the root nodes. A secondary answer is to directly synthesize the answer from the root nodes. Args: summary_template (Optional[BasePromptTemplate]): A Summarization Prompt (see :ref:`Prompt-Templates`). insert_prompt (Optional[BasePromptTemplate]): An Tree Insertion Prompt (see :ref:`Prompt-Templates`). num_children (int): The number of children each node should have. build_tree (bool): Whether to build the tree during index construction. show_progress (bool): Whether to show progress bars. Defaults to False. """ index_struct_cls = IndexGraph def __init__( self, nodes: Optional[Sequence[BaseNode]] = None, objects: Optional[Sequence[IndexNode]] = None, index_struct: Optional[IndexGraph] = None, llm: Optional[LLM] = None, summary_template: Optional[BasePromptTemplate] = None, insert_prompt: Optional[BasePromptTemplate] = None, num_children: int = 10, build_tree: bool = True, use_async: bool = False, show_progress: bool = False, # deprecated service_context: Optional[ServiceContext] = None, **kwargs: Any, ) -> None: """Initialize params.""" # need to set parameters before building index in base class. self.num_children = num_children self.summary_template = summary_template or DEFAULT_SUMMARY_PROMPT self.insert_prompt: BasePromptTemplate = insert_prompt or DEFAULT_INSERT_PROMPT self.build_tree = build_tree self._use_async = use_async self._llm = llm or llm_from_settings_or_context(Settings, service_context) super().__init__( nodes=nodes, index_struct=index_struct, service_context=service_context, show_progress=show_progress, objects=objects, **kwargs, ) def as_retriever( self, retriever_mode: Union[str, TreeRetrieverMode] = TreeRetrieverMode.SELECT_LEAF, embed_model: Optional[BaseEmbedding] = None, **kwargs: Any, ) -> BaseRetriever: # NOTE: lazy import from llama_index.core.indices.tree.all_leaf_retriever import ( TreeAllLeafRetriever, ) from llama_index.core.indices.tree.select_leaf_embedding_retriever import ( TreeSelectLeafEmbeddingRetriever, ) from llama_index.core.indices.tree.select_leaf_retriever import ( TreeSelectLeafRetriever, ) from llama_index.core.indices.tree.tree_root_retriever import ( TreeRootRetriever, ) self._validate_build_tree_required(TreeRetrieverMode(retriever_mode)) if retriever_mode == TreeRetrieverMode.SELECT_LEAF: return TreeSelectLeafRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.SELECT_LEAF_EMBEDDING: embed_model = embed_model or embed_model_from_settings_or_context( Settings, self._service_context ) return TreeSelectLeafEmbeddingRetriever( self, embed_model=embed_model, object_map=self._object_map, **kwargs ) elif retriever_mode == TreeRetrieverMode.ROOT: return TreeRootRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.ALL_LEAF: return TreeAllLeafRetriever(self, object_map=self._object_map, **kwargs) else: raise ValueError(f"Unknown retriever mode: {retriever_mode}") def _validate_build_tree_required(self, retriever_mode: TreeRetrieverMode) -> None: """Check if index supports modes that require trees.""" if retriever_mode in REQUIRE_TREE_MODES and not self.build_tree: raise ValueError( "Index was constructed without building trees, " f"but retriever mode {retriever_mode} requires trees." ) def _build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IndexGraph: """Build the index from nodes.""" index_builder = GPTTreeIndexBuilder( self.num_children, self.summary_template, service_context=self.service_context, llm=self._llm, use_async=self._use_async, show_progress=self._show_progress, docstore=self._docstore, ) return index_builder.build_from_nodes(nodes, build_tree=self.build_tree) def _insert(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None: """Insert a document.""" # TODO: allow to customize insert prompt inserter = TreeIndexInserter( self.index_struct, service_context=self.service_context, llm=self._llm, num_children=self.num_children, insert_prompt=self.insert_prompt, summary_prompt=self.summary_template, docstore=self._docstore, ) inserter.insert(nodes) def _delete_node(self, node_id: str, **delete_kwargs: Any) -> None: """Delete a node.""" raise NotImplementedError("Delete not implemented for tree index.") @property def ref_doc_info(self) -> Dict[str, RefDocInfo]: """Retrieve a dict mapping of ingested documents and their nodes+metadata.""" node_doc_ids = list(self.index_struct.all_nodes.values()) nodes = self.docstore.get_nodes(node_doc_ids) all_ref_doc_info = {} for node in nodes: ref_node = node.source_node if not ref_node: continue ref_doc_info = self.docstore.get_ref_doc_info(ref_node.node_id) if not ref_doc_info: continue all_ref_doc_info[ref_node.node_id] = ref_doc_info return all_ref_doc_info # legacy GPTTreeIndex = TreeIndex
[ "llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever", "llama_index.core.settings.embed_model_from_settings_or_context", "llama_index.core.indices.tree.inserter.TreeIndexInserter", "llama_index.core.settings.llm_from_settings_or_context", "llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever", "llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever", "llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder", "llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever" ]
[((5992, 6202), 'llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder', 'GPTTreeIndexBuilder', (['self.num_children', 'self.summary_template'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'use_async': 'self._use_async', 'show_progress': 'self._show_progress', 'docstore': 'self._docstore'}), '(self.num_children, self.summary_template,\n service_context=self.service_context, llm=self._llm, use_async=self.\n _use_async, show_progress=self._show_progress, docstore=self._docstore)\n', (6011, 6202), False, 'from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder\n'), ((6552, 6784), 'llama_index.core.indices.tree.inserter.TreeIndexInserter', 'TreeIndexInserter', (['self.index_struct'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'num_children': 'self.num_children', 'insert_prompt': 'self.insert_prompt', 'summary_prompt': 'self.summary_template', 'docstore': 'self._docstore'}), '(self.index_struct, service_context=self.service_context,\n llm=self._llm, num_children=self.num_children, insert_prompt=self.\n insert_prompt, summary_prompt=self.summary_template, docstore=self.\n _docstore)\n', (6569, 6784), False, 'from llama_index.core.indices.tree.inserter import TreeIndexInserter\n'), ((3443, 3498), 'llama_index.core.settings.llm_from_settings_or_context', 'llm_from_settings_or_context', (['Settings', 'service_context'], {}), '(Settings, service_context)\n', (3471, 3498), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((4636, 4704), 'llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever', 'TreeSelectLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (4659, 4704), False, 'from llama_index.core.indices.tree.select_leaf_retriever import TreeSelectLeafRetriever\n'), ((4937, 5044), 'llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever', 'TreeSelectLeafEmbeddingRetriever', (['self'], {'embed_model': 'embed_model', 'object_map': 'self._object_map'}), '(self, embed_model=embed_model, object_map=\n self._object_map, **kwargs)\n', (4969, 5044), False, 'from llama_index.core.indices.tree.select_leaf_embedding_retriever import TreeSelectLeafEmbeddingRetriever\n'), ((4818, 4887), 'llama_index.core.settings.embed_model_from_settings_or_context', 'embed_model_from_settings_or_context', (['Settings', 'self._service_context'], {}), '(Settings, self._service_context)\n', (4854, 4887), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((5144, 5206), 'llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever', 'TreeRootRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5161, 5206), False, 'from llama_index.core.indices.tree.tree_root_retriever import TreeRootRetriever\n'), ((5285, 5350), 'llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever', 'TreeAllLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5305, 5350), False, 'from llama_index.core.indices.tree.all_leaf_retriever import TreeAllLeafRetriever\n')]
"""Tree-based index.""" from enum import Enum from typing import Any, Dict, Optional, Sequence, Union from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.embeddings.base import BaseEmbedding # from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder from llama_index.core.indices.tree.inserter import TreeIndexInserter from llama_index.core.llms.llm import LLM from llama_index.core.prompts import BasePromptTemplate from llama_index.core.prompts.default_prompts import ( DEFAULT_INSERT_PROMPT, DEFAULT_SUMMARY_PROMPT, ) from llama_index.core.schema import BaseNode, IndexNode from llama_index.core.service_context import ServiceContext from llama_index.core.settings import ( Settings, embed_model_from_settings_or_context, llm_from_settings_or_context, ) from llama_index.core.storage.docstore.types import RefDocInfo class TreeRetrieverMode(str, Enum): SELECT_LEAF = "select_leaf" SELECT_LEAF_EMBEDDING = "select_leaf_embedding" ALL_LEAF = "all_leaf" ROOT = "root" REQUIRE_TREE_MODES = { TreeRetrieverMode.SELECT_LEAF, TreeRetrieverMode.SELECT_LEAF_EMBEDDING, TreeRetrieverMode.ROOT, } class TreeIndex(BaseIndex[IndexGraph]): """Tree Index. The tree index is a tree-structured index, where each node is a summary of the children nodes. During index construction, the tree is constructed in a bottoms-up fashion until we end up with a set of root_nodes. There are a few different options during query time (see :ref:`Ref-Query`). The main option is to traverse down the tree from the root nodes. A secondary answer is to directly synthesize the answer from the root nodes. Args: summary_template (Optional[BasePromptTemplate]): A Summarization Prompt (see :ref:`Prompt-Templates`). insert_prompt (Optional[BasePromptTemplate]): An Tree Insertion Prompt (see :ref:`Prompt-Templates`). num_children (int): The number of children each node should have. build_tree (bool): Whether to build the tree during index construction. show_progress (bool): Whether to show progress bars. Defaults to False. """ index_struct_cls = IndexGraph def __init__( self, nodes: Optional[Sequence[BaseNode]] = None, objects: Optional[Sequence[IndexNode]] = None, index_struct: Optional[IndexGraph] = None, llm: Optional[LLM] = None, summary_template: Optional[BasePromptTemplate] = None, insert_prompt: Optional[BasePromptTemplate] = None, num_children: int = 10, build_tree: bool = True, use_async: bool = False, show_progress: bool = False, # deprecated service_context: Optional[ServiceContext] = None, **kwargs: Any, ) -> None: """Initialize params.""" # need to set parameters before building index in base class. self.num_children = num_children self.summary_template = summary_template or DEFAULT_SUMMARY_PROMPT self.insert_prompt: BasePromptTemplate = insert_prompt or DEFAULT_INSERT_PROMPT self.build_tree = build_tree self._use_async = use_async self._llm = llm or llm_from_settings_or_context(Settings, service_context) super().__init__( nodes=nodes, index_struct=index_struct, service_context=service_context, show_progress=show_progress, objects=objects, **kwargs, ) def as_retriever( self, retriever_mode: Union[str, TreeRetrieverMode] = TreeRetrieverMode.SELECT_LEAF, embed_model: Optional[BaseEmbedding] = None, **kwargs: Any, ) -> BaseRetriever: # NOTE: lazy import from llama_index.core.indices.tree.all_leaf_retriever import ( TreeAllLeafRetriever, ) from llama_index.core.indices.tree.select_leaf_embedding_retriever import ( TreeSelectLeafEmbeddingRetriever, ) from llama_index.core.indices.tree.select_leaf_retriever import ( TreeSelectLeafRetriever, ) from llama_index.core.indices.tree.tree_root_retriever import ( TreeRootRetriever, ) self._validate_build_tree_required(TreeRetrieverMode(retriever_mode)) if retriever_mode == TreeRetrieverMode.SELECT_LEAF: return TreeSelectLeafRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.SELECT_LEAF_EMBEDDING: embed_model = embed_model or embed_model_from_settings_or_context( Settings, self._service_context ) return TreeSelectLeafEmbeddingRetriever( self, embed_model=embed_model, object_map=self._object_map, **kwargs ) elif retriever_mode == TreeRetrieverMode.ROOT: return TreeRootRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.ALL_LEAF: return TreeAllLeafRetriever(self, object_map=self._object_map, **kwargs) else: raise ValueError(f"Unknown retriever mode: {retriever_mode}") def _validate_build_tree_required(self, retriever_mode: TreeRetrieverMode) -> None: """Check if index supports modes that require trees.""" if retriever_mode in REQUIRE_TREE_MODES and not self.build_tree: raise ValueError( "Index was constructed without building trees, " f"but retriever mode {retriever_mode} requires trees." ) def _build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IndexGraph: """Build the index from nodes.""" index_builder = GPTTreeIndexBuilder( self.num_children, self.summary_template, service_context=self.service_context, llm=self._llm, use_async=self._use_async, show_progress=self._show_progress, docstore=self._docstore, ) return index_builder.build_from_nodes(nodes, build_tree=self.build_tree) def _insert(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None: """Insert a document.""" # TODO: allow to customize insert prompt inserter = TreeIndexInserter( self.index_struct, service_context=self.service_context, llm=self._llm, num_children=self.num_children, insert_prompt=self.insert_prompt, summary_prompt=self.summary_template, docstore=self._docstore, ) inserter.insert(nodes) def _delete_node(self, node_id: str, **delete_kwargs: Any) -> None: """Delete a node.""" raise NotImplementedError("Delete not implemented for tree index.") @property def ref_doc_info(self) -> Dict[str, RefDocInfo]: """Retrieve a dict mapping of ingested documents and their nodes+metadata.""" node_doc_ids = list(self.index_struct.all_nodes.values()) nodes = self.docstore.get_nodes(node_doc_ids) all_ref_doc_info = {} for node in nodes: ref_node = node.source_node if not ref_node: continue ref_doc_info = self.docstore.get_ref_doc_info(ref_node.node_id) if not ref_doc_info: continue all_ref_doc_info[ref_node.node_id] = ref_doc_info return all_ref_doc_info # legacy GPTTreeIndex = TreeIndex
[ "llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever", "llama_index.core.settings.embed_model_from_settings_or_context", "llama_index.core.indices.tree.inserter.TreeIndexInserter", "llama_index.core.settings.llm_from_settings_or_context", "llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever", "llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever", "llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder", "llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever" ]
[((5992, 6202), 'llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder', 'GPTTreeIndexBuilder', (['self.num_children', 'self.summary_template'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'use_async': 'self._use_async', 'show_progress': 'self._show_progress', 'docstore': 'self._docstore'}), '(self.num_children, self.summary_template,\n service_context=self.service_context, llm=self._llm, use_async=self.\n _use_async, show_progress=self._show_progress, docstore=self._docstore)\n', (6011, 6202), False, 'from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder\n'), ((6552, 6784), 'llama_index.core.indices.tree.inserter.TreeIndexInserter', 'TreeIndexInserter', (['self.index_struct'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'num_children': 'self.num_children', 'insert_prompt': 'self.insert_prompt', 'summary_prompt': 'self.summary_template', 'docstore': 'self._docstore'}), '(self.index_struct, service_context=self.service_context,\n llm=self._llm, num_children=self.num_children, insert_prompt=self.\n insert_prompt, summary_prompt=self.summary_template, docstore=self.\n _docstore)\n', (6569, 6784), False, 'from llama_index.core.indices.tree.inserter import TreeIndexInserter\n'), ((3443, 3498), 'llama_index.core.settings.llm_from_settings_or_context', 'llm_from_settings_or_context', (['Settings', 'service_context'], {}), '(Settings, service_context)\n', (3471, 3498), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((4636, 4704), 'llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever', 'TreeSelectLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (4659, 4704), False, 'from llama_index.core.indices.tree.select_leaf_retriever import TreeSelectLeafRetriever\n'), ((4937, 5044), 'llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever', 'TreeSelectLeafEmbeddingRetriever', (['self'], {'embed_model': 'embed_model', 'object_map': 'self._object_map'}), '(self, embed_model=embed_model, object_map=\n self._object_map, **kwargs)\n', (4969, 5044), False, 'from llama_index.core.indices.tree.select_leaf_embedding_retriever import TreeSelectLeafEmbeddingRetriever\n'), ((4818, 4887), 'llama_index.core.settings.embed_model_from_settings_or_context', 'embed_model_from_settings_or_context', (['Settings', 'self._service_context'], {}), '(Settings, self._service_context)\n', (4854, 4887), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((5144, 5206), 'llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever', 'TreeRootRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5161, 5206), False, 'from llama_index.core.indices.tree.tree_root_retriever import TreeRootRetriever\n'), ((5285, 5350), 'llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever', 'TreeAllLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5305, 5350), False, 'from llama_index.core.indices.tree.all_leaf_retriever import TreeAllLeafRetriever\n')]
"""Tree-based index.""" from enum import Enum from typing import Any, Dict, Optional, Sequence, Union from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.base.embeddings.base import BaseEmbedding # from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.data_structs.data_structs import IndexGraph from llama_index.core.indices.base import BaseIndex from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder from llama_index.core.indices.tree.inserter import TreeIndexInserter from llama_index.core.llms.llm import LLM from llama_index.core.prompts import BasePromptTemplate from llama_index.core.prompts.default_prompts import ( DEFAULT_INSERT_PROMPT, DEFAULT_SUMMARY_PROMPT, ) from llama_index.core.schema import BaseNode, IndexNode from llama_index.core.service_context import ServiceContext from llama_index.core.settings import ( Settings, embed_model_from_settings_or_context, llm_from_settings_or_context, ) from llama_index.core.storage.docstore.types import RefDocInfo class TreeRetrieverMode(str, Enum): SELECT_LEAF = "select_leaf" SELECT_LEAF_EMBEDDING = "select_leaf_embedding" ALL_LEAF = "all_leaf" ROOT = "root" REQUIRE_TREE_MODES = { TreeRetrieverMode.SELECT_LEAF, TreeRetrieverMode.SELECT_LEAF_EMBEDDING, TreeRetrieverMode.ROOT, } class TreeIndex(BaseIndex[IndexGraph]): """Tree Index. The tree index is a tree-structured index, where each node is a summary of the children nodes. During index construction, the tree is constructed in a bottoms-up fashion until we end up with a set of root_nodes. There are a few different options during query time (see :ref:`Ref-Query`). The main option is to traverse down the tree from the root nodes. A secondary answer is to directly synthesize the answer from the root nodes. Args: summary_template (Optional[BasePromptTemplate]): A Summarization Prompt (see :ref:`Prompt-Templates`). insert_prompt (Optional[BasePromptTemplate]): An Tree Insertion Prompt (see :ref:`Prompt-Templates`). num_children (int): The number of children each node should have. build_tree (bool): Whether to build the tree during index construction. show_progress (bool): Whether to show progress bars. Defaults to False. """ index_struct_cls = IndexGraph def __init__( self, nodes: Optional[Sequence[BaseNode]] = None, objects: Optional[Sequence[IndexNode]] = None, index_struct: Optional[IndexGraph] = None, llm: Optional[LLM] = None, summary_template: Optional[BasePromptTemplate] = None, insert_prompt: Optional[BasePromptTemplate] = None, num_children: int = 10, build_tree: bool = True, use_async: bool = False, show_progress: bool = False, # deprecated service_context: Optional[ServiceContext] = None, **kwargs: Any, ) -> None: """Initialize params.""" # need to set parameters before building index in base class. self.num_children = num_children self.summary_template = summary_template or DEFAULT_SUMMARY_PROMPT self.insert_prompt: BasePromptTemplate = insert_prompt or DEFAULT_INSERT_PROMPT self.build_tree = build_tree self._use_async = use_async self._llm = llm or llm_from_settings_or_context(Settings, service_context) super().__init__( nodes=nodes, index_struct=index_struct, service_context=service_context, show_progress=show_progress, objects=objects, **kwargs, ) def as_retriever( self, retriever_mode: Union[str, TreeRetrieverMode] = TreeRetrieverMode.SELECT_LEAF, embed_model: Optional[BaseEmbedding] = None, **kwargs: Any, ) -> BaseRetriever: # NOTE: lazy import from llama_index.core.indices.tree.all_leaf_retriever import ( TreeAllLeafRetriever, ) from llama_index.core.indices.tree.select_leaf_embedding_retriever import ( TreeSelectLeafEmbeddingRetriever, ) from llama_index.core.indices.tree.select_leaf_retriever import ( TreeSelectLeafRetriever, ) from llama_index.core.indices.tree.tree_root_retriever import ( TreeRootRetriever, ) self._validate_build_tree_required(TreeRetrieverMode(retriever_mode)) if retriever_mode == TreeRetrieverMode.SELECT_LEAF: return TreeSelectLeafRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.SELECT_LEAF_EMBEDDING: embed_model = embed_model or embed_model_from_settings_or_context( Settings, self._service_context ) return TreeSelectLeafEmbeddingRetriever( self, embed_model=embed_model, object_map=self._object_map, **kwargs ) elif retriever_mode == TreeRetrieverMode.ROOT: return TreeRootRetriever(self, object_map=self._object_map, **kwargs) elif retriever_mode == TreeRetrieverMode.ALL_LEAF: return TreeAllLeafRetriever(self, object_map=self._object_map, **kwargs) else: raise ValueError(f"Unknown retriever mode: {retriever_mode}") def _validate_build_tree_required(self, retriever_mode: TreeRetrieverMode) -> None: """Check if index supports modes that require trees.""" if retriever_mode in REQUIRE_TREE_MODES and not self.build_tree: raise ValueError( "Index was constructed without building trees, " f"but retriever mode {retriever_mode} requires trees." ) def _build_index_from_nodes(self, nodes: Sequence[BaseNode]) -> IndexGraph: """Build the index from nodes.""" index_builder = GPTTreeIndexBuilder( self.num_children, self.summary_template, service_context=self.service_context, llm=self._llm, use_async=self._use_async, show_progress=self._show_progress, docstore=self._docstore, ) return index_builder.build_from_nodes(nodes, build_tree=self.build_tree) def _insert(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None: """Insert a document.""" # TODO: allow to customize insert prompt inserter = TreeIndexInserter( self.index_struct, service_context=self.service_context, llm=self._llm, num_children=self.num_children, insert_prompt=self.insert_prompt, summary_prompt=self.summary_template, docstore=self._docstore, ) inserter.insert(nodes) def _delete_node(self, node_id: str, **delete_kwargs: Any) -> None: """Delete a node.""" raise NotImplementedError("Delete not implemented for tree index.") @property def ref_doc_info(self) -> Dict[str, RefDocInfo]: """Retrieve a dict mapping of ingested documents and their nodes+metadata.""" node_doc_ids = list(self.index_struct.all_nodes.values()) nodes = self.docstore.get_nodes(node_doc_ids) all_ref_doc_info = {} for node in nodes: ref_node = node.source_node if not ref_node: continue ref_doc_info = self.docstore.get_ref_doc_info(ref_node.node_id) if not ref_doc_info: continue all_ref_doc_info[ref_node.node_id] = ref_doc_info return all_ref_doc_info # legacy GPTTreeIndex = TreeIndex
[ "llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever", "llama_index.core.settings.embed_model_from_settings_or_context", "llama_index.core.indices.tree.inserter.TreeIndexInserter", "llama_index.core.settings.llm_from_settings_or_context", "llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever", "llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever", "llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder", "llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever" ]
[((5992, 6202), 'llama_index.core.indices.common_tree.base.GPTTreeIndexBuilder', 'GPTTreeIndexBuilder', (['self.num_children', 'self.summary_template'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'use_async': 'self._use_async', 'show_progress': 'self._show_progress', 'docstore': 'self._docstore'}), '(self.num_children, self.summary_template,\n service_context=self.service_context, llm=self._llm, use_async=self.\n _use_async, show_progress=self._show_progress, docstore=self._docstore)\n', (6011, 6202), False, 'from llama_index.core.indices.common_tree.base import GPTTreeIndexBuilder\n'), ((6552, 6784), 'llama_index.core.indices.tree.inserter.TreeIndexInserter', 'TreeIndexInserter', (['self.index_struct'], {'service_context': 'self.service_context', 'llm': 'self._llm', 'num_children': 'self.num_children', 'insert_prompt': 'self.insert_prompt', 'summary_prompt': 'self.summary_template', 'docstore': 'self._docstore'}), '(self.index_struct, service_context=self.service_context,\n llm=self._llm, num_children=self.num_children, insert_prompt=self.\n insert_prompt, summary_prompt=self.summary_template, docstore=self.\n _docstore)\n', (6569, 6784), False, 'from llama_index.core.indices.tree.inserter import TreeIndexInserter\n'), ((3443, 3498), 'llama_index.core.settings.llm_from_settings_or_context', 'llm_from_settings_or_context', (['Settings', 'service_context'], {}), '(Settings, service_context)\n', (3471, 3498), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((4636, 4704), 'llama_index.core.indices.tree.select_leaf_retriever.TreeSelectLeafRetriever', 'TreeSelectLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (4659, 4704), False, 'from llama_index.core.indices.tree.select_leaf_retriever import TreeSelectLeafRetriever\n'), ((4937, 5044), 'llama_index.core.indices.tree.select_leaf_embedding_retriever.TreeSelectLeafEmbeddingRetriever', 'TreeSelectLeafEmbeddingRetriever', (['self'], {'embed_model': 'embed_model', 'object_map': 'self._object_map'}), '(self, embed_model=embed_model, object_map=\n self._object_map, **kwargs)\n', (4969, 5044), False, 'from llama_index.core.indices.tree.select_leaf_embedding_retriever import TreeSelectLeafEmbeddingRetriever\n'), ((4818, 4887), 'llama_index.core.settings.embed_model_from_settings_or_context', 'embed_model_from_settings_or_context', (['Settings', 'self._service_context'], {}), '(Settings, self._service_context)\n', (4854, 4887), False, 'from llama_index.core.settings import Settings, embed_model_from_settings_or_context, llm_from_settings_or_context\n'), ((5144, 5206), 'llama_index.core.indices.tree.tree_root_retriever.TreeRootRetriever', 'TreeRootRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5161, 5206), False, 'from llama_index.core.indices.tree.tree_root_retriever import TreeRootRetriever\n'), ((5285, 5350), 'llama_index.core.indices.tree.all_leaf_retriever.TreeAllLeafRetriever', 'TreeAllLeafRetriever', (['self'], {'object_map': 'self._object_map'}), '(self, object_map=self._object_map, **kwargs)\n', (5305, 5350), False, 'from llama_index.core.indices.tree.all_leaf_retriever import TreeAllLeafRetriever\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode EXAMPLE_URL = "https://clarifai.com/anthropic/completion/models/claude-v2" class Clarifai(LLM): model_url: Optional[str] = Field( description=f"Full URL of the model. e.g. `{EXAMPLE_URL}`" ) model_version_id: Optional[str] = Field(description="Model Version ID.") app_id: Optional[str] = Field(description="Clarifai application ID of the model.") user_id: Optional[str] = Field(description="Clarifai user ID of the model.") pat: Optional[str] = Field( description="Personal Access Tokens(PAT) to validate requests." ) _model: Any = PrivateAttr() _is_chat_model: bool = PrivateAttr() def __init__( self, model_name: Optional[str] = None, model_url: Optional[str] = None, model_version_id: Optional[str] = "", app_id: Optional[str] = None, user_id: Optional[str] = None, pat: Optional[str] = None, temperature: float = 0.1, max_tokens: int = 512, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ): try: import os from clarifai.client.model import Model except ImportError: raise ImportError("ClarifaiLLM requires `pip install clarifai`.") if pat is None and os.environ.get("CLARIFAI_PAT") is not None: pat = os.environ.get("CLARIFAI_PAT") if not pat and os.environ.get("CLARIFAI_PAT") is None: raise ValueError( "Set `CLARIFAI_PAT` as env variable or pass `pat` as constructor argument" ) if model_url is not None and model_name is not None: raise ValueError("You can only specify one of model_url or model_name.") if model_url is None and model_name is None: raise ValueError("You must specify one of model_url or model_name.") if model_name is not None: if app_id is None or user_id is None: raise ValueError( f"Missing one app ID or user ID of the model: {app_id=}, {user_id=}" ) else: self._model = Model( user_id=user_id, app_id=app_id, model_id=model_name, model_version={"id": model_version_id}, pat=pat, ) if model_url is not None: self._model = Model(model_url, pat=pat) model_name = self._model.id self._is_chat_model = False if "chat" in self._model.app_id or "chat" in self._model.id: self._is_chat_model = True additional_kwargs = additional_kwargs or {} super().__init__( temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, callback_manager=callback_manager, model_name=model_name, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "ClarifaiLLM" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( context_window=self.context_window, num_output=self.max_tokens, model_name=self._model, is_chat_model=self._is_chat_model, ) # TODO: When the Clarifai python SDK supports inference params, add here. def chat( self, messages: Sequence[ChatMessage], inference_params: Optional[Dict] = {}, **kwargs: Any, ) -> ChatResponse: """Chat endpoint for LLM.""" prompt = "".join([str(m) for m in messages]) try: response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="UTF-8"), input_type="text", inference_params=inference_params, ) .outputs[0] .data.text.raw ) except Exception as e: raise Exception(f"Prediction failed: {e}") return ChatResponse(message=ChatMessage(content=response)) def complete( self, prompt: str, formatted: bool = False, inference_params: Optional[Dict] = {}, **kwargs: Any, ) -> CompletionResponse: """Completion endpoint for LLM.""" try: response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="utf-8"), input_type="text", inference_params=inference_params, ) .outputs[0] .data.text.raw ) except Exception as e: raise Exception(f"Prediction failed: {e}") return CompletionResponse(text=response) def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise NotImplementedError( "Clarifai does not currently support streaming completion." ) def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise NotImplementedError( "Clarifai does not currently support streaming completion." ) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: raise NotImplementedError("Currently not supported.") @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: return self.complete(prompt, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError("Currently not supported.") @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError("Clarifai does not currently support this function.")
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse" ]
[((762, 827), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': 'f"""Full URL of the model. e.g. `{EXAMPLE_URL}`"""'}), "(description=f'Full URL of the model. e.g. `{EXAMPLE_URL}`')\n", (767, 827), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((880, 918), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Model Version ID."""'}), "(description='Model Version ID.')\n", (885, 918), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((947, 1005), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Clarifai application ID of the model."""'}), "(description='Clarifai application ID of the model.')\n", (952, 1005), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1035, 1086), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Clarifai user ID of the model."""'}), "(description='Clarifai user ID of the model.')\n", (1040, 1086), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1112, 1182), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Personal Access Tokens(PAT) to validate requests."""'}), "(description='Personal Access Tokens(PAT) to validate requests.')\n", (1117, 1182), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1216, 1229), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1227, 1229), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1257, 1270), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1268, 1270), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((6542, 6561), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6559, 6561), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6735, 6760), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6758, 6760), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6934, 6953), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6951, 6953), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7142, 7167), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7165, 7167), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4359, 4497), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_window', 'num_output': 'self.max_tokens', 'model_name': 'self._model', 'is_chat_model': 'self._is_chat_model'}), '(context_window=self.context_window, num_output=self.max_tokens,\n model_name=self._model, is_chat_model=self._is_chat_model)\n', (4370, 4497), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((6035, 6068), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response'}), '(text=response)\n', (6053, 6068), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((2360, 2390), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2374, 2390), False, 'import os\n'), ((3434, 3459), 'clarifai.client.model.Model', 'Model', (['model_url'], {'pat': 'pat'}), '(model_url, pat=pat)\n', (3439, 3459), False, 'from clarifai.client.model import Model\n'), ((2298, 2328), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2312, 2328), False, 'import os\n'), ((2415, 2445), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2429, 2445), False, 'import os\n'), ((3146, 3258), 'clarifai.client.model.Model', 'Model', ([], {'user_id': 'user_id', 'app_id': 'app_id', 'model_id': 'model_name', 'model_version': "{'id': model_version_id}", 'pat': 'pat'}), "(user_id=user_id, app_id=app_id, model_id=model_name, model_version={\n 'id': model_version_id}, pat=pat)\n", (3151, 3258), False, 'from clarifai.client.model import Model\n'), ((5340, 5369), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'content': 'response'}), '(content=response)\n', (5351, 5369), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import ( llm_chat_callback, llm_completion_callback, ) from llama_index.legacy.llms.llm import LLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode EXAMPLE_URL = "https://clarifai.com/anthropic/completion/models/claude-v2" class Clarifai(LLM): model_url: Optional[str] = Field( description=f"Full URL of the model. e.g. `{EXAMPLE_URL}`" ) model_version_id: Optional[str] = Field(description="Model Version ID.") app_id: Optional[str] = Field(description="Clarifai application ID of the model.") user_id: Optional[str] = Field(description="Clarifai user ID of the model.") pat: Optional[str] = Field( description="Personal Access Tokens(PAT) to validate requests." ) _model: Any = PrivateAttr() _is_chat_model: bool = PrivateAttr() def __init__( self, model_name: Optional[str] = None, model_url: Optional[str] = None, model_version_id: Optional[str] = "", app_id: Optional[str] = None, user_id: Optional[str] = None, pat: Optional[str] = None, temperature: float = 0.1, max_tokens: int = 512, additional_kwargs: Optional[Dict[str, Any]] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ): try: import os from clarifai.client.model import Model except ImportError: raise ImportError("ClarifaiLLM requires `pip install clarifai`.") if pat is None and os.environ.get("CLARIFAI_PAT") is not None: pat = os.environ.get("CLARIFAI_PAT") if not pat and os.environ.get("CLARIFAI_PAT") is None: raise ValueError( "Set `CLARIFAI_PAT` as env variable or pass `pat` as constructor argument" ) if model_url is not None and model_name is not None: raise ValueError("You can only specify one of model_url or model_name.") if model_url is None and model_name is None: raise ValueError("You must specify one of model_url or model_name.") if model_name is not None: if app_id is None or user_id is None: raise ValueError( f"Missing one app ID or user ID of the model: {app_id=}, {user_id=}" ) else: self._model = Model( user_id=user_id, app_id=app_id, model_id=model_name, model_version={"id": model_version_id}, pat=pat, ) if model_url is not None: self._model = Model(model_url, pat=pat) model_name = self._model.id self._is_chat_model = False if "chat" in self._model.app_id or "chat" in self._model.id: self._is_chat_model = True additional_kwargs = additional_kwargs or {} super().__init__( temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs, callback_manager=callback_manager, model_name=model_name, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "ClarifaiLLM" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( context_window=self.context_window, num_output=self.max_tokens, model_name=self._model, is_chat_model=self._is_chat_model, ) # TODO: When the Clarifai python SDK supports inference params, add here. def chat( self, messages: Sequence[ChatMessage], inference_params: Optional[Dict] = {}, **kwargs: Any, ) -> ChatResponse: """Chat endpoint for LLM.""" prompt = "".join([str(m) for m in messages]) try: response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="UTF-8"), input_type="text", inference_params=inference_params, ) .outputs[0] .data.text.raw ) except Exception as e: raise Exception(f"Prediction failed: {e}") return ChatResponse(message=ChatMessage(content=response)) def complete( self, prompt: str, formatted: bool = False, inference_params: Optional[Dict] = {}, **kwargs: Any, ) -> CompletionResponse: """Completion endpoint for LLM.""" try: response = ( self._model.predict_by_bytes( input_bytes=prompt.encode(encoding="utf-8"), input_type="text", inference_params=inference_params, ) .outputs[0] .data.text.raw ) except Exception as e: raise Exception(f"Prediction failed: {e}") return CompletionResponse(text=response) def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise NotImplementedError( "Clarifai does not currently support streaming completion." ) def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise NotImplementedError( "Clarifai does not currently support streaming completion." ) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: raise NotImplementedError("Currently not supported.") @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: return self.complete(prompt, **kwargs) @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: raise NotImplementedError("Currently not supported.") @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: raise NotImplementedError("Clarifai does not currently support this function.")
[ "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatMessage", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse" ]
[((762, 827), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': 'f"""Full URL of the model. e.g. `{EXAMPLE_URL}`"""'}), "(description=f'Full URL of the model. e.g. `{EXAMPLE_URL}`')\n", (767, 827), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((880, 918), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Model Version ID."""'}), "(description='Model Version ID.')\n", (885, 918), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((947, 1005), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Clarifai application ID of the model."""'}), "(description='Clarifai application ID of the model.')\n", (952, 1005), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1035, 1086), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Clarifai user ID of the model."""'}), "(description='Clarifai user ID of the model.')\n", (1040, 1086), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1112, 1182), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""Personal Access Tokens(PAT) to validate requests."""'}), "(description='Personal Access Tokens(PAT) to validate requests.')\n", (1117, 1182), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1216, 1229), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1227, 1229), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1257, 1270), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1268, 1270), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((6542, 6561), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6559, 6561), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6735, 6760), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (6758, 6760), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((6934, 6953), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (6951, 6953), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((7142, 7167), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (7165, 7167), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4359, 4497), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_window', 'num_output': 'self.max_tokens', 'model_name': 'self._model', 'is_chat_model': 'self._is_chat_model'}), '(context_window=self.context_window, num_output=self.max_tokens,\n model_name=self._model, is_chat_model=self._is_chat_model)\n', (4370, 4497), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((6035, 6068), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'response'}), '(text=response)\n', (6053, 6068), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n'), ((2360, 2390), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2374, 2390), False, 'import os\n'), ((3434, 3459), 'clarifai.client.model.Model', 'Model', (['model_url'], {'pat': 'pat'}), '(model_url, pat=pat)\n', (3439, 3459), False, 'from clarifai.client.model import Model\n'), ((2298, 2328), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2312, 2328), False, 'import os\n'), ((2415, 2445), 'os.environ.get', 'os.environ.get', (['"""CLARIFAI_PAT"""'], {}), "('CLARIFAI_PAT')\n", (2429, 2445), False, 'import os\n'), ((3146, 3258), 'clarifai.client.model.Model', 'Model', ([], {'user_id': 'user_id', 'app_id': 'app_id', 'model_id': 'model_name', 'model_version': "{'id': model_version_id}", 'pat': 'pat'}), "(user_id=user_id, app_id=app_id, model_id=model_name, model_version={\n 'id': model_version_id}, pat=pat)\n", (3151, 3258), False, 'from clarifai.client.model import Model\n'), ((5340, 5369), 'llama_index.legacy.core.llms.types.ChatMessage', 'ChatMessage', ([], {'content': 'response'}), '(content=response)\n', (5351, 5369), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseAsyncGen, ChatResponseGen, CompletionResponse, CompletionResponseAsyncGen, CompletionResponseGen, LLMMetadata\n')]
"""PII postprocessor.""" import json from copy import deepcopy from typing import Callable, Dict, List, Optional, Tuple from llama_index.core.llms.llm import LLM from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.prompts.base import PromptTemplate from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle DEFAULT_PII_TMPL = ( "The current context information is provided. \n" "A task is also provided to mask the PII within the context. \n" "Return the text, with all PII masked out, and a mapping of the original PII " "to the masked PII. \n" "Return the output of the task in JSON. \n" "Context:\n" "Hello Zhang Wei, I am John. " "Your AnyCompany Financial Services, " "LLC credit card account 1111-0000-1111-0008 " "has a minimum payment of $24.53 that is due " "by July 31st. Based on your autopay settings, we will withdraw your payment. " "Task: Mask out the PII, replace each PII with a tag, and return the text. Return the mapping in JSON. \n" "Output: \n" "Hello [NAME1], I am [NAME2]. " "Your AnyCompany Financial Services, " "LLC credit card account [CREDIT_CARD_NUMBER] " "has a minimum payment of $24.53 that is due " "by [DATE_TIME]. Based on your autopay settings, we will withdraw your payment. " "Output Mapping:\n" '{{"NAME1": "Zhang Wei", "NAME2": "John", "CREDIT_CARD_NUMBER": "1111-0000-1111-0008", "DATE_TIME": "July 31st"}}\n' "Context:\n{context_str}\n" "Task: {query_str}\n" "Output: \n" "" ) class PIINodePostprocessor(BaseNodePostprocessor): """PII Node processor. NOTE: this is a beta feature, the API might change. Args: llm (LLM): The local LLM to use for prediction. """ llm: LLM pii_str_tmpl: str = DEFAULT_PII_TMPL pii_node_info_key: str = "__pii_node_info__" @classmethod def class_name(cls) -> str: return "PIINodePostprocessor" def mask_pii(self, text: str) -> Tuple[str, Dict]: """Mask PII in text.""" pii_prompt = PromptTemplate(self.pii_str_tmpl) # TODO: allow customization task_str = ( "Mask out the PII, replace each PII with a tag, and return the text. " "Return the mapping in JSON." ) response = self.llm.predict(pii_prompt, context_str=text, query_str=task_str) splits = response.split("Output Mapping:") text_output = splits[0].strip() json_str_output = splits[1].strip() json_dict = json.loads(json_str_output) return text_output, json_dict def _postprocess_nodes( self, nodes: List[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> List[NodeWithScore]: """Postprocess nodes.""" # swap out text from nodes, with the original node mappings new_nodes = [] for node_with_score in nodes: node = node_with_score.node new_text, mapping_info = self.mask_pii( node.get_content(metadata_mode=MetadataMode.LLM) ) new_node = deepcopy(node) new_node.excluded_embed_metadata_keys.append(self.pii_node_info_key) new_node.excluded_llm_metadata_keys.append(self.pii_node_info_key) new_node.metadata[self.pii_node_info_key] = mapping_info new_node.set_content(new_text) new_nodes.append(NodeWithScore(node=new_node, score=node_with_score.score)) return new_nodes class NERPIINodePostprocessor(BaseNodePostprocessor): """NER PII Node processor. Uses a HF transformers model. """ pii_node_info_key: str = "__pii_node_info__" @classmethod def class_name(cls) -> str: return "NERPIINodePostprocessor" def mask_pii(self, ner: Callable, text: str) -> Tuple[str, Dict]: """Mask PII in text.""" new_text = text response = ner(text) mapping = {} for entry in response: entity_group_tag = f"[{entry['entity_group']}_{entry['start']}]" new_text = new_text.replace(entry["word"], entity_group_tag).strip() mapping[entity_group_tag] = entry["word"] return new_text, mapping def _postprocess_nodes( self, nodes: List[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> List[NodeWithScore]: """Postprocess nodes.""" from transformers import pipeline # pants: no-infer-dep ner = pipeline("ner", grouped_entities=True) # swap out text from nodes, with the original node mappings new_nodes = [] for node_with_score in nodes: node = node_with_score.node new_text, mapping_info = self.mask_pii( ner, node.get_content(metadata_mode=MetadataMode.LLM) ) new_node = deepcopy(node) new_node.excluded_embed_metadata_keys.append(self.pii_node_info_key) new_node.excluded_llm_metadata_keys.append(self.pii_node_info_key) new_node.metadata[self.pii_node_info_key] = mapping_info new_node.set_content(new_text) new_nodes.append(NodeWithScore(node=new_node, score=node_with_score.score)) return new_nodes
[ "llama_index.core.prompts.base.PromptTemplate", "llama_index.core.schema.NodeWithScore" ]
[((2092, 2125), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', (['self.pii_str_tmpl'], {}), '(self.pii_str_tmpl)\n', (2106, 2125), False, 'from llama_index.core.prompts.base import PromptTemplate\n'), ((2560, 2587), 'json.loads', 'json.loads', (['json_str_output'], {}), '(json_str_output)\n', (2570, 2587), False, 'import json\n'), ((4543, 4581), 'transformers.pipeline', 'pipeline', (['"""ner"""'], {'grouped_entities': '(True)'}), "('ner', grouped_entities=True)\n", (4551, 4581), False, 'from transformers import pipeline\n'), ((3143, 3157), 'copy.deepcopy', 'deepcopy', (['node'], {}), '(node)\n', (3151, 3157), False, 'from copy import deepcopy\n'), ((4911, 4925), 'copy.deepcopy', 'deepcopy', (['node'], {}), '(node)\n', (4919, 4925), False, 'from copy import deepcopy\n'), ((3459, 3516), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'new_node', 'score': 'node_with_score.score'}), '(node=new_node, score=node_with_score.score)\n', (3472, 3516), False, 'from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle\n'), ((5227, 5284), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'new_node', 'score': 'node_with_score.score'}), '(node=new_node, score=node_with_score.score)\n', (5240, 5284), False, 'from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle\n')]
"""PII postprocessor.""" import json from copy import deepcopy from typing import Callable, Dict, List, Optional, Tuple from llama_index.core.llms.llm import LLM from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.prompts.base import PromptTemplate from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle DEFAULT_PII_TMPL = ( "The current context information is provided. \n" "A task is also provided to mask the PII within the context. \n" "Return the text, with all PII masked out, and a mapping of the original PII " "to the masked PII. \n" "Return the output of the task in JSON. \n" "Context:\n" "Hello Zhang Wei, I am John. " "Your AnyCompany Financial Services, " "LLC credit card account 1111-0000-1111-0008 " "has a minimum payment of $24.53 that is due " "by July 31st. Based on your autopay settings, we will withdraw your payment. " "Task: Mask out the PII, replace each PII with a tag, and return the text. Return the mapping in JSON. \n" "Output: \n" "Hello [NAME1], I am [NAME2]. " "Your AnyCompany Financial Services, " "LLC credit card account [CREDIT_CARD_NUMBER] " "has a minimum payment of $24.53 that is due " "by [DATE_TIME]. Based on your autopay settings, we will withdraw your payment. " "Output Mapping:\n" '{{"NAME1": "Zhang Wei", "NAME2": "John", "CREDIT_CARD_NUMBER": "1111-0000-1111-0008", "DATE_TIME": "July 31st"}}\n' "Context:\n{context_str}\n" "Task: {query_str}\n" "Output: \n" "" ) class PIINodePostprocessor(BaseNodePostprocessor): """PII Node processor. NOTE: this is a beta feature, the API might change. Args: llm (LLM): The local LLM to use for prediction. """ llm: LLM pii_str_tmpl: str = DEFAULT_PII_TMPL pii_node_info_key: str = "__pii_node_info__" @classmethod def class_name(cls) -> str: return "PIINodePostprocessor" def mask_pii(self, text: str) -> Tuple[str, Dict]: """Mask PII in text.""" pii_prompt = PromptTemplate(self.pii_str_tmpl) # TODO: allow customization task_str = ( "Mask out the PII, replace each PII with a tag, and return the text. " "Return the mapping in JSON." ) response = self.llm.predict(pii_prompt, context_str=text, query_str=task_str) splits = response.split("Output Mapping:") text_output = splits[0].strip() json_str_output = splits[1].strip() json_dict = json.loads(json_str_output) return text_output, json_dict def _postprocess_nodes( self, nodes: List[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> List[NodeWithScore]: """Postprocess nodes.""" # swap out text from nodes, with the original node mappings new_nodes = [] for node_with_score in nodes: node = node_with_score.node new_text, mapping_info = self.mask_pii( node.get_content(metadata_mode=MetadataMode.LLM) ) new_node = deepcopy(node) new_node.excluded_embed_metadata_keys.append(self.pii_node_info_key) new_node.excluded_llm_metadata_keys.append(self.pii_node_info_key) new_node.metadata[self.pii_node_info_key] = mapping_info new_node.set_content(new_text) new_nodes.append(NodeWithScore(node=new_node, score=node_with_score.score)) return new_nodes class NERPIINodePostprocessor(BaseNodePostprocessor): """NER PII Node processor. Uses a HF transformers model. """ pii_node_info_key: str = "__pii_node_info__" @classmethod def class_name(cls) -> str: return "NERPIINodePostprocessor" def mask_pii(self, ner: Callable, text: str) -> Tuple[str, Dict]: """Mask PII in text.""" new_text = text response = ner(text) mapping = {} for entry in response: entity_group_tag = f"[{entry['entity_group']}_{entry['start']}]" new_text = new_text.replace(entry["word"], entity_group_tag).strip() mapping[entity_group_tag] = entry["word"] return new_text, mapping def _postprocess_nodes( self, nodes: List[NodeWithScore], query_bundle: Optional[QueryBundle] = None, ) -> List[NodeWithScore]: """Postprocess nodes.""" from transformers import pipeline # pants: no-infer-dep ner = pipeline("ner", grouped_entities=True) # swap out text from nodes, with the original node mappings new_nodes = [] for node_with_score in nodes: node = node_with_score.node new_text, mapping_info = self.mask_pii( ner, node.get_content(metadata_mode=MetadataMode.LLM) ) new_node = deepcopy(node) new_node.excluded_embed_metadata_keys.append(self.pii_node_info_key) new_node.excluded_llm_metadata_keys.append(self.pii_node_info_key) new_node.metadata[self.pii_node_info_key] = mapping_info new_node.set_content(new_text) new_nodes.append(NodeWithScore(node=new_node, score=node_with_score.score)) return new_nodes
[ "llama_index.core.prompts.base.PromptTemplate", "llama_index.core.schema.NodeWithScore" ]
[((2092, 2125), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', (['self.pii_str_tmpl'], {}), '(self.pii_str_tmpl)\n', (2106, 2125), False, 'from llama_index.core.prompts.base import PromptTemplate\n'), ((2560, 2587), 'json.loads', 'json.loads', (['json_str_output'], {}), '(json_str_output)\n', (2570, 2587), False, 'import json\n'), ((4543, 4581), 'transformers.pipeline', 'pipeline', (['"""ner"""'], {'grouped_entities': '(True)'}), "('ner', grouped_entities=True)\n", (4551, 4581), False, 'from transformers import pipeline\n'), ((3143, 3157), 'copy.deepcopy', 'deepcopy', (['node'], {}), '(node)\n', (3151, 3157), False, 'from copy import deepcopy\n'), ((4911, 4925), 'copy.deepcopy', 'deepcopy', (['node'], {}), '(node)\n', (4919, 4925), False, 'from copy import deepcopy\n'), ((3459, 3516), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'new_node', 'score': 'node_with_score.score'}), '(node=new_node, score=node_with_score.score)\n', (3472, 3516), False, 'from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle\n'), ((5227, 5284), 'llama_index.core.schema.NodeWithScore', 'NodeWithScore', ([], {'node': 'new_node', 'score': 'node_with_score.score'}), '(node=new_node, score=node_with_score.score)\n', (5240, 5284), False, 'from llama_index.core.schema import MetadataMode, NodeWithScore, QueryBundle\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS, DEFAULT_TEMPERATURE from llama_index.legacy.core.llms.types import ChatMessage, LLMMetadata from llama_index.legacy.llms.everlyai_utils import everlyai_modelname_to_contextsize from llama_index.legacy.llms.generic_utils import get_from_param_or_env from llama_index.legacy.llms.openai import OpenAI from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode EVERLYAI_API_BASE = "https://everlyai.xyz/hosted" DEFAULT_MODEL = "meta-llama/Llama-2-7b-chat-hf" class EverlyAI(OpenAI): def __init__( self, model: str = DEFAULT_MODEL, temperature: float = DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_NUM_OUTPUTS, additional_kwargs: Optional[Dict[str, Any]] = None, max_retries: int = 10, api_key: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) api_key = get_from_param_or_env("api_key", api_key, "EverlyAI_API_KEY") super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, api_base=EVERLYAI_API_BASE, api_key=api_key, additional_kwargs=additional_kwargs, max_retries=max_retries, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "EverlyAI_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=everlyai_modelname_to_contextsize(self.model), num_output=self.max_tokens, is_chat_model=True, model_name=self.model, ) @property def _is_chat_model(self) -> bool: return True
[ "llama_index.legacy.llms.generic_utils.get_from_param_or_env", "llama_index.legacy.callbacks.CallbackManager", "llama_index.legacy.llms.everlyai_utils.everlyai_modelname_to_contextsize" ]
[((1525, 1586), 'llama_index.legacy.llms.generic_utils.get_from_param_or_env', 'get_from_param_or_env', (['"""api_key"""', 'api_key', '"""EverlyAI_API_KEY"""'], {}), "('api_key', api_key, 'EverlyAI_API_KEY')\n", (1546, 1586), False, 'from llama_index.legacy.llms.generic_utils import get_from_param_or_env\n'), ((1486, 1505), 'llama_index.legacy.callbacks.CallbackManager', 'CallbackManager', (['[]'], {}), '([])\n', (1501, 1505), False, 'from llama_index.legacy.callbacks import CallbackManager\n'), ((2357, 2402), 'llama_index.legacy.llms.everlyai_utils.everlyai_modelname_to_contextsize', 'everlyai_modelname_to_contextsize', (['self.model'], {}), '(self.model)\n', (2390, 2402), False, 'from llama_index.legacy.llms.everlyai_utils import everlyai_modelname_to_contextsize\n')]
"""txtai reader.""" from typing import Any, Dict, List import numpy as np from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document class TxtaiReader(BaseReader): """txtai reader. Retrieves documents through an existing in-memory txtai index. These documents can then be used in a downstream LlamaIndex data structure. If you wish use txtai itself as an index to to organize documents, insert documents, and perform queries on them, please use VectorStoreIndex with TxtaiVectorStore. Args: txtai_index (txtai.ann.ANN): A txtai Index object (required) """ def __init__(self, index: Any): """Initialize with parameters.""" import_err_msg = """ `txtai` package not found. For instructions on how to install `txtai` please visit https://neuml.github.io/txtai/install/ """ try: import txtai # noqa except ImportError: raise ImportError(import_err_msg) self._index = index def load_data( self, query: np.ndarray, id_to_text_map: Dict[str, str], k: int = 4, separate_documents: bool = True, ) -> List[Document]: """Load data from txtai index. Args: query (np.ndarray): A 2D numpy array of query vectors. id_to_text_map (Dict[str, str]): A map from ID's to text. k (int): Number of nearest neighbors to retrieve. Defaults to 4. separate_documents (Optional[bool]): Whether to return separate documents. Defaults to True. Returns: List[Document]: A list of documents. """ search_result = self._index.search(query, k) documents = [] for query_result in search_result: for doc_id, _ in query_result: doc_id = str(doc_id) if doc_id not in id_to_text_map: raise ValueError( f"Document ID {doc_id} not found in id_to_text_map." ) text = id_to_text_map[doc_id] documents.append(Document(text=text)) if not separate_documents: # join all documents into one text_list = [doc.get_content() for doc in documents] text = "\n\n".join(text_list) documents = [Document(text=text)] return documents
[ "llama_index.legacy.schema.Document" ]
[((2425, 2444), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (2433, 2444), False, 'from llama_index.legacy.schema import Document\n'), ((2194, 2213), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (2202, 2213), False, 'from llama_index.legacy.schema import Document\n')]
"""txtai reader.""" from typing import Any, Dict, List import numpy as np from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document class TxtaiReader(BaseReader): """txtai reader. Retrieves documents through an existing in-memory txtai index. These documents can then be used in a downstream LlamaIndex data structure. If you wish use txtai itself as an index to to organize documents, insert documents, and perform queries on them, please use VectorStoreIndex with TxtaiVectorStore. Args: txtai_index (txtai.ann.ANN): A txtai Index object (required) """ def __init__(self, index: Any): """Initialize with parameters.""" import_err_msg = """ `txtai` package not found. For instructions on how to install `txtai` please visit https://neuml.github.io/txtai/install/ """ try: import txtai # noqa except ImportError: raise ImportError(import_err_msg) self._index = index def load_data( self, query: np.ndarray, id_to_text_map: Dict[str, str], k: int = 4, separate_documents: bool = True, ) -> List[Document]: """Load data from txtai index. Args: query (np.ndarray): A 2D numpy array of query vectors. id_to_text_map (Dict[str, str]): A map from ID's to text. k (int): Number of nearest neighbors to retrieve. Defaults to 4. separate_documents (Optional[bool]): Whether to return separate documents. Defaults to True. Returns: List[Document]: A list of documents. """ search_result = self._index.search(query, k) documents = [] for query_result in search_result: for doc_id, _ in query_result: doc_id = str(doc_id) if doc_id not in id_to_text_map: raise ValueError( f"Document ID {doc_id} not found in id_to_text_map." ) text = id_to_text_map[doc_id] documents.append(Document(text=text)) if not separate_documents: # join all documents into one text_list = [doc.get_content() for doc in documents] text = "\n\n".join(text_list) documents = [Document(text=text)] return documents
[ "llama_index.legacy.schema.Document" ]
[((2425, 2444), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (2433, 2444), False, 'from llama_index.legacy.schema import Document\n'), ((2194, 2213), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (2202, 2213), False, 'from llama_index.legacy.schema import Document\n')]
from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType """Single select prompt. PromptTemplate to select one out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str` """ SingleSelectPrompt = PromptTemplate """Multiple select prompt. PromptTemplate to select multiple candidates (up to `max_outputs`) out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str`, `max_outputs` """ MultiSelectPrompt = PromptTemplate # single select DEFAULT_SINGLE_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return " "the choice that is most relevant to the question: '{query_str}'\n" ) DEFAULT_SINGLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=PromptType.SINGLE_SELECT ) # multiple select DEFAULT_MULTI_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choices " "(no more than {max_outputs}, but only select what is needed) that " "are most relevant to the question: '{query_str}'\n" ) DEFAULT_MULTIPLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=PromptType.MULTI_SELECT ) # single pydantic select DEFAULT_SINGLE_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, generate " "the selection object and reason that is most relevant to the " "question: '{query_str}'\n" ) # multiple pydantic select DEFAULT_MULTI_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choice(s) " "(no more than {max_outputs}, but only select what is needed) by generating " "the selection object and reasons that are most relevant to the " "question: '{query_str}'\n" )
[ "llama_index.core.prompts.base.PromptTemplate" ]
[((1156, 1257), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_SINGLE_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.SINGLE_SELECT'}), '(template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.SINGLE_SELECT)\n', (1170, 1257), False, 'from llama_index.core.prompts.base import PromptTemplate\n'), ((1812, 1911), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_MULTI_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.MULTI_SELECT'}), '(template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.MULTI_SELECT)\n', (1826, 1911), False, 'from llama_index.core.prompts.base import PromptTemplate\n')]
from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType """Single select prompt. PromptTemplate to select one out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str` """ SingleSelectPrompt = PromptTemplate """Multiple select prompt. PromptTemplate to select multiple candidates (up to `max_outputs`) out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str`, `max_outputs` """ MultiSelectPrompt = PromptTemplate # single select DEFAULT_SINGLE_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return " "the choice that is most relevant to the question: '{query_str}'\n" ) DEFAULT_SINGLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=PromptType.SINGLE_SELECT ) # multiple select DEFAULT_MULTI_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choices " "(no more than {max_outputs}, but only select what is needed) that " "are most relevant to the question: '{query_str}'\n" ) DEFAULT_MULTIPLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=PromptType.MULTI_SELECT ) # single pydantic select DEFAULT_SINGLE_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, generate " "the selection object and reason that is most relevant to the " "question: '{query_str}'\n" ) # multiple pydantic select DEFAULT_MULTI_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choice(s) " "(no more than {max_outputs}, but only select what is needed) by generating " "the selection object and reasons that are most relevant to the " "question: '{query_str}'\n" )
[ "llama_index.core.prompts.base.PromptTemplate" ]
[((1156, 1257), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_SINGLE_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.SINGLE_SELECT'}), '(template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.SINGLE_SELECT)\n', (1170, 1257), False, 'from llama_index.core.prompts.base import PromptTemplate\n'), ((1812, 1911), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_MULTI_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.MULTI_SELECT'}), '(template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.MULTI_SELECT)\n', (1826, 1911), False, 'from llama_index.core.prompts.base import PromptTemplate\n')]
from llama_index.core.prompts.base import PromptTemplate from llama_index.core.prompts.prompt_type import PromptType """Single select prompt. PromptTemplate to select one out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str` """ SingleSelectPrompt = PromptTemplate """Multiple select prompt. PromptTemplate to select multiple candidates (up to `max_outputs`) out of `num_choices` options provided in `context_list`, given a query `query_str`. Required template variables: `num_chunks`, `context_list`, `query_str`, `max_outputs` """ MultiSelectPrompt = PromptTemplate # single select DEFAULT_SINGLE_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return " "the choice that is most relevant to the question: '{query_str}'\n" ) DEFAULT_SINGLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=PromptType.SINGLE_SELECT ) # multiple select DEFAULT_MULTI_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choices " "(no more than {max_outputs}, but only select what is needed) that " "are most relevant to the question: '{query_str}'\n" ) DEFAULT_MULTIPLE_SELECT_PROMPT = PromptTemplate( template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=PromptType.MULTI_SELECT ) # single pydantic select DEFAULT_SINGLE_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered list " "(1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, generate " "the selection object and reason that is most relevant to the " "question: '{query_str}'\n" ) # multiple pydantic select DEFAULT_MULTI_PYD_SELECT_PROMPT_TMPL = ( "Some choices are given below. It is provided in a numbered " "list (1 to {num_choices}), " "where each item in the list corresponds to a summary.\n" "---------------------\n" "{context_list}" "\n---------------------\n" "Using only the choices above and not prior knowledge, return the top choice(s) " "(no more than {max_outputs}, but only select what is needed) by generating " "the selection object and reasons that are most relevant to the " "question: '{query_str}'\n" )
[ "llama_index.core.prompts.base.PromptTemplate" ]
[((1156, 1257), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_SINGLE_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.SINGLE_SELECT'}), '(template=DEFAULT_SINGLE_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.SINGLE_SELECT)\n', (1170, 1257), False, 'from llama_index.core.prompts.base import PromptTemplate\n'), ((1812, 1911), 'llama_index.core.prompts.base.PromptTemplate', 'PromptTemplate', ([], {'template': 'DEFAULT_MULTI_SELECT_PROMPT_TMPL', 'prompt_type': 'PromptType.MULTI_SELECT'}), '(template=DEFAULT_MULTI_SELECT_PROMPT_TMPL, prompt_type=\n PromptType.MULTI_SELECT)\n', (1826, 1911), False, 'from llama_index.core.prompts.base import PromptTemplate\n')]
"""Awadb reader.""" from typing import Any, List import numpy as np from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document class AwadbReader(BaseReader): """Awadb reader. Retrieves documents through an existing awadb client. These documents can then be used in a downstream LlamaIndex data structure. Args: client (awadb.client): An awadb client. """ def __init__(self, client: Any): """Initialize with parameters.""" import_err_msg = """ `faiss` package not found. For instructions on how to install `faiss` please visit https://github.com/facebookresearch/faiss/wiki/Installing-Faiss """ try: pass except ImportError: raise ImportError(import_err_msg) self.awadb_client = client def load_data( self, query: np.ndarray, k: int = 4, separate_documents: bool = True, ) -> List[Document]: """Load data from Faiss. Args: query (np.ndarray): A 2D numpy array of query vectors. k (int): Number of nearest neighbors to retrieve. Defaults to 4. separate_documents (Optional[bool]): Whether to return separate documents. Defaults to True. Returns: List[Document]: A list of documents. """ results = self.awadb_client.Search( query, k, text_in_page_content=None, meta_filter=None, not_include_fields=None, ) documents = [] for item_detail in results[0]["ResultItems"]: documents.append(Document(text=item_detail["embedding_text"])) if not separate_documents: # join all documents into one text_list = [doc.get_content() for doc in documents] text = "\n\n".join(text_list) documents = [Document(text=text)] return documents
[ "llama_index.legacy.schema.Document" ]
[((1780, 1824), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': "item_detail['embedding_text']"}), "(text=item_detail['embedding_text'])\n", (1788, 1824), False, 'from llama_index.legacy.schema import Document\n'), ((2042, 2061), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (2050, 2061), False, 'from llama_index.legacy.schema import Document\n')]
"""Mongo client.""" from typing import Dict, Iterable, List, Optional, Union from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document class SimpleMongoReader(BaseReader): """Simple mongo reader. Concatenates each Mongo doc into Document used by LlamaIndex. Args: host (str): Mongo host. port (int): Mongo port. """ def __init__( self, host: Optional[str] = None, port: Optional[int] = None, uri: Optional[str] = None, ) -> None: """Initialize with parameters.""" try: from pymongo import MongoClient except ImportError as err: raise ImportError( "`pymongo` package not found, please run `pip install pymongo`" ) from err client: MongoClient if uri: client = MongoClient(uri) elif host and port: client = MongoClient(host, port) else: raise ValueError("Either `host` and `port` or `uri` must be provided.") self.client = client def _flatten(self, texts: List[Union[str, List[str]]]) -> List[str]: result = [] for text in texts: result += text if isinstance(text, list) else [text] return result def lazy_load_data( self, db_name: str, collection_name: str, field_names: List[str] = ["text"], separator: str = "", query_dict: Optional[Dict] = None, max_docs: int = 0, metadata_names: Optional[List[str]] = None, ) -> Iterable[Document]: """Load data from the input directory. Args: db_name (str): name of the database. collection_name (str): name of the collection. field_names(List[str]): names of the fields to be concatenated. Defaults to ["text"] separator (str): separator to be used between fields. Defaults to "" query_dict (Optional[Dict]): query to filter documents. Read more at [official docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.find/#std-label-method-find-query) Defaults to None max_docs (int): maximum number of documents to load. Defaults to 0 (no limit) metadata_names (Optional[List[str]]): names of the fields to be added to the metadata attribute of the Document. Defaults to None Returns: List[Document]: A list of documents. """ db = self.client[db_name] cursor = db[collection_name].find(filter=query_dict or {}, limit=max_docs) for item in cursor: try: texts = [item[name] for name in field_names] except KeyError as err: raise ValueError( f"{err.args[0]} field not found in Mongo document." ) from err texts = self._flatten(texts) text = separator.join(texts) if metadata_names is None: yield Document(text=text) else: try: metadata = {name: item[name] for name in metadata_names} except KeyError as err: raise ValueError( f"{err.args[0]} field not found in Mongo document." ) from err yield Document(text=text, metadata=metadata)
[ "llama_index.legacy.schema.Document" ]
[((887, 903), 'pymongo.MongoClient', 'MongoClient', (['uri'], {}), '(uri)\n', (898, 903), False, 'from pymongo import MongoClient\n'), ((953, 976), 'pymongo.MongoClient', 'MongoClient', (['host', 'port'], {}), '(host, port)\n', (964, 976), False, 'from pymongo import MongoClient\n'), ((3133, 3152), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (3141, 3152), False, 'from llama_index.legacy.schema import Document\n'), ((3476, 3514), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text', 'metadata': 'metadata'}), '(text=text, metadata=metadata)\n', (3484, 3514), False, 'from llama_index.legacy.schema import Document\n')]
"""Mongo client.""" from typing import Dict, Iterable, List, Optional, Union from llama_index.legacy.readers.base import BaseReader from llama_index.legacy.schema import Document class SimpleMongoReader(BaseReader): """Simple mongo reader. Concatenates each Mongo doc into Document used by LlamaIndex. Args: host (str): Mongo host. port (int): Mongo port. """ def __init__( self, host: Optional[str] = None, port: Optional[int] = None, uri: Optional[str] = None, ) -> None: """Initialize with parameters.""" try: from pymongo import MongoClient except ImportError as err: raise ImportError( "`pymongo` package not found, please run `pip install pymongo`" ) from err client: MongoClient if uri: client = MongoClient(uri) elif host and port: client = MongoClient(host, port) else: raise ValueError("Either `host` and `port` or `uri` must be provided.") self.client = client def _flatten(self, texts: List[Union[str, List[str]]]) -> List[str]: result = [] for text in texts: result += text if isinstance(text, list) else [text] return result def lazy_load_data( self, db_name: str, collection_name: str, field_names: List[str] = ["text"], separator: str = "", query_dict: Optional[Dict] = None, max_docs: int = 0, metadata_names: Optional[List[str]] = None, ) -> Iterable[Document]: """Load data from the input directory. Args: db_name (str): name of the database. collection_name (str): name of the collection. field_names(List[str]): names of the fields to be concatenated. Defaults to ["text"] separator (str): separator to be used between fields. Defaults to "" query_dict (Optional[Dict]): query to filter documents. Read more at [official docs](https://www.mongodb.com/docs/manual/reference/method/db.collection.find/#std-label-method-find-query) Defaults to None max_docs (int): maximum number of documents to load. Defaults to 0 (no limit) metadata_names (Optional[List[str]]): names of the fields to be added to the metadata attribute of the Document. Defaults to None Returns: List[Document]: A list of documents. """ db = self.client[db_name] cursor = db[collection_name].find(filter=query_dict or {}, limit=max_docs) for item in cursor: try: texts = [item[name] for name in field_names] except KeyError as err: raise ValueError( f"{err.args[0]} field not found in Mongo document." ) from err texts = self._flatten(texts) text = separator.join(texts) if metadata_names is None: yield Document(text=text) else: try: metadata = {name: item[name] for name in metadata_names} except KeyError as err: raise ValueError( f"{err.args[0]} field not found in Mongo document." ) from err yield Document(text=text, metadata=metadata)
[ "llama_index.legacy.schema.Document" ]
[((887, 903), 'pymongo.MongoClient', 'MongoClient', (['uri'], {}), '(uri)\n', (898, 903), False, 'from pymongo import MongoClient\n'), ((953, 976), 'pymongo.MongoClient', 'MongoClient', (['host', 'port'], {}), '(host, port)\n', (964, 976), False, 'from pymongo import MongoClient\n'), ((3133, 3152), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text'}), '(text=text)\n', (3141, 3152), False, 'from llama_index.legacy.schema import Document\n'), ((3476, 3514), 'llama_index.legacy.schema.Document', 'Document', ([], {'text': 'text', 'metadata': 'metadata'}), '(text=text, metadata=metadata)\n', (3484, 3514), False, 'from llama_index.legacy.schema import Document\n')]
from typing import Any, Callable, Optional, Sequence from typing_extensions import override from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class _BaseGradientLLM(CustomLLM): _gradient = PrivateAttr() _model = PrivateAttr() # Config max_tokens: Optional[int] = Field( default=DEFAULT_NUM_OUTPUTS, description="The number of tokens to generate.", gt=0, lt=512, ) # Gradient client config access_token: Optional[str] = Field( description="The Gradient access token to use.", ) host: Optional[str] = Field( description="The url of the Gradient service to access." ) workspace_id: Optional[str] = Field( description="The Gradient workspace id to use.", ) is_chat_model: bool = Field( default=False, description="Whether the model is a chat model." ) def __init__( self, *, access_token: Optional[str] = None, host: Optional[str] = None, max_tokens: Optional[int] = None, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: super().__init__( max_tokens=max_tokens, access_token=access_token, host=host, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, **kwargs, ) try: from gradientai import Gradient self._gradient = Gradient( access_token=access_token, host=host, workspace_id=workspace_id ) except ImportError as e: raise ImportError( "Could not import Gradient Python package. " "Please install it with `pip install gradientai`." ) from e def close(self) -> None: self._gradient.close() @llm_completion_callback() @override def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: return CompletionResponse( text=self._model.complete( query=prompt, max_generated_token_count=self.max_tokens, **kwargs, ).generated_output ) @llm_completion_callback() @override async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: grdt_reponse = await self._model.acomplete( query=prompt, max_generated_token_count=self.max_tokens, **kwargs, ) return CompletionResponse(text=grdt_reponse.generated_output) @override def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any, ) -> CompletionResponseGen: raise NotImplementedError @property @override def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=1024, num_output=self.max_tokens or 20, is_chat_model=self.is_chat_model, is_function_calling_model=False, model_name=self._model.id, ) class GradientBaseModelLLM(_BaseGradientLLM): base_model_slug: str = Field( description="The slug of the base model to use.", ) def __init__( self, *, access_token: Optional[str] = None, base_model_slug: str, host: Optional[str] = None, max_tokens: Optional[int] = None, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, ) -> None: super().__init__( access_token=access_token, base_model_slug=base_model_slug, host=host, max_tokens=max_tokens, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, ) self._model = self._gradient.get_base_model( base_model_slug=base_model_slug, ) class GradientModelAdapterLLM(_BaseGradientLLM): model_adapter_id: str = Field( description="The id of the model adapter to use.", ) def __init__( self, *, access_token: Optional[str] = None, host: Optional[str] = None, max_tokens: Optional[int] = None, model_adapter_id: str, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, ) -> None: super().__init__( access_token=access_token, host=host, max_tokens=max_tokens, model_adapter_id=model_adapter_id, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, ) self._model = self._gradient.get_model_adapter( model_adapter_id=model_adapter_id )
[ "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse" ]
[((660, 673), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (671, 673), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((687, 700), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (698, 700), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((747, 849), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_NUM_OUTPUTS', 'description': '"""The number of tokens to generate."""', 'gt': '(0)', 'lt': '(512)'}), "(default=DEFAULT_NUM_OUTPUTS, description=\n 'The number of tokens to generate.', gt=0, lt=512)\n", (752, 849), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((948, 1002), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Gradient access token to use."""'}), "(description='The Gradient access token to use.')\n", (953, 1002), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1044, 1107), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The url of the Gradient service to access."""'}), "(description='The url of the Gradient service to access.')\n", (1049, 1107), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1156, 1210), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Gradient workspace id to use."""'}), "(description='The Gradient workspace id to use.')\n", (1161, 1210), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1252, 1322), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether the model is a chat model."""'}), "(default=False, description='Whether the model is a chat model.')\n", (1257, 1322), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3019, 3044), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3042, 3044), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((3408, 3433), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3431, 3433), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((4391, 4446), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The slug of the base model to use."""'}), "(description='The slug of the base model to use.')\n", (4396, 4446), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5307, 5363), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The id of the model adapter to use."""'}), "(description='The id of the model adapter to use.')\n", (5312, 5363), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3749, 3803), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'grdt_reponse.generated_output'}), '(text=grdt_reponse.generated_output)\n', (3767, 3803), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((4084, 4252), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': '(1024)', 'num_output': '(self.max_tokens or 20)', 'is_chat_model': 'self.is_chat_model', 'is_function_calling_model': '(False)', 'model_name': 'self._model.id'}), '(context_window=1024, num_output=self.max_tokens or 20,\n is_chat_model=self.is_chat_model, is_function_calling_model=False,\n model_name=self._model.id)\n', (4095, 4252), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2635, 2708), 'gradientai.Gradient', 'Gradient', ([], {'access_token': 'access_token', 'host': 'host', 'workspace_id': 'workspace_id'}), '(access_token=access_token, host=host, workspace_id=workspace_id)\n', (2643, 2708), False, 'from gradientai import Gradient\n')]
from typing import Any, Callable, Optional, Sequence from typing_extensions import override from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class _BaseGradientLLM(CustomLLM): _gradient = PrivateAttr() _model = PrivateAttr() # Config max_tokens: Optional[int] = Field( default=DEFAULT_NUM_OUTPUTS, description="The number of tokens to generate.", gt=0, lt=512, ) # Gradient client config access_token: Optional[str] = Field( description="The Gradient access token to use.", ) host: Optional[str] = Field( description="The url of the Gradient service to access." ) workspace_id: Optional[str] = Field( description="The Gradient workspace id to use.", ) is_chat_model: bool = Field( default=False, description="Whether the model is a chat model." ) def __init__( self, *, access_token: Optional[str] = None, host: Optional[str] = None, max_tokens: Optional[int] = None, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, **kwargs: Any, ) -> None: super().__init__( max_tokens=max_tokens, access_token=access_token, host=host, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, **kwargs, ) try: from gradientai import Gradient self._gradient = Gradient( access_token=access_token, host=host, workspace_id=workspace_id ) except ImportError as e: raise ImportError( "Could not import Gradient Python package. " "Please install it with `pip install gradientai`." ) from e def close(self) -> None: self._gradient.close() @llm_completion_callback() @override def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: return CompletionResponse( text=self._model.complete( query=prompt, max_generated_token_count=self.max_tokens, **kwargs, ).generated_output ) @llm_completion_callback() @override async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: grdt_reponse = await self._model.acomplete( query=prompt, max_generated_token_count=self.max_tokens, **kwargs, ) return CompletionResponse(text=grdt_reponse.generated_output) @override def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any, ) -> CompletionResponseGen: raise NotImplementedError @property @override def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=1024, num_output=self.max_tokens or 20, is_chat_model=self.is_chat_model, is_function_calling_model=False, model_name=self._model.id, ) class GradientBaseModelLLM(_BaseGradientLLM): base_model_slug: str = Field( description="The slug of the base model to use.", ) def __init__( self, *, access_token: Optional[str] = None, base_model_slug: str, host: Optional[str] = None, max_tokens: Optional[int] = None, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, ) -> None: super().__init__( access_token=access_token, base_model_slug=base_model_slug, host=host, max_tokens=max_tokens, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, ) self._model = self._gradient.get_base_model( base_model_slug=base_model_slug, ) class GradientModelAdapterLLM(_BaseGradientLLM): model_adapter_id: str = Field( description="The id of the model adapter to use.", ) def __init__( self, *, access_token: Optional[str] = None, host: Optional[str] = None, max_tokens: Optional[int] = None, model_adapter_id: str, workspace_id: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, is_chat_model: bool = False, ) -> None: super().__init__( access_token=access_token, host=host, max_tokens=max_tokens, model_adapter_id=model_adapter_id, workspace_id=workspace_id, callback_manager=callback_manager, is_chat_model=is_chat_model, ) self._model = self._gradient.get_model_adapter( model_adapter_id=model_adapter_id )
[ "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.core.llms.types.CompletionResponse" ]
[((660, 673), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (671, 673), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((687, 700), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (698, 700), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((747, 849), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': 'DEFAULT_NUM_OUTPUTS', 'description': '"""The number of tokens to generate."""', 'gt': '(0)', 'lt': '(512)'}), "(default=DEFAULT_NUM_OUTPUTS, description=\n 'The number of tokens to generate.', gt=0, lt=512)\n", (752, 849), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((948, 1002), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Gradient access token to use."""'}), "(description='The Gradient access token to use.')\n", (953, 1002), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1044, 1107), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The url of the Gradient service to access."""'}), "(description='The url of the Gradient service to access.')\n", (1049, 1107), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1156, 1210), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The Gradient workspace id to use."""'}), "(description='The Gradient workspace id to use.')\n", (1161, 1210), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1252, 1322), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default': '(False)', 'description': '"""Whether the model is a chat model."""'}), "(default=False, description='Whether the model is a chat model.')\n", (1257, 1322), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3019, 3044), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3042, 3044), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((3408, 3433), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3431, 3433), False, 'from llama_index.legacy.llms.base import llm_completion_callback\n'), ((4391, 4446), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The slug of the base model to use."""'}), "(description='The slug of the base model to use.')\n", (4396, 4446), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((5307, 5363), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The id of the model adapter to use."""'}), "(description='The id of the model adapter to use.')\n", (5312, 5363), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3749, 3803), 'llama_index.legacy.core.llms.types.CompletionResponse', 'CompletionResponse', ([], {'text': 'grdt_reponse.generated_output'}), '(text=grdt_reponse.generated_output)\n', (3767, 3803), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((4084, 4252), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': '(1024)', 'num_output': '(self.max_tokens or 20)', 'is_chat_model': 'self.is_chat_model', 'is_function_calling_model': '(False)', 'model_name': 'self._model.id'}), '(context_window=1024, num_output=self.max_tokens or 20,\n is_chat_model=self.is_chat_model, is_function_calling_model=False,\n model_name=self._model.id)\n', (4095, 4252), False, 'from llama_index.legacy.core.llms.types import ChatMessage, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((2635, 2708), 'gradientai.Gradient', 'Gradient', ([], {'access_token': 'access_token', 'host': 'host', 'workspace_id': 'workspace_id'}), '(access_token=access_token, host=host, workspace_id=workspace_id)\n', (2643, 2708), False, 'from gradientai import Gradient\n')]
from typing import Dict, Type from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding RECOGNIZED_EMBEDDINGS: Dict[str, Type[BaseEmbedding]] = { MockEmbedding.class_name(): MockEmbedding, } # conditionals for llama-cloud support try: from llama_index.embeddings.openai import OpenAIEmbedding # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[OpenAIEmbedding.class_name()] = OpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.azure_openai import ( AzureOpenAIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[AzureOpenAIEmbedding.class_name()] = AzureOpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.huggingface import ( HuggingFaceInferenceAPIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[ HuggingFaceInferenceAPIEmbedding.class_name() ] = HuggingFaceInferenceAPIEmbedding except ImportError: pass def load_embed_model(data: dict) -> BaseEmbedding: """Load Embedding by name.""" if isinstance(data, BaseEmbedding): return data name = data.get("class_name", None) if name is None: raise ValueError("Embedding loading requires a class_name") if name not in RECOGNIZED_EMBEDDINGS: raise ValueError(f"Invalid Embedding name: {name}") return RECOGNIZED_EMBEDDINGS[name].from_dict(data)
[ "llama_index.embeddings.huggingface.HuggingFaceInferenceAPIEmbedding.class_name", "llama_index.embeddings.azure_openai.AzureOpenAIEmbedding.class_name", "llama_index.core.embeddings.mock_embed_model.MockEmbedding.class_name", "llama_index.embeddings.openai.OpenAIEmbedding.class_name" ]
[((229, 255), 'llama_index.core.embeddings.mock_embed_model.MockEmbedding.class_name', 'MockEmbedding.class_name', ([], {}), '()\n', (253, 255), False, 'from llama_index.core.embeddings.mock_embed_model import MockEmbedding\n'), ((431, 459), 'llama_index.embeddings.openai.OpenAIEmbedding.class_name', 'OpenAIEmbedding.class_name', ([], {}), '()\n', (457, 459), False, 'from llama_index.embeddings.openai import OpenAIEmbedding\n'), ((654, 687), 'llama_index.embeddings.azure_openai.AzureOpenAIEmbedding.class_name', 'AzureOpenAIEmbedding.class_name', ([], {}), '()\n', (685, 687), False, 'from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding\n'), ((907, 952), 'llama_index.embeddings.huggingface.HuggingFaceInferenceAPIEmbedding.class_name', 'HuggingFaceInferenceAPIEmbedding.class_name', ([], {}), '()\n', (950, 952), False, 'from llama_index.embeddings.huggingface import HuggingFaceInferenceAPIEmbedding\n')]
from typing import Dict, Type from llama_index.core.base.embeddings.base import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding RECOGNIZED_EMBEDDINGS: Dict[str, Type[BaseEmbedding]] = { MockEmbedding.class_name(): MockEmbedding, } # conditionals for llama-cloud support try: from llama_index.embeddings.openai import OpenAIEmbedding # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[OpenAIEmbedding.class_name()] = OpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.azure_openai import ( AzureOpenAIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[AzureOpenAIEmbedding.class_name()] = AzureOpenAIEmbedding except ImportError: pass try: from llama_index.embeddings.huggingface import ( HuggingFaceInferenceAPIEmbedding, ) # pants: no-infer-dep RECOGNIZED_EMBEDDINGS[ HuggingFaceInferenceAPIEmbedding.class_name() ] = HuggingFaceInferenceAPIEmbedding except ImportError: pass def load_embed_model(data: dict) -> BaseEmbedding: """Load Embedding by name.""" if isinstance(data, BaseEmbedding): return data name = data.get("class_name", None) if name is None: raise ValueError("Embedding loading requires a class_name") if name not in RECOGNIZED_EMBEDDINGS: raise ValueError(f"Invalid Embedding name: {name}") return RECOGNIZED_EMBEDDINGS[name].from_dict(data)
[ "llama_index.embeddings.huggingface.HuggingFaceInferenceAPIEmbedding.class_name", "llama_index.embeddings.azure_openai.AzureOpenAIEmbedding.class_name", "llama_index.core.embeddings.mock_embed_model.MockEmbedding.class_name", "llama_index.embeddings.openai.OpenAIEmbedding.class_name" ]
[((229, 255), 'llama_index.core.embeddings.mock_embed_model.MockEmbedding.class_name', 'MockEmbedding.class_name', ([], {}), '()\n', (253, 255), False, 'from llama_index.core.embeddings.mock_embed_model import MockEmbedding\n'), ((431, 459), 'llama_index.embeddings.openai.OpenAIEmbedding.class_name', 'OpenAIEmbedding.class_name', ([], {}), '()\n', (457, 459), False, 'from llama_index.embeddings.openai import OpenAIEmbedding\n'), ((654, 687), 'llama_index.embeddings.azure_openai.AzureOpenAIEmbedding.class_name', 'AzureOpenAIEmbedding.class_name', ([], {}), '()\n', (685, 687), False, 'from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding\n'), ((907, 952), 'llama_index.embeddings.huggingface.HuggingFaceInferenceAPIEmbedding.class_name', 'HuggingFaceInferenceAPIEmbedding.class_name', ([], {}), '()\n', (950, 952), False, 'from llama_index.embeddings.huggingface import HuggingFaceInferenceAPIEmbedding\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core.evaluation import CorrectnessEvaluator from llama_index.llms import OpenAI, Gemini from llama_index.core import ServiceContext import pandas as pd async def main(): # DOWNLOAD LLAMADATASET evaluator_dataset, _ = download_llama_dataset( "MiniMtBenchSingleGradingDataset", "./mini_mt_bench_data" ) # DEFINE EVALUATORS gpt_4_context = ServiceContext.from_defaults( llm=OpenAI(temperature=0, model="gpt-4"), ) gpt_3p5_context = ServiceContext.from_defaults( llm=OpenAI(temperature=0, model="gpt-3.5-turbo"), ) gemini_pro_context = ServiceContext.from_defaults( llm=Gemini(model="models/gemini-pro", temperature=0) ) evaluators = { "gpt-4": CorrectnessEvaluator(service_context=gpt_4_context), "gpt-3.5": CorrectnessEvaluator(service_context=gpt_3p5_context), "gemini-pro": CorrectnessEvaluator(service_context=gemini_pro_context), } # EVALUATE WITH PACK ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ EvaluatorBenchmarkerPack = download_llama_pack("EvaluatorBenchmarkerPack", "./pack") evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gpt-3.5"], eval_dataset=evaluator_dataset, show_progress=True, ) gpt_3p5_benchmark_df = await evaluator_benchmarker.arun( batch_size=100, sleep_time_in_seconds=0 ) evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gpt-4"], eval_dataset=evaluator_dataset, show_progress=True, ) gpt_4_benchmark_df = await evaluator_benchmarker.arun( batch_size=100, sleep_time_in_seconds=0 ) evaluator_benchmarker = EvaluatorBenchmarkerPack( evaluator=evaluators["gemini-pro"], eval_dataset=evaluator_dataset, show_progress=True, ) gemini_pro_benchmark_df = await evaluator_benchmarker.arun( batch_size=5, sleep_time_in_seconds=0.5 ) benchmark_df = pd.concat( [ gpt_3p5_benchmark_df, gpt_4_benchmark_df, gemini_pro_benchmark_df, ], axis=0, ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.llama_pack.download_llama_pack", "llama_index.core.evaluation.CorrectnessEvaluator", "llama_index.llms.Gemini", "llama_index.llms.OpenAI", "llama_index.core.llama_dataset.download_llama_dataset" ]
[((386, 471), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""MiniMtBenchSingleGradingDataset"""', '"""./mini_mt_bench_data"""'], {}), "('MiniMtBenchSingleGradingDataset',\n './mini_mt_bench_data')\n", (408, 471), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((1646, 1703), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""EvaluatorBenchmarkerPack"""', '"""./pack"""'], {}), "('EvaluatorBenchmarkerPack', './pack')\n", (1665, 1703), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((2580, 2670), 'pandas.concat', 'pd.concat', (['[gpt_3p5_benchmark_df, gpt_4_benchmark_df, gemini_pro_benchmark_df]'], {'axis': '(0)'}), '([gpt_3p5_benchmark_df, gpt_4_benchmark_df,\n gemini_pro_benchmark_df], axis=0)\n', (2589, 2670), True, 'import pandas as pd\n'), ((2801, 2825), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (2823, 2825), False, 'import asyncio\n'), ((890, 941), 'llama_index.core.evaluation.CorrectnessEvaluator', 'CorrectnessEvaluator', ([], {'service_context': 'gpt_4_context'}), '(service_context=gpt_4_context)\n', (910, 941), False, 'from llama_index.core.evaluation import CorrectnessEvaluator\n'), ((962, 1015), 'llama_index.core.evaluation.CorrectnessEvaluator', 'CorrectnessEvaluator', ([], {'service_context': 'gpt_3p5_context'}), '(service_context=gpt_3p5_context)\n', (982, 1015), False, 'from llama_index.core.evaluation import CorrectnessEvaluator\n'), ((1039, 1095), 'llama_index.core.evaluation.CorrectnessEvaluator', 'CorrectnessEvaluator', ([], {'service_context': 'gemini_pro_context'}), '(service_context=gemini_pro_context)\n', (1059, 1095), False, 'from llama_index.core.evaluation import CorrectnessEvaluator\n'), ((569, 605), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-4"""'}), "(temperature=0, model='gpt-4')\n", (575, 605), False, 'from llama_index.llms import OpenAI, Gemini\n'), ((678, 722), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'model': '"""gpt-3.5-turbo"""'}), "(temperature=0, model='gpt-3.5-turbo')\n", (684, 722), False, 'from llama_index.llms import OpenAI, Gemini\n'), ((798, 846), 'llama_index.llms.Gemini', 'Gemini', ([], {'model': '"""models/gemini-pro"""', 'temperature': '(0)'}), "(model='models/gemini-pro', temperature=0)\n", (804, 846), False, 'from llama_index.llms import OpenAI, Gemini\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "PaulGrahamEssayDataset", "./paul_graham" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 330), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""PaulGrahamEssayDataset"""', '"""./paul_graham"""'], {}), "('PaulGrahamEssayDataset', './paul_graham')\n", (287, 330), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((389, 441), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (420, 441), False, 'from llama_index.core import VectorStoreIndex\n'), ((534, 589), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (553, 589), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1440, 1464), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1462, 1464), False, 'import asyncio\n')]
import asyncio from llama_index.core.llama_dataset import download_llama_dataset from llama_index.core.llama_pack import download_llama_pack from llama_index.core import VectorStoreIndex async def main(): # DOWNLOAD LLAMADATASET rag_dataset, documents = download_llama_dataset( "PaulGrahamEssayDataset", "./paul_graham" ) # BUILD BASIC RAG PIPELINE index = VectorStoreIndex.from_documents(documents=documents) query_engine = index.as_query_engine() # EVALUATE WITH PACK RagEvaluatorPack = download_llama_pack("RagEvaluatorPack", "./pack_stuff") rag_evaluator = RagEvaluatorPack(query_engine=query_engine, rag_dataset=rag_dataset) ############################################################################ # NOTE: If have a lower tier subscription for OpenAI API like Usage Tier 1 # # then you'll need to use different batch_size and sleep_time_in_seconds. # # For Usage Tier 1, settings that seemed to work well were batch_size=5, # # and sleep_time_in_seconds=15 (as of December 2023.) # ############################################################################ benchmark_df = await rag_evaluator.arun( batch_size=20, # batches the number of openai api calls to make sleep_time_in_seconds=1, # number of seconds sleep before making an api call ) print(benchmark_df) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main)
[ "llama_index.core.VectorStoreIndex.from_documents", "llama_index.core.llama_dataset.download_llama_dataset", "llama_index.core.llama_pack.download_llama_pack" ]
[((265, 330), 'llama_index.core.llama_dataset.download_llama_dataset', 'download_llama_dataset', (['"""PaulGrahamEssayDataset"""', '"""./paul_graham"""'], {}), "('PaulGrahamEssayDataset', './paul_graham')\n", (287, 330), False, 'from llama_index.core.llama_dataset import download_llama_dataset\n'), ((389, 441), 'llama_index.core.VectorStoreIndex.from_documents', 'VectorStoreIndex.from_documents', ([], {'documents': 'documents'}), '(documents=documents)\n', (420, 441), False, 'from llama_index.core import VectorStoreIndex\n'), ((534, 589), 'llama_index.core.llama_pack.download_llama_pack', 'download_llama_pack', (['"""RagEvaluatorPack"""', '"""./pack_stuff"""'], {}), "('RagEvaluatorPack', './pack_stuff')\n", (553, 589), False, 'from llama_index.core.llama_pack import download_llama_pack\n'), ((1440, 1464), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1462, 1464), False, 'import asyncio\n')]
from typing import TYPE_CHECKING, Any, Optional from llama_index.core.base.base_query_engine import BaseQueryEngine if TYPE_CHECKING: from llama_index.core.langchain_helpers.agents.tools import ( LlamaIndexTool, ) from llama_index.core.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput DEFAULT_NAME = "query_engine_tool" DEFAULT_DESCRIPTION = """Useful for running a natural language query against a knowledge base and get back a natural language response. """ class QueryEngineTool(AsyncBaseTool): """Query engine tool. A tool making use of a query engine. Args: query_engine (BaseQueryEngine): A query engine. metadata (ToolMetadata): The associated metadata of the query engine. """ def __init__( self, query_engine: BaseQueryEngine, metadata: ToolMetadata, resolve_input_errors: bool = True, ) -> None: self._query_engine = query_engine self._metadata = metadata self._resolve_input_errors = resolve_input_errors @classmethod def from_defaults( cls, query_engine: BaseQueryEngine, name: Optional[str] = None, description: Optional[str] = None, resolve_input_errors: bool = True, ) -> "QueryEngineTool": name = name or DEFAULT_NAME description = description or DEFAULT_DESCRIPTION metadata = ToolMetadata(name=name, description=description) return cls( query_engine=query_engine, metadata=metadata, resolve_input_errors=resolve_input_errors, ) @property def query_engine(self) -> BaseQueryEngine: return self._query_engine @property def metadata(self) -> ToolMetadata: return self._metadata def call(self, *args: Any, **kwargs: Any) -> ToolOutput: if args is not None and len(args) > 0: query_str = str(args[0]) elif kwargs is not None and "input" in kwargs: # NOTE: this assumes our default function schema of `input` query_str = kwargs["input"] elif kwargs is not None and self._resolve_input_errors: query_str = str(kwargs) else: raise ValueError( "Cannot call query engine without specifying `input` parameter." ) response = self._query_engine.query(query_str) return ToolOutput( content=str(response), tool_name=self.metadata.name, raw_input={"input": query_str}, raw_output=response, ) async def acall(self, *args: Any, **kwargs: Any) -> ToolOutput: if args is not None and len(args) > 0: query_str = str(args[0]) elif kwargs is not None and "input" in kwargs: # NOTE: this assumes our default function schema of `input` query_str = kwargs["input"] elif kwargs is not None and self._resolve_input_errors: query_str = str(kwargs) else: raise ValueError("Cannot call query engine without inputs") response = await self._query_engine.aquery(query_str) return ToolOutput( content=str(response), tool_name=self.metadata.name, raw_input={"input": query_str}, raw_output=response, ) def as_langchain_tool(self) -> "LlamaIndexTool": from llama_index.core.langchain_helpers.agents.tools import ( IndexToolConfig, LlamaIndexTool, ) tool_config = IndexToolConfig( query_engine=self.query_engine, name=self.metadata.name, description=self.metadata.description, ) return LlamaIndexTool.from_tool_config(tool_config=tool_config)
[ "llama_index.core.langchain_helpers.agents.tools.IndexToolConfig", "llama_index.core.langchain_helpers.agents.tools.LlamaIndexTool.from_tool_config", "llama_index.core.tools.types.ToolMetadata" ]
[((1402, 1450), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'name': 'name', 'description': 'description'}), '(name=name, description=description)\n', (1414, 1450), False, 'from llama_index.core.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput\n'), ((3560, 3675), 'llama_index.core.langchain_helpers.agents.tools.IndexToolConfig', 'IndexToolConfig', ([], {'query_engine': 'self.query_engine', 'name': 'self.metadata.name', 'description': 'self.metadata.description'}), '(query_engine=self.query_engine, name=self.metadata.name,\n description=self.metadata.description)\n', (3575, 3675), False, 'from llama_index.core.langchain_helpers.agents.tools import IndexToolConfig, LlamaIndexTool\n'), ((3734, 3790), 'llama_index.core.langchain_helpers.agents.tools.LlamaIndexTool.from_tool_config', 'LlamaIndexTool.from_tool_config', ([], {'tool_config': 'tool_config'}), '(tool_config=tool_config)\n', (3765, 3790), False, 'from llama_index.core.langchain_helpers.agents.tools import IndexToolConfig, LlamaIndexTool\n')]
from typing import TYPE_CHECKING, Any, Optional from llama_index.core.base.base_query_engine import BaseQueryEngine if TYPE_CHECKING: from llama_index.core.langchain_helpers.agents.tools import ( LlamaIndexTool, ) from llama_index.core.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput DEFAULT_NAME = "query_engine_tool" DEFAULT_DESCRIPTION = """Useful for running a natural language query against a knowledge base and get back a natural language response. """ class QueryEngineTool(AsyncBaseTool): """Query engine tool. A tool making use of a query engine. Args: query_engine (BaseQueryEngine): A query engine. metadata (ToolMetadata): The associated metadata of the query engine. """ def __init__( self, query_engine: BaseQueryEngine, metadata: ToolMetadata, resolve_input_errors: bool = True, ) -> None: self._query_engine = query_engine self._metadata = metadata self._resolve_input_errors = resolve_input_errors @classmethod def from_defaults( cls, query_engine: BaseQueryEngine, name: Optional[str] = None, description: Optional[str] = None, resolve_input_errors: bool = True, ) -> "QueryEngineTool": name = name or DEFAULT_NAME description = description or DEFAULT_DESCRIPTION metadata = ToolMetadata(name=name, description=description) return cls( query_engine=query_engine, metadata=metadata, resolve_input_errors=resolve_input_errors, ) @property def query_engine(self) -> BaseQueryEngine: return self._query_engine @property def metadata(self) -> ToolMetadata: return self._metadata def call(self, *args: Any, **kwargs: Any) -> ToolOutput: if args is not None and len(args) > 0: query_str = str(args[0]) elif kwargs is not None and "input" in kwargs: # NOTE: this assumes our default function schema of `input` query_str = kwargs["input"] elif kwargs is not None and self._resolve_input_errors: query_str = str(kwargs) else: raise ValueError( "Cannot call query engine without specifying `input` parameter." ) response = self._query_engine.query(query_str) return ToolOutput( content=str(response), tool_name=self.metadata.name, raw_input={"input": query_str}, raw_output=response, ) async def acall(self, *args: Any, **kwargs: Any) -> ToolOutput: if args is not None and len(args) > 0: query_str = str(args[0]) elif kwargs is not None and "input" in kwargs: # NOTE: this assumes our default function schema of `input` query_str = kwargs["input"] elif kwargs is not None and self._resolve_input_errors: query_str = str(kwargs) else: raise ValueError("Cannot call query engine without inputs") response = await self._query_engine.aquery(query_str) return ToolOutput( content=str(response), tool_name=self.metadata.name, raw_input={"input": query_str}, raw_output=response, ) def as_langchain_tool(self) -> "LlamaIndexTool": from llama_index.core.langchain_helpers.agents.tools import ( IndexToolConfig, LlamaIndexTool, ) tool_config = IndexToolConfig( query_engine=self.query_engine, name=self.metadata.name, description=self.metadata.description, ) return LlamaIndexTool.from_tool_config(tool_config=tool_config)
[ "llama_index.core.langchain_helpers.agents.tools.IndexToolConfig", "llama_index.core.langchain_helpers.agents.tools.LlamaIndexTool.from_tool_config", "llama_index.core.tools.types.ToolMetadata" ]
[((1402, 1450), 'llama_index.core.tools.types.ToolMetadata', 'ToolMetadata', ([], {'name': 'name', 'description': 'description'}), '(name=name, description=description)\n', (1414, 1450), False, 'from llama_index.core.tools.types import AsyncBaseTool, ToolMetadata, ToolOutput\n'), ((3560, 3675), 'llama_index.core.langchain_helpers.agents.tools.IndexToolConfig', 'IndexToolConfig', ([], {'query_engine': 'self.query_engine', 'name': 'self.metadata.name', 'description': 'self.metadata.description'}), '(query_engine=self.query_engine, name=self.metadata.name,\n description=self.metadata.description)\n', (3575, 3675), False, 'from llama_index.core.langchain_helpers.agents.tools import IndexToolConfig, LlamaIndexTool\n'), ((3734, 3790), 'llama_index.core.langchain_helpers.agents.tools.LlamaIndexTool.from_tool_config', 'LlamaIndexTool.from_tool_config', ([], {'tool_config': 'tool_config'}), '(tool_config=tool_config)\n', (3765, 3790), False, 'from llama_index.core.langchain_helpers.agents.tools import IndexToolConfig, LlamaIndexTool\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator from llama_index.legacy.llms.openai_utils import ( from_openai_message_dict, to_openai_message_dicts, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class LlamaAPI(CustomLLM): model: str = Field(description="The llama-api model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_tokens: int = Field(description="The maximum number of tokens to generate.") additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the llama-api API." ) _client: Any = PrivateAttr() def __init__( self, model: str = "llama-13b-chat", temperature: float = 0.1, max_tokens: int = DEFAULT_NUM_OUTPUTS, additional_kwargs: Optional[Dict[str, Any]] = None, api_key: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from llamaapi import LlamaAPI as Client except ImportError as e: raise ImportError( "llama_api not installed." "Please install it with `pip install llamaapi`." ) from e self._client = Client(api_key) super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs or {}, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "llama_api_llm" @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_length": self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=4096, num_output=DEFAULT_NUM_OUTPUTS, is_chat_model=True, is_function_calling_model=True, model_name="llama-api", ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: message_dicts = to_openai_message_dicts(messages) json_dict = { "messages": message_dicts, **self._model_kwargs, **kwargs, } response = self._client.run(json_dict).json() message_dict = response["choices"][0]["message"] message = from_openai_message_dict(message_dict) return ChatResponse(message=message, raw=response) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: complete_fn = chat_to_completion_decorator(self.chat) return complete_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise NotImplementedError("stream_complete is not supported for LlamaAPI") @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise NotImplementedError("stream_chat is not supported for LlamaAPI")
[ "llama_index.legacy.llms.openai_utils.from_openai_message_dict", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatResponse", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.openai_utils.to_openai_message_dicts" ]
[((868, 916), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The llama-api model to use."""'}), "(description='The llama-api model to use.')\n", (873, 916), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((942, 999), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (947, 999), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1022, 1084), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1027, 1084), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1125, 1213), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the llama-api API."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the llama-api API.')\n", (1130, 1213), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1243, 1256), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1254, 1256), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3379, 3398), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (3396, 3398), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3902, 3927), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3925, 3927), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4154, 4179), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (4177, 4179), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4392, 4411), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4409, 4411), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2205, 2220), 'llamaapi.LlamaAPI', 'Client', (['api_key'], {}), '(api_key)\n', (2211, 2220), True, 'from llamaapi import LlamaAPI as Client\n'), ((3161, 3305), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': '(4096)', 'num_output': 'DEFAULT_NUM_OUTPUTS', 'is_chat_model': '(True)', 'is_function_calling_model': '(True)', 'model_name': '"""llama-api"""'}), "(context_window=4096, num_output=DEFAULT_NUM_OUTPUTS,\n is_chat_model=True, is_function_calling_model=True, model_name='llama-api')\n", (3172, 3305), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((3507, 3540), 'llama_index.legacy.llms.openai_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (3530, 3540), False, 'from llama_index.legacy.llms.openai_utils import from_openai_message_dict, to_openai_message_dicts\n'), ((3797, 3835), 'llama_index.legacy.llms.openai_utils.from_openai_message_dict', 'from_openai_message_dict', (['message_dict'], {}), '(message_dict)\n', (3821, 3835), False, 'from llama_index.legacy.llms.openai_utils import from_openai_message_dict, to_openai_message_dicts\n'), ((3852, 3895), 'llama_index.legacy.core.llms.types.ChatResponse', 'ChatResponse', ([], {'message': 'message', 'raw': 'response'}), '(message=message, raw=response)\n', (3864, 3895), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((4063, 4102), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self.chat'], {}), '(self.chat)\n', (4091, 4102), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator\n')]
from typing import Any, Callable, Dict, Optional, Sequence from llama_index.legacy.bridge.pydantic import Field, PrivateAttr from llama_index.legacy.callbacks import CallbackManager from llama_index.legacy.constants import DEFAULT_NUM_OUTPUTS from llama_index.legacy.core.llms.types import ( ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata, ) from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback from llama_index.legacy.llms.custom import CustomLLM from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator from llama_index.legacy.llms.openai_utils import ( from_openai_message_dict, to_openai_message_dicts, ) from llama_index.legacy.types import BaseOutputParser, PydanticProgramMode class LlamaAPI(CustomLLM): model: str = Field(description="The llama-api model to use.") temperature: float = Field(description="The temperature to use for sampling.") max_tokens: int = Field(description="The maximum number of tokens to generate.") additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the llama-api API." ) _client: Any = PrivateAttr() def __init__( self, model: str = "llama-13b-chat", temperature: float = 0.1, max_tokens: int = DEFAULT_NUM_OUTPUTS, additional_kwargs: Optional[Dict[str, Any]] = None, api_key: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: try: from llamaapi import LlamaAPI as Client except ImportError as e: raise ImportError( "llama_api not installed." "Please install it with `pip install llamaapi`." ) from e self._client = Client(api_key) super().__init__( model=model, temperature=temperature, max_tokens=max_tokens, additional_kwargs=additional_kwargs or {}, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) @classmethod def class_name(cls) -> str: return "llama_api_llm" @property def _model_kwargs(self) -> Dict[str, Any]: base_kwargs = { "model": self.model, "temperature": self.temperature, "max_length": self.max_tokens, } return { **base_kwargs, **self.additional_kwargs, } @property def metadata(self) -> LLMMetadata: return LLMMetadata( context_window=4096, num_output=DEFAULT_NUM_OUTPUTS, is_chat_model=True, is_function_calling_model=True, model_name="llama-api", ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: message_dicts = to_openai_message_dicts(messages) json_dict = { "messages": message_dicts, **self._model_kwargs, **kwargs, } response = self._client.run(json_dict).json() message_dict = response["choices"][0]["message"] message = from_openai_message_dict(message_dict) return ChatResponse(message=message, raw=response) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: complete_fn = chat_to_completion_decorator(self.chat) return complete_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: raise NotImplementedError("stream_complete is not supported for LlamaAPI") @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: raise NotImplementedError("stream_chat is not supported for LlamaAPI")
[ "llama_index.legacy.llms.openai_utils.from_openai_message_dict", "llama_index.legacy.llms.base.llm_chat_callback", "llama_index.legacy.core.llms.types.ChatResponse", "llama_index.legacy.llms.base.llm_completion_callback", "llama_index.legacy.bridge.pydantic.PrivateAttr", "llama_index.legacy.core.llms.types.LLMMetadata", "llama_index.legacy.bridge.pydantic.Field", "llama_index.legacy.llms.generic_utils.chat_to_completion_decorator", "llama_index.legacy.llms.openai_utils.to_openai_message_dicts" ]
[((868, 916), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The llama-api model to use."""'}), "(description='The llama-api model to use.')\n", (873, 916), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((942, 999), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (947, 999), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1022, 1084), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (1027, 1084), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1125, 1213), 'llama_index.legacy.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Additional kwargs for the llama-api API."""'}), "(default_factory=dict, description=\n 'Additional kwargs for the llama-api API.')\n", (1130, 1213), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((1243, 1256), 'llama_index.legacy.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (1254, 1256), False, 'from llama_index.legacy.bridge.pydantic import Field, PrivateAttr\n'), ((3379, 3398), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (3396, 3398), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((3902, 3927), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (3925, 3927), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4154, 4179), 'llama_index.legacy.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (4177, 4179), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((4392, 4411), 'llama_index.legacy.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (4409, 4411), False, 'from llama_index.legacy.llms.base import llm_chat_callback, llm_completion_callback\n'), ((2205, 2220), 'llamaapi.LlamaAPI', 'Client', (['api_key'], {}), '(api_key)\n', (2211, 2220), True, 'from llamaapi import LlamaAPI as Client\n'), ((3161, 3305), 'llama_index.legacy.core.llms.types.LLMMetadata', 'LLMMetadata', ([], {'context_window': '(4096)', 'num_output': 'DEFAULT_NUM_OUTPUTS', 'is_chat_model': '(True)', 'is_function_calling_model': '(True)', 'model_name': '"""llama-api"""'}), "(context_window=4096, num_output=DEFAULT_NUM_OUTPUTS,\n is_chat_model=True, is_function_calling_model=True, model_name='llama-api')\n", (3172, 3305), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((3507, 3540), 'llama_index.legacy.llms.openai_utils.to_openai_message_dicts', 'to_openai_message_dicts', (['messages'], {}), '(messages)\n', (3530, 3540), False, 'from llama_index.legacy.llms.openai_utils import from_openai_message_dict, to_openai_message_dicts\n'), ((3797, 3835), 'llama_index.legacy.llms.openai_utils.from_openai_message_dict', 'from_openai_message_dict', (['message_dict'], {}), '(message_dict)\n', (3821, 3835), False, 'from llama_index.legacy.llms.openai_utils import from_openai_message_dict, to_openai_message_dicts\n'), ((3852, 3895), 'llama_index.legacy.core.llms.types.ChatResponse', 'ChatResponse', ([], {'message': 'message', 'raw': 'response'}), '(message=message, raw=response)\n', (3864, 3895), False, 'from llama_index.legacy.core.llms.types import ChatMessage, ChatResponse, ChatResponseGen, CompletionResponse, CompletionResponseGen, LLMMetadata\n'), ((4063, 4102), 'llama_index.legacy.llms.generic_utils.chat_to_completion_decorator', 'chat_to_completion_decorator', (['self.chat'], {}), '(self.chat)\n', (4091, 4102), False, 'from llama_index.legacy.llms.generic_utils import chat_to_completion_decorator\n')]
"""Download tool from Llama Hub.""" from typing import Optional, Type from llama_index.legacy.download.module import ( LLAMA_HUB_URL, MODULE_TYPE, download_llama_module, track_download, ) from llama_index.legacy.tools.tool_spec.base import BaseToolSpec def download_tool( tool_class: str, llama_hub_url: str = LLAMA_HUB_URL, refresh_cache: bool = False, custom_path: Optional[str] = None, ) -> Type[BaseToolSpec]: """Download a single tool from Llama Hub. Args: tool_class: The name of the tool class you want to download, such as `GmailToolSpec`. refresh_cache: If true, the local cache will be skipped and the loader will be fetched directly from the remote repo. custom_path: Custom dirpath to download loader into. Returns: A Loader. """ tool_cls = download_llama_module( tool_class, llama_hub_url=llama_hub_url, refresh_cache=refresh_cache, custom_dir="tools", custom_path=custom_path, library_path="tools/library.json", ) if not issubclass(tool_cls, BaseToolSpec): raise ValueError(f"Tool class {tool_class} must be a subclass of BaseToolSpec.") track_download(tool_class, MODULE_TYPE.TOOL) return tool_cls
[ "llama_index.legacy.download.module.track_download", "llama_index.legacy.download.module.download_llama_module" ]
[((867, 1047), 'llama_index.legacy.download.module.download_llama_module', 'download_llama_module', (['tool_class'], {'llama_hub_url': 'llama_hub_url', 'refresh_cache': 'refresh_cache', 'custom_dir': '"""tools"""', 'custom_path': 'custom_path', 'library_path': '"""tools/library.json"""'}), "(tool_class, llama_hub_url=llama_hub_url,\n refresh_cache=refresh_cache, custom_dir='tools', custom_path=\n custom_path, library_path='tools/library.json')\n", (888, 1047), False, 'from llama_index.legacy.download.module import LLAMA_HUB_URL, MODULE_TYPE, download_llama_module, track_download\n'), ((1234, 1278), 'llama_index.legacy.download.module.track_download', 'track_download', (['tool_class', 'MODULE_TYPE.TOOL'], {}), '(tool_class, MODULE_TYPE.TOOL)\n', (1248, 1278), False, 'from llama_index.legacy.download.module import LLAMA_HUB_URL, MODULE_TYPE, download_llama_module, track_download\n')]
"""Simple Engine.""" import json import os from typing import Any, Optional, Union from llama_index.core import SimpleDirectoryReader, VectorStoreIndex from llama_index.core.callbacks.base import CallbackManager from llama_index.core.embeddings import BaseEmbedding from llama_index.core.embeddings.mock_embed_model import MockEmbedding from llama_index.core.indices.base import BaseIndex from llama_index.core.ingestion.pipeline import run_transformations from llama_index.core.llms import LLM from llama_index.core.node_parser import SentenceSplitter from llama_index.core.postprocessor.types import BaseNodePostprocessor from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.response_synthesizers import ( BaseSynthesizer, get_response_synthesizer, ) from llama_index.core.retrievers import BaseRetriever from llama_index.core.schema import ( BaseNode, Document, NodeWithScore, QueryBundle, QueryType, TransformComponent, ) from metagpt.rag.factories import ( get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever, ) from metagpt.rag.interface import NoEmbedding, RAGObject from metagpt.rag.retrievers.base import ModifiableRAGRetriever, PersistableRAGRetriever from metagpt.rag.retrievers.hybrid_retriever import SimpleHybridRetriever from metagpt.rag.schema import ( BaseIndexConfig, BaseRankerConfig, BaseRetrieverConfig, BM25RetrieverConfig, ObjectNode, ) from metagpt.utils.common import import_class class SimpleEngine(RetrieverQueryEngine): """SimpleEngine is designed to be simple and straightforward. It is a lightweight and easy-to-use search engine that integrates document reading, embedding, indexing, retrieving, and ranking functionalities into a single, straightforward workflow. It is designed to quickly set up a search engine from a collection of documents. """ def __init__( self, retriever: BaseRetriever, response_synthesizer: Optional[BaseSynthesizer] = None, node_postprocessors: Optional[list[BaseNodePostprocessor]] = None, callback_manager: Optional[CallbackManager] = None, index: Optional[BaseIndex] = None, ) -> None: super().__init__( retriever=retriever, response_synthesizer=response_synthesizer, node_postprocessors=node_postprocessors, callback_manager=callback_manager, ) self.index = index @classmethod def from_docs( cls, input_dir: str = None, input_files: list[str] = None, transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": """From docs. Must provide either `input_dir` or `input_files`. Args: input_dir: Path to the directory. input_files: List of file paths to read (Optional; overrides input_dir, exclude). transformations: Parse documents to nodes. Default [SentenceSplitter]. embed_model: Parse nodes to embedding. Must supported by llama index. Default OpenAIEmbedding. llm: Must supported by llama index. Default OpenAI. retriever_configs: Configuration for retrievers. If more than one config, will use SimpleHybridRetriever. ranker_configs: Configuration for rankers. """ if not input_dir and not input_files: raise ValueError("Must provide either `input_dir` or `input_files`.") documents = SimpleDirectoryReader(input_dir=input_dir, input_files=input_files).load_data() cls._fix_document_metadata(documents) index = VectorStoreIndex.from_documents( documents=documents, transformations=transformations or [SentenceSplitter()], embed_model=cls._resolve_embed_model(embed_model, retriever_configs), ) return cls._from_index(index, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs) @classmethod def from_objs( cls, objs: Optional[list[RAGObject]] = None, transformations: Optional[list[TransformComponent]] = None, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": """From objs. Args: objs: List of RAGObject. transformations: Parse documents to nodes. Default [SentenceSplitter]. embed_model: Parse nodes to embedding. Must supported by llama index. Default OpenAIEmbedding. llm: Must supported by llama index. Default OpenAI. retriever_configs: Configuration for retrievers. If more than one config, will use SimpleHybridRetriever. ranker_configs: Configuration for rankers. """ if not objs and any(isinstance(config, BM25RetrieverConfig) for config in retriever_configs): raise ValueError("In BM25RetrieverConfig, Objs must not be empty.") objs = objs or [] nodes = [ObjectNode(text=obj.rag_key(), metadata=ObjectNode.get_obj_metadata(obj)) for obj in objs] index = VectorStoreIndex( nodes=nodes, transformations=transformations or [SentenceSplitter()], embed_model=cls._resolve_embed_model(embed_model, retriever_configs), ) return cls._from_index(index, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs) @classmethod def from_index( cls, index_config: BaseIndexConfig, embed_model: BaseEmbedding = None, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": """Load from previously maintained index by self.persist(), index_config contains persis_path.""" index = get_index(index_config, embed_model=cls._resolve_embed_model(embed_model, [index_config])) return cls._from_index(index, llm=llm, retriever_configs=retriever_configs, ranker_configs=ranker_configs) async def asearch(self, content: str, **kwargs) -> str: """Inplement tools.SearchInterface""" return await self.aquery(content) async def aretrieve(self, query: QueryType) -> list[NodeWithScore]: """Allow query to be str.""" query_bundle = QueryBundle(query) if isinstance(query, str) else query nodes = await super().aretrieve(query_bundle) self._try_reconstruct_obj(nodes) return nodes def add_docs(self, input_files: list[str]): """Add docs to retriever. retriever must has add_nodes func.""" self._ensure_retriever_modifiable() documents = SimpleDirectoryReader(input_files=input_files).load_data() self._fix_document_metadata(documents) nodes = run_transformations(documents, transformations=self.index._transformations) self._save_nodes(nodes) def add_objs(self, objs: list[RAGObject]): """Adds objects to the retriever, storing each object's original form in metadata for future reference.""" self._ensure_retriever_modifiable() nodes = [ObjectNode(text=obj.rag_key(), metadata=ObjectNode.get_obj_metadata(obj)) for obj in objs] self._save_nodes(nodes) def persist(self, persist_dir: Union[str, os.PathLike], **kwargs): """Persist.""" self._ensure_retriever_persistable() self._persist(str(persist_dir), **kwargs) @classmethod def _from_index( cls, index: BaseIndex, llm: LLM = None, retriever_configs: list[BaseRetrieverConfig] = None, ranker_configs: list[BaseRankerConfig] = None, ) -> "SimpleEngine": llm = llm or get_rag_llm() retriever = get_retriever(configs=retriever_configs, index=index) # Default index.as_retriever rankers = get_rankers(configs=ranker_configs, llm=llm) # Default [] return cls( retriever=retriever, node_postprocessors=rankers, response_synthesizer=get_response_synthesizer(llm=llm), index=index, ) def _ensure_retriever_modifiable(self): self._ensure_retriever_of_type(ModifiableRAGRetriever) def _ensure_retriever_persistable(self): self._ensure_retriever_of_type(PersistableRAGRetriever) def _ensure_retriever_of_type(self, required_type: BaseRetriever): """Ensure that self.retriever is required_type, or at least one of its components, if it's a SimpleHybridRetriever. Args: required_type: The class that the retriever is expected to be an instance of. """ if isinstance(self.retriever, SimpleHybridRetriever): if not any(isinstance(r, required_type) for r in self.retriever.retrievers): raise TypeError( f"Must have at least one retriever of type {required_type.__name__} in SimpleHybridRetriever" ) if not isinstance(self.retriever, required_type): raise TypeError(f"The retriever is not of type {required_type.__name__}: {type(self.retriever)}") def _save_nodes(self, nodes: list[BaseNode]): self.retriever.add_nodes(nodes) def _persist(self, persist_dir: str, **kwargs): self.retriever.persist(persist_dir, **kwargs) @staticmethod def _try_reconstruct_obj(nodes: list[NodeWithScore]): """If node is object, then dynamically reconstruct object, and save object to node.metadata["obj"].""" for node in nodes: if node.metadata.get("is_obj", False): obj_cls = import_class(node.metadata["obj_cls_name"], node.metadata["obj_mod_name"]) obj_dict = json.loads(node.metadata["obj_json"]) node.metadata["obj"] = obj_cls(**obj_dict) @staticmethod def _fix_document_metadata(documents: list[Document]): """LlamaIndex keep metadata['file_path'], which is unnecessary, maybe deleted in the near future.""" for doc in documents: doc.excluded_embed_metadata_keys.append("file_path") @staticmethod def _resolve_embed_model(embed_model: BaseEmbedding = None, configs: list[Any] = None) -> BaseEmbedding: if configs and all(isinstance(c, NoEmbedding) for c in configs): return MockEmbedding(embed_dim=1) return embed_model or get_rag_embedding()
[ "llama_index.core.node_parser.SentenceSplitter", "llama_index.core.response_synthesizers.get_response_synthesizer", "llama_index.core.ingestion.pipeline.run_transformations", "llama_index.core.embeddings.mock_embed_model.MockEmbedding", "llama_index.core.schema.QueryBundle", "llama_index.core.SimpleDirectoryReader" ]
[((7145, 7220), 'llama_index.core.ingestion.pipeline.run_transformations', 'run_transformations', (['documents'], {'transformations': 'self.index._transformations'}), '(documents, transformations=self.index._transformations)\n', (7164, 7220), False, 'from llama_index.core.ingestion.pipeline import run_transformations\n'), ((8091, 8144), 'metagpt.rag.factories.get_retriever', 'get_retriever', ([], {'configs': 'retriever_configs', 'index': 'index'}), '(configs=retriever_configs, index=index)\n', (8104, 8144), False, 'from metagpt.rag.factories import get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever\n'), ((8193, 8237), 'metagpt.rag.factories.get_rankers', 'get_rankers', ([], {'configs': 'ranker_configs', 'llm': 'llm'}), '(configs=ranker_configs, llm=llm)\n', (8204, 8237), False, 'from metagpt.rag.factories import get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever\n'), ((6663, 6681), 'llama_index.core.schema.QueryBundle', 'QueryBundle', (['query'], {}), '(query)\n', (6674, 6681), False, 'from llama_index.core.schema import BaseNode, Document, NodeWithScore, QueryBundle, QueryType, TransformComponent\n'), ((8057, 8070), 'metagpt.rag.factories.get_rag_llm', 'get_rag_llm', ([], {}), '()\n', (8068, 8070), False, 'from metagpt.rag.factories import get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever\n'), ((10657, 10683), 'llama_index.core.embeddings.mock_embed_model.MockEmbedding', 'MockEmbedding', ([], {'embed_dim': '(1)'}), '(embed_dim=1)\n', (10670, 10683), False, 'from llama_index.core.embeddings.mock_embed_model import MockEmbedding\n'), ((10715, 10734), 'metagpt.rag.factories.get_rag_embedding', 'get_rag_embedding', ([], {}), '()\n', (10732, 10734), False, 'from metagpt.rag.factories import get_index, get_rag_embedding, get_rag_llm, get_rankers, get_retriever\n'), ((3729, 3796), 'llama_index.core.SimpleDirectoryReader', 'SimpleDirectoryReader', ([], {'input_dir': 'input_dir', 'input_files': 'input_files'}), '(input_dir=input_dir, input_files=input_files)\n', (3750, 3796), False, 'from llama_index.core import SimpleDirectoryReader, VectorStoreIndex\n'), ((7022, 7068), 'llama_index.core.SimpleDirectoryReader', 'SimpleDirectoryReader', ([], {'input_files': 'input_files'}), '(input_files=input_files)\n', (7043, 7068), False, 'from llama_index.core import SimpleDirectoryReader, VectorStoreIndex\n'), ((8380, 8413), 'llama_index.core.response_synthesizers.get_response_synthesizer', 'get_response_synthesizer', ([], {'llm': 'llm'}), '(llm=llm)\n', (8404, 8413), False, 'from llama_index.core.response_synthesizers import BaseSynthesizer, get_response_synthesizer\n'), ((9956, 10030), 'metagpt.utils.common.import_class', 'import_class', (["node.metadata['obj_cls_name']", "node.metadata['obj_mod_name']"], {}), "(node.metadata['obj_cls_name'], node.metadata['obj_mod_name'])\n", (9968, 10030), False, 'from metagpt.utils.common import import_class\n'), ((10058, 10095), 'json.loads', 'json.loads', (["node.metadata['obj_json']"], {}), "(node.metadata['obj_json'])\n", (10068, 10095), False, 'import json\n'), ((5368, 5400), 'metagpt.rag.schema.ObjectNode.get_obj_metadata', 'ObjectNode.get_obj_metadata', (['obj'], {}), '(obj)\n', (5395, 5400), False, 'from metagpt.rag.schema import BaseIndexConfig, BaseRankerConfig, BaseRetrieverConfig, BM25RetrieverConfig, ObjectNode\n'), ((7518, 7550), 'metagpt.rag.schema.ObjectNode.get_obj_metadata', 'ObjectNode.get_obj_metadata', (['obj'], {}), '(obj)\n', (7545, 7550), False, 'from metagpt.rag.schema import BaseIndexConfig, BaseRankerConfig, BaseRetrieverConfig, BM25RetrieverConfig, ObjectNode\n'), ((3986, 4004), 'llama_index.core.node_parser.SentenceSplitter', 'SentenceSplitter', ([], {}), '()\n', (4002, 4004), False, 'from llama_index.core.node_parser import SentenceSplitter\n'), ((5526, 5544), 'llama_index.core.node_parser.SentenceSplitter', 'SentenceSplitter', ([], {}), '()\n', (5542, 5544), False, 'from llama_index.core.node_parser import SentenceSplitter\n')]
import os from typing import Optional, Dict import openai import pandas as pd import llama_index from llama_index.llms.openai import OpenAI from llama_index.readers.schema.base import Document from llama_index.readers import SimpleWebPageReader from llama_index.prompts import PromptTemplate from llama_index import ServiceContext, StorageContext, load_index_from_storage from llama_index import LLMPredictor, OpenAIEmbedding from llama_index.indices.vector_store.base import VectorStore from llama_hub.github_repo import GithubClient, GithubRepositoryReader from llama_hub.youtube_transcript import YoutubeTranscriptReader, is_youtube_video from mindsdb.integrations.libs.base import BaseMLEngine from mindsdb.utilities.config import Config from mindsdb.utilities.security import is_private_url from mindsdb.integrations.handlers.llama_index_handler import config from mindsdb.integrations.handlers.llama_index_handler.github_loader_helper import ( _get_github_token, _get_filter_file_extensions, _get_filter_directories, ) from mindsdb.integrations.utilities.handler_utils import get_api_key def _validate_prompt_template(prompt_template: str): if "{context_str}" not in prompt_template or "{query_str}" not in prompt_template: raise Exception( "Provided prompt template is invalid, missing `{context_str}`, `{query_str}`. Please ensure both placeholders are present and try again." ) # noqa class LlamaIndexHandler(BaseMLEngine): """Integration with the LlamaIndex data framework for LLM applications.""" name = "llama_index" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.generative = True self.default_index_class = "GPTVectorStoreIndex" self.supported_index_class = ["GPTVectorStoreIndex", "VectorStoreIndex"] self.default_reader = "DFReader" self.supported_reader = [ "DFReader", "SimpleWebPageReader", "GithubRepositoryReader", "YoutubeTranscriptReader", ] @staticmethod def create_validation(target, args=None, **kwargs): reader = args["using"].get("reader", "DFReader") if reader not in config.data_loaders: raise Exception( f"Invalid reader argument. Please use one of {config.data_loaders.keys()}" ) config_dict = config.data_loaders[reader] missing_keys = [key for key in config_dict if key not in args["using"]] if missing_keys: raise Exception(f"{reader} requires {missing_keys} arguments") if "prompt_template" in args["using"]: _validate_prompt_template(args["using"]["prompt_template"]) if args["using"].get("mode") == "conversational": for param in ("user_column", "assistant_column"): if param not in args["using"]: raise Exception(f"Conversational mode requires {param} parameter") def create( self, target: str, df: Optional[pd.DataFrame] = None, args: Optional[Dict] = None, ) -> None: if "using" not in args: raise Exception( "LlamaIndex engine requires a USING clause! Refer to its documentation for more details." ) if "index_class" not in args["using"]: args["using"]["index_class"] = self.default_index_class elif args["using"]["index_class"] not in self.supported_index_class: raise Exception( f"Invalid index class argument. Please use one of {self.supported_index_class}" ) if "reader" not in args["using"]: args["using"]["reader"] = self.default_reader elif args["using"]["reader"] not in self.supported_reader: raise Exception( f"Invalid operation mode. Please use one of {self.supported_reader}" ) # workaround to create llama model without input data if df is None or df.empty: df = pd.DataFrame([{"text": ""}]) if args["using"]["reader"] == "DFReader": dstrs = df.apply( lambda x: ", ".join( [f"{col}: {str(entry)}" for col, entry in zip(df.columns, x)] ), axis=1, ) reader = list(map(lambda x: Document(text=x), dstrs.tolist())) elif args["using"]["reader"] == "SimpleWebPageReader": url = args["using"]["source_url_link"] config = Config() is_cloud = config.get("cloud", False) if is_cloud and is_private_url(url): raise Exception(f"URL is private: {url}") reader = SimpleWebPageReader(html_to_text=True).load_data([url]) elif args["using"]["reader"] == "GithubRepositoryReader": engine_storage = self.engine_storage key = "GITHUB_TOKEN" github_token = get_api_key( key, args["using"], engine_storage, strict=False ) if github_token is None: github_token = get_api_key( key.lower(), args["using"], engine_storage, strict=True, ) github_client = GithubClient(github_token) owner = args["using"]["owner"] repo = args["using"]["repo"] filter_file_extensions = _get_filter_file_extensions(args["using"]) filter_directories = _get_filter_directories(args["using"]) reader = GithubRepositoryReader( github_client, owner=owner, repo=repo, verbose=True, filter_file_extensions=filter_file_extensions, filter_directories=filter_directories, ).load_data(branch=args["using"].get("branch", "main")) elif args["using"]["reader"] == "YoutubeTranscriptReader": ytlinks = args["using"]["ytlinks"] for link in ytlinks: if not is_youtube_video(link): raise Exception(f"Invalid youtube link: {link}") reader = YoutubeTranscriptReader().load_data(ytlinks) else: raise Exception( f"Invalid operation mode. Please use one of {self.supported_reader}." ) self.model_storage.json_set("args", args) index = self._setup_index(reader) path = self.model_storage.folder_get("context") index.storage_context.persist(persist_dir=path) self.model_storage.folder_sync("context") def update(self, args) -> None: prompt_template = args["using"].get( "prompt_template", args.get("prompt_template", None) ) if prompt_template is not None: _validate_prompt_template(prompt_template) args_cur = self.model_storage.json_get("args") args_cur["using"].update(args["using"]) # check new set of arguments self.create_validation(None, args_cur) self.model_storage.json_set("args", args_cur) def predict( self, df: Optional[pd.DataFrame] = None, args: Optional[Dict] = None ) -> pd.DataFrame: pred_args = args["predict_params"] if args else {} args = self.model_storage.json_get("args") engine_kwargs = {} if args["using"].get("mode") == "conversational": user_column = args["using"]["user_column"] assistant_column = args["using"]["assistant_column"] messages = [] for row in df[:-1].to_dict("records"): messages.append(f"user: {row[user_column]}") messages.append(f"assistant: {row[assistant_column]}") conversation = "\n".join(messages) questions = [df.iloc[-1][user_column]] if "prompt" in pred_args and pred_args["prompt"] is not None: user_prompt = pred_args["prompt"] else: user_prompt = args["using"].get("prompt", "") prompt_template = ( f"{user_prompt}\n" f"---------------------\n" f"We have provided context information below. \n" f"{{context_str}}\n" f"---------------------\n" f"This is previous conversation history:\n" f"{conversation}\n" f"---------------------\n" f"Given this information, please answer the question: {{query_str}}" ) engine_kwargs["text_qa_template"] = PromptTemplate(prompt_template) else: input_column = args["using"].get("input_column", None) prompt_template = args["using"].get( "prompt_template", args.get("prompt_template", None) ) if prompt_template is not None: _validate_prompt_template(prompt_template) engine_kwargs["text_qa_template"] = PromptTemplate(prompt_template) if input_column is None: raise Exception( f"`input_column` must be provided at model creation time or through USING clause when predicting. Please try again." ) # noqa if input_column not in df.columns: raise Exception( f'Column "{input_column}" not found in input data! Please try again.' ) questions = df[input_column] index_path = self.model_storage.folder_get("context") storage_context = StorageContext.from_defaults(persist_dir=index_path) service_context = self._get_service_context() index = load_index_from_storage( storage_context, service_context=service_context ) query_engine = index.as_query_engine(**engine_kwargs) results = [] for question in questions: query_results = query_engine.query( question ) # TODO: provide extra_info in explain_target col results.append(query_results.response) result_df = pd.DataFrame( {"question": questions, args["target"]: results} ) # result_df['answer'].tolist() return result_df def _get_service_context(self): args = self.model_storage.json_get("args") engine_storage = self.engine_storage openai_api_key = get_api_key('openai', args["using"], engine_storage, strict=True) llm_kwargs = {"openai_api_key": openai_api_key} if "temperature" in args["using"]: llm_kwargs["temperature"] = args["using"]["temperature"] if "model_name" in args["using"]: llm_kwargs["model_name"] = args["using"]["model_name"] if "max_tokens" in args["using"]: llm_kwargs["max_tokens"] = args["using"]["max_tokens"] llm = OpenAI(**llm_kwargs) # TODO: all usual params should go here embed_model = OpenAIEmbedding(api_key=openai_api_key) service_context = ServiceContext.from_defaults( llm=llm, embed_model=embed_model ) return service_context def _setup_index(self, documents): args = self.model_storage.json_get("args") indexer: VectorStore = getattr(llama_index, args["using"]["index_class"]) index = indexer.from_documents( documents, service_context=self._get_service_context() ) return index
[ "llama_index.readers.SimpleWebPageReader", "llama_index.llms.openai.OpenAI", "llama_index.ServiceContext.from_defaults", "llama_index.OpenAIEmbedding", "llama_index.prompts.PromptTemplate", "llama_index.StorageContext.from_defaults", "llama_index.load_index_from_storage", "llama_index.readers.schema.base.Document" ]
[((9647, 9699), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': 'index_path'}), '(persist_dir=index_path)\n', (9675, 9699), False, 'from llama_index import ServiceContext, StorageContext, load_index_from_storage\n'), ((9770, 9843), 'llama_index.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {'service_context': 'service_context'}), '(storage_context, service_context=service_context)\n', (9793, 9843), False, 'from llama_index import ServiceContext, StorageContext, load_index_from_storage\n'), ((10195, 10257), 'pandas.DataFrame', 'pd.DataFrame', (["{'question': questions, args['target']: results}"], {}), "({'question': questions, args['target']: results})\n", (10207, 10257), True, 'import pandas as pd\n'), ((10496, 10561), 'mindsdb.integrations.utilities.handler_utils.get_api_key', 'get_api_key', (['"""openai"""', "args['using']", 'engine_storage'], {'strict': '(True)'}), "('openai', args['using'], engine_storage, strict=True)\n", (10507, 10561), False, 'from mindsdb.integrations.utilities.handler_utils import get_api_key\n'), ((10964, 10984), 'llama_index.llms.openai.OpenAI', 'OpenAI', ([], {}), '(**llm_kwargs)\n', (10970, 10984), False, 'from llama_index.llms.openai import OpenAI\n'), ((11048, 11087), 'llama_index.OpenAIEmbedding', 'OpenAIEmbedding', ([], {'api_key': 'openai_api_key'}), '(api_key=openai_api_key)\n', (11063, 11087), False, 'from llama_index import LLMPredictor, OpenAIEmbedding\n'), ((11114, 11176), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'llm': 'llm', 'embed_model': 'embed_model'}), '(llm=llm, embed_model=embed_model)\n', (11142, 11176), False, 'from llama_index import ServiceContext, StorageContext, load_index_from_storage\n'), ((4055, 4083), 'pandas.DataFrame', 'pd.DataFrame', (["[{'text': ''}]"], {}), "([{'text': ''}])\n", (4067, 4083), True, 'import pandas as pd\n'), ((8659, 8690), 'llama_index.prompts.PromptTemplate', 'PromptTemplate', (['prompt_template'], {}), '(prompt_template)\n', (8673, 8690), False, 'from llama_index.prompts import PromptTemplate\n'), ((4552, 4560), 'mindsdb.utilities.config.Config', 'Config', ([], {}), '()\n', (4558, 4560), False, 'from mindsdb.utilities.config import Config\n'), ((4584, 4610), 'mindsdb.integrations.handlers.llama_index_handler.config.get', 'config.get', (['"""cloud"""', '(False)'], {}), "('cloud', False)\n", (4594, 4610), False, 'from mindsdb.integrations.handlers.llama_index_handler import config\n'), ((9061, 9092), 'llama_index.prompts.PromptTemplate', 'PromptTemplate', (['prompt_template'], {}), '(prompt_template)\n', (9075, 9092), False, 'from llama_index.prompts import PromptTemplate\n'), ((4639, 4658), 'mindsdb.utilities.security.is_private_url', 'is_private_url', (['url'], {}), '(url)\n', (4653, 4658), False, 'from mindsdb.utilities.security import is_private_url\n'), ((4972, 5033), 'mindsdb.integrations.utilities.handler_utils.get_api_key', 'get_api_key', (['key', "args['using']", 'engine_storage'], {'strict': '(False)'}), "(key, args['using'], engine_storage, strict=False)\n", (4983, 5033), False, 'from mindsdb.integrations.utilities.handler_utils import get_api_key\n'), ((5329, 5355), 'llama_hub.github_repo.GithubClient', 'GithubClient', (['github_token'], {}), '(github_token)\n', (5341, 5355), False, 'from llama_hub.github_repo import GithubClient, GithubRepositoryReader\n'), ((5477, 5519), 'mindsdb.integrations.handlers.llama_index_handler.github_loader_helper._get_filter_file_extensions', '_get_filter_file_extensions', (["args['using']"], {}), "(args['using'])\n", (5504, 5519), False, 'from mindsdb.integrations.handlers.llama_index_handler.github_loader_helper import _get_github_token, _get_filter_file_extensions, _get_filter_directories\n'), ((5553, 5591), 'mindsdb.integrations.handlers.llama_index_handler.github_loader_helper._get_filter_directories', '_get_filter_directories', (["args['using']"], {}), "(args['using'])\n", (5576, 5591), False, 'from mindsdb.integrations.handlers.llama_index_handler.github_loader_helper import _get_github_token, _get_filter_file_extensions, _get_filter_directories\n'), ((2335, 2361), 'mindsdb.integrations.handlers.llama_index_handler.config.data_loaders.keys', 'config.data_loaders.keys', ([], {}), '()\n', (2359, 2361), False, 'from mindsdb.integrations.handlers.llama_index_handler import config\n'), ((4381, 4397), 'llama_index.readers.schema.base.Document', 'Document', ([], {'text': 'x'}), '(text=x)\n', (4389, 4397), False, 'from llama_index.readers.schema.base import Document\n'), ((4740, 4778), 'llama_index.readers.SimpleWebPageReader', 'SimpleWebPageReader', ([], {'html_to_text': '(True)'}), '(html_to_text=True)\n', (4759, 4778), False, 'from llama_index.readers import SimpleWebPageReader\n'), ((5614, 5784), 'llama_hub.github_repo.GithubRepositoryReader', 'GithubRepositoryReader', (['github_client'], {'owner': 'owner', 'repo': 'repo', 'verbose': '(True)', 'filter_file_extensions': 'filter_file_extensions', 'filter_directories': 'filter_directories'}), '(github_client, owner=owner, repo=repo, verbose=True,\n filter_file_extensions=filter_file_extensions, filter_directories=\n filter_directories)\n', (5636, 5784), False, 'from llama_hub.github_repo import GithubClient, GithubRepositoryReader\n'), ((6112, 6134), 'llama_hub.youtube_transcript.is_youtube_video', 'is_youtube_video', (['link'], {}), '(link)\n', (6128, 6134), False, 'from llama_hub.youtube_transcript import YoutubeTranscriptReader, is_youtube_video\n'), ((6226, 6251), 'llama_hub.youtube_transcript.YoutubeTranscriptReader', 'YoutubeTranscriptReader', ([], {}), '()\n', (6249, 6251), False, 'from llama_hub.youtube_transcript import YoutubeTranscriptReader, is_youtube_video\n')]
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import os from typing import Any, Callable, Dict, Optional, Sequence from llama_index.bridge.pydantic import Field, PrivateAttr from llama_index.callbacks import CallbackManager from llama_index.constants import DEFAULT_CONTEXT_WINDOW, DEFAULT_NUM_OUTPUTS from llama_index.llms.base import ( ChatMessage, ChatResponse, CompletionResponse, LLMMetadata, llm_chat_callback, llm_completion_callback, ) from llama_index.llms.custom import CustomLLM from llama_index.llms.generic_utils import completion_response_to_chat_response from llama_index.llms.generic_utils import ( messages_to_prompt as generic_messages_to_prompt, ) from transformers import LlamaTokenizer import gc import json import torch import numpy as np from tensorrt_llm.runtime import ModelConfig, SamplingConfig import tensorrt_llm from pathlib import Path import uuid import time EOS_TOKEN = 2 PAD_TOKEN = 2 class TrtLlmAPI(CustomLLM): model_path: Optional[str] = Field( description="The path to the trt engine." ) temperature: float = Field(description="The temperature to use for sampling.") max_new_tokens: int = Field(description="The maximum number of tokens to generate.") context_window: int = Field( description="The maximum number of context tokens for the model." ) messages_to_prompt: Callable = Field( description="The function to convert messages to a prompt.", exclude=True ) completion_to_prompt: Callable = Field( description="The function to convert a completion to a prompt.", exclude=True ) generate_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Kwargs used for generation." ) model_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Kwargs used for model initialization." ) verbose: bool = Field(description="Whether to print verbose output.") _model: Any = PrivateAttr() _model_config: Any = PrivateAttr() _tokenizer: Any = PrivateAttr() _max_new_tokens = PrivateAttr() _sampling_config = PrivateAttr() _verbose = PrivateAttr() def __init__( self, model_path: Optional[str] = None, engine_name: Optional[str] = None, tokenizer_dir: Optional[str] = None, temperature: float = 0.1, max_new_tokens: int = DEFAULT_NUM_OUTPUTS, context_window: int = DEFAULT_CONTEXT_WINDOW, messages_to_prompt: Optional[Callable] = None, completion_to_prompt: Optional[Callable] = None, callback_manager: Optional[CallbackManager] = None, generate_kwargs: Optional[Dict[str, Any]] = None, model_kwargs: Optional[Dict[str, Any]] = None, verbose: bool = False ) -> None: model_kwargs = model_kwargs or {} model_kwargs.update({"n_ctx": context_window, "verbose": verbose}) self._max_new_tokens = max_new_tokens self._verbose = verbose # check if model is cached if model_path is not None: if not os.path.exists(model_path): raise ValueError( "Provided model path does not exist. " "Please check the path or provide a model_url to download." ) else: engine_dir = model_path engine_dir_path = Path(engine_dir) config_path = engine_dir_path / 'config.json' # config function with open(config_path, 'r') as f: config = json.load(f) use_gpt_attention_plugin = config['plugin_config']['gpt_attention_plugin'] remove_input_padding = config['plugin_config']['remove_input_padding'] tp_size = config['builder_config']['tensor_parallel'] pp_size = config['builder_config']['pipeline_parallel'] world_size = tp_size * pp_size assert world_size == tensorrt_llm.mpi_world_size(), \ f'Engine world size ({world_size}) != Runtime world size ({tensorrt_llm.mpi_world_size()})' num_heads = config['builder_config']['num_heads'] // tp_size hidden_size = config['builder_config']['hidden_size'] // tp_size vocab_size = config['builder_config']['vocab_size'] num_layers = config['builder_config']['num_layers'] num_kv_heads = config['builder_config'].get('num_kv_heads', num_heads) paged_kv_cache = config['plugin_config']['paged_kv_cache'] if config['builder_config'].get('multi_query_mode', False): tensorrt_llm.logger.warning( "`multi_query_mode` config is deprecated. Please rebuild the engine." ) num_kv_heads = 1 num_kv_heads = (num_kv_heads + tp_size - 1) // tp_size self._model_config = ModelConfig(num_heads=num_heads, num_kv_heads=num_kv_heads, hidden_size=hidden_size, vocab_size=vocab_size, num_layers=num_layers, gpt_attention_plugin=use_gpt_attention_plugin, paged_kv_cache=paged_kv_cache, remove_input_padding=remove_input_padding) assert pp_size == 1, 'Python runtime does not support pipeline parallelism' world_size = tp_size * pp_size runtime_rank = tensorrt_llm.mpi_rank() runtime_mapping = tensorrt_llm.Mapping(world_size, runtime_rank, tp_size=tp_size, pp_size=pp_size) torch.cuda.set_device(runtime_rank % runtime_mapping.gpus_per_node) self._tokenizer = LlamaTokenizer.from_pretrained(tokenizer_dir, legacy=False) self._sampling_config = SamplingConfig(end_id=EOS_TOKEN, pad_id=PAD_TOKEN, num_beams=1, temperature=temperature) serialize_path = engine_dir_path / engine_name with open(serialize_path, 'rb') as f: engine_buffer = f.read() decoder = tensorrt_llm.runtime.GenerationSession(self._model_config, engine_buffer, runtime_mapping, debug_mode=False) self._model = decoder messages_to_prompt = messages_to_prompt or generic_messages_to_prompt completion_to_prompt = completion_to_prompt or (lambda x: x) generate_kwargs = generate_kwargs or {} generate_kwargs.update( {"temperature": temperature, "max_tokens": max_new_tokens} ) super().__init__( model_path=model_path, temperature=temperature, context_window=context_window, max_new_tokens=max_new_tokens, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, callback_manager=callback_manager, generate_kwargs=generate_kwargs, model_kwargs=model_kwargs, verbose=verbose, ) @classmethod def class_name(cls) -> str: """Get class name.""" return "TrtLlmAPI" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( context_window=self.context_window, num_output=self.max_new_tokens, model_name=self.model_path, ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, formatted=True, **kwargs) return completion_response_to_chat_response(completion_response) @llm_completion_callback() def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: self.generate_kwargs.update({"stream": False}) is_formatted = kwargs.pop("formatted", False) if not is_formatted: prompt = self.completion_to_prompt(prompt) input_text = prompt input_ids, input_lengths = self.parse_input(input_text, self._tokenizer, EOS_TOKEN, self._model_config) max_input_length = torch.max(input_lengths).item() self._model.setup(input_lengths.size(0), max_input_length, self._max_new_tokens, 1) # beam size is set to 1 if self._verbose: start_time = time.time() output_ids = self._model.decode(input_ids, input_lengths, self._sampling_config) torch.cuda.synchronize() elapsed_time = None if self._verbose: end_time = time.time() elapsed_time = end_time - start_time output_txt, output_token_ids = self.get_output(output_ids, input_lengths, self._max_new_tokens, self._tokenizer) if self._verbose: print(f"Input context length : {input_ids.shape[1]}") print(f"Inference time : {elapsed_time:.2f} seconds") print(f"Output context length : {len(output_token_ids)} ") print(f"Inference token/sec : {(len(output_token_ids) / elapsed_time):2f}") # call garbage collected after inference torch.cuda.empty_cache() gc.collect() return CompletionResponse(text=output_txt, raw=self.generate_completion_dict(output_txt)) def parse_input(self, input_text: str, tokenizer, end_id: int, remove_input_padding: bool): input_tokens = [] input_tokens.append( tokenizer.encode(input_text, add_special_tokens=False)) input_lengths = torch.tensor([len(x) for x in input_tokens], dtype=torch.int32, device='cuda') if remove_input_padding: input_ids = np.concatenate(input_tokens) input_ids = torch.tensor(input_ids, dtype=torch.int32, device='cuda').unsqueeze(0) else: input_ids = torch.nested.to_padded_tensor( torch.nested.nested_tensor(input_tokens, dtype=torch.int32), end_id).cuda() return input_ids, input_lengths def remove_extra_eos_ids(self, outputs): outputs.reverse() while outputs and outputs[0] == 2: outputs.pop(0) outputs.reverse() outputs.append(2) return outputs def get_output(self, output_ids, input_lengths, max_output_len, tokenizer): num_beams = output_ids.size(1) output_text = "" outputs = None for b in range(input_lengths.size(0)): for beam in range(num_beams): output_begin = input_lengths[b] output_end = input_lengths[b] + max_output_len outputs = output_ids[b][beam][output_begin:output_end].tolist() outputs = self.remove_extra_eos_ids(outputs) output_text = tokenizer.decode(outputs) return output_text, outputs def generate_completion_dict(self, text_str): """ Generate a dictionary for text completion details. Returns: dict: A dictionary containing completion details. """ completion_id: str = f"cmpl-{str(uuid.uuid4())}" created: int = int(time.time()) model_name: str = self._model if self._model is not None else self.model_path return { "id": completion_id, "object": "text_completion", "created": created, "model": model_name, "choices": [ { "text": text_str, "index": 0, "logprobs": None, "finish_reason": 'stop' } ], "usage": { "prompt_tokens": None, "completion_tokens": None, "total_tokens": None } } @llm_completion_callback() def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponse: pass
[ "llama_index.llms.base.llm_chat_callback", "llama_index.llms.base.LLMMetadata", "llama_index.bridge.pydantic.Field", "llama_index.llms.generic_utils.completion_response_to_chat_response", "llama_index.bridge.pydantic.PrivateAttr", "llama_index.llms.base.llm_completion_callback" ]
[((2151, 2199), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The path to the trt engine."""'}), "(description='The path to the trt engine.')\n", (2156, 2199), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2239, 2296), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The temperature to use for sampling."""'}), "(description='The temperature to use for sampling.')\n", (2244, 2296), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2323, 2385), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of tokens to generate."""'}), "(description='The maximum number of tokens to generate.')\n", (2328, 2385), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2412, 2484), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The maximum number of context tokens for the model."""'}), "(description='The maximum number of context tokens for the model.')\n", (2417, 2484), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2534, 2619), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The function to convert messages to a prompt."""', 'exclude': '(True)'}), "(description='The function to convert messages to a prompt.', exclude=True\n )\n", (2539, 2619), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2666, 2754), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""The function to convert a completion to a prompt."""', 'exclude': '(True)'}), "(description='The function to convert a completion to a prompt.',\n exclude=True)\n", (2671, 2754), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2803, 2873), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Kwargs used for generation."""'}), "(default_factory=dict, description='Kwargs used for generation.')\n", (2808, 2873), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((2923, 3008), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'default_factory': 'dict', 'description': '"""Kwargs used for model initialization."""'}), "(default_factory=dict, description='Kwargs used for model initialization.'\n )\n", (2928, 3008), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3038, 3091), 'llama_index.bridge.pydantic.Field', 'Field', ([], {'description': '"""Whether to print verbose output."""'}), "(description='Whether to print verbose output.')\n", (3043, 3091), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3111, 3124), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3122, 3124), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3150, 3163), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3161, 3163), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3186, 3199), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3197, 3199), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3222, 3235), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3233, 3235), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3259, 3272), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3270, 3272), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((3288, 3301), 'llama_index.bridge.pydantic.PrivateAttr', 'PrivateAttr', ([], {}), '()\n', (3299, 3301), False, 'from llama_index.bridge.pydantic import Field, PrivateAttr\n'), ((9389, 9408), 'llama_index.llms.base.llm_chat_callback', 'llm_chat_callback', ([], {}), '()\n', (9406, 9408), False, 'from llama_index.llms.base import ChatMessage, ChatResponse, CompletionResponse, LLMMetadata, llm_chat_callback, llm_completion_callback\n'), ((9701, 9726), 'llama_index.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (9724, 9726), False, 'from llama_index.llms.base import ChatMessage, ChatResponse, CompletionResponse, LLMMetadata, llm_chat_callback, llm_completion_callback\n'), ((14134, 14159), 'llama_index.llms.base.llm_completion_callback', 'llm_completion_callback', ([], {}), '()\n', (14157, 14159), False, 'from llama_index.llms.base import ChatMessage, ChatResponse, CompletionResponse, LLMMetadata, llm_chat_callback, llm_completion_callback\n'), ((9228, 9340), 'llama_index.llms.base.LLMMetadata', 'LLMMetadata', ([], {'context_window': 'self.context_window', 'num_output': 'self.max_new_tokens', 'model_name': 'self.model_path'}), '(context_window=self.context_window, num_output=self.\n max_new_tokens, model_name=self.model_path)\n', (9239, 9340), False, 'from llama_index.llms.base import ChatMessage, ChatResponse, CompletionResponse, LLMMetadata, llm_chat_callback, llm_completion_callback\n'), ((9637, 9694), 'llama_index.llms.generic_utils.completion_response_to_chat_response', 'completion_response_to_chat_response', (['completion_response'], {}), '(completion_response)\n', (9673, 9694), False, 'from llama_index.llms.generic_utils import completion_response_to_chat_response\n'), ((10577, 10601), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (10599, 10601), False, 'import torch\n'), ((11367, 11391), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (11389, 11391), False, 'import torch\n'), ((11400, 11412), 'gc.collect', 'gc.collect', ([], {}), '()\n', (11410, 11412), False, 'import gc\n'), ((10467, 10478), 'time.time', 'time.time', ([], {}), '()\n', (10476, 10478), False, 'import time\n'), ((10680, 10691), 'time.time', 'time.time', ([], {}), '()\n', (10689, 10691), False, 'import time\n'), ((11988, 12016), 'numpy.concatenate', 'np.concatenate', (['input_tokens'], {}), '(input_tokens)\n', (12002, 12016), True, 'import numpy as np\n'), ((13479, 13490), 'time.time', 'time.time', ([], {}), '()\n', (13488, 13490), False, 'import time\n'), ((4271, 4297), 'os.path.exists', 'os.path.exists', (['model_path'], {}), '(model_path)\n', (4285, 4297), False, 'import os\n'), ((4582, 4598), 'pathlib.Path', 'Path', (['engine_dir'], {}), '(engine_dir)\n', (4586, 4598), False, 'from pathlib import Path\n'), ((6180, 6445), 'tensorrt_llm.runtime.ModelConfig', 'ModelConfig', ([], {'num_heads': 'num_heads', 'num_kv_heads': 'num_kv_heads', 'hidden_size': 'hidden_size', 'vocab_size': 'vocab_size', 'num_layers': 'num_layers', 'gpt_attention_plugin': 'use_gpt_attention_plugin', 'paged_kv_cache': 'paged_kv_cache', 'remove_input_padding': 'remove_input_padding'}), '(num_heads=num_heads, num_kv_heads=num_kv_heads, hidden_size=\n hidden_size, vocab_size=vocab_size, num_layers=num_layers,\n gpt_attention_plugin=use_gpt_attention_plugin, paged_kv_cache=\n paged_kv_cache, remove_input_padding=remove_input_padding)\n', (6191, 6445), False, 'from tensorrt_llm.runtime import ModelConfig, SamplingConfig\n'), ((6947, 6970), 'tensorrt_llm.mpi_rank', 'tensorrt_llm.mpi_rank', ([], {}), '()\n', (6968, 6970), False, 'import tensorrt_llm\n'), ((7005, 7090), 'tensorrt_llm.Mapping', 'tensorrt_llm.Mapping', (['world_size', 'runtime_rank'], {'tp_size': 'tp_size', 'pp_size': 'pp_size'}), '(world_size, runtime_rank, tp_size=tp_size, pp_size=pp_size\n )\n', (7025, 7090), False, 'import tensorrt_llm\n'), ((7267, 7334), 'torch.cuda.set_device', 'torch.cuda.set_device', (['(runtime_rank % runtime_mapping.gpus_per_node)'], {}), '(runtime_rank % runtime_mapping.gpus_per_node)\n', (7288, 7334), False, 'import torch\n'), ((7369, 7428), 'transformers.LlamaTokenizer.from_pretrained', 'LlamaTokenizer.from_pretrained', (['tokenizer_dir'], {'legacy': '(False)'}), '(tokenizer_dir, legacy=False)\n', (7399, 7428), False, 'from transformers import LlamaTokenizer\n'), ((7469, 7562), 'tensorrt_llm.runtime.SamplingConfig', 'SamplingConfig', ([], {'end_id': 'EOS_TOKEN', 'pad_id': 'PAD_TOKEN', 'num_beams': '(1)', 'temperature': 'temperature'}), '(end_id=EOS_TOKEN, pad_id=PAD_TOKEN, num_beams=1, temperature\n =temperature)\n', (7483, 7562), False, 'from tensorrt_llm.runtime import ModelConfig, SamplingConfig\n'), ((7912, 8024), 'tensorrt_llm.runtime.GenerationSession', 'tensorrt_llm.runtime.GenerationSession', (['self._model_config', 'engine_buffer', 'runtime_mapping'], {'debug_mode': '(False)'}), '(self._model_config, engine_buffer,\n runtime_mapping, debug_mode=False)\n', (7950, 8024), False, 'import tensorrt_llm\n'), ((10268, 10292), 'torch.max', 'torch.max', (['input_lengths'], {}), '(input_lengths)\n', (10277, 10292), False, 'import torch\n'), ((4775, 4787), 'json.load', 'json.load', (['f'], {}), '(f)\n', (4784, 4787), False, 'import json\n'), ((5192, 5221), 'tensorrt_llm.mpi_world_size', 'tensorrt_llm.mpi_world_size', ([], {}), '()\n', (5219, 5221), False, 'import tensorrt_llm\n'), ((5889, 5992), 'tensorrt_llm.logger.warning', 'tensorrt_llm.logger.warning', (['"""`multi_query_mode` config is deprecated. Please rebuild the engine."""'], {}), "(\n '`multi_query_mode` config is deprecated. Please rebuild the engine.')\n", (5916, 5992), False, 'import tensorrt_llm\n'), ((12041, 12098), 'torch.tensor', 'torch.tensor', (['input_ids'], {'dtype': 'torch.int32', 'device': '"""cuda"""'}), "(input_ids, dtype=torch.int32, device='cuda')\n", (12053, 12098), False, 'import torch\n'), ((13436, 13448), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (13446, 13448), False, 'import uuid\n'), ((5304, 5333), 'tensorrt_llm.mpi_world_size', 'tensorrt_llm.mpi_world_size', ([], {}), '()\n', (5331, 5333), False, 'import tensorrt_llm\n'), ((12234, 12293), 'torch.nested.nested_tensor', 'torch.nested.nested_tensor', (['input_tokens'], {'dtype': 'torch.int32'}), '(input_tokens, dtype=torch.int32)\n', (12260, 12293), False, 'import torch\n')]
from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.core.llms import ChatMessage, ChatResponse from llama_index.core.schema import NodeWithScore, TextNode import chainlit as cl @cl.on_chat_start async def start(): await cl.Message(content="LlamaIndexCb").send() cb = cl.LlamaIndexCallbackHandler() cb.on_event_start(CBEventType.RETRIEVE, payload={}) await cl.sleep(0.2) cb.on_event_end( CBEventType.RETRIEVE, payload={ EventPayload.NODES: [ NodeWithScore(node=TextNode(text="This is text1"), score=1) ] }, ) cb.on_event_start(CBEventType.LLM) await cl.sleep(0.2) response = ChatResponse(message=ChatMessage(content="This is the LLM response")) cb.on_event_end( CBEventType.LLM, payload={ EventPayload.RESPONSE: response, EventPayload.PROMPT: "This is the LLM prompt", }, )
[ "llama_index.core.schema.TextNode", "llama_index.core.llms.ChatMessage" ]
[((316, 346), 'chainlit.LlamaIndexCallbackHandler', 'cl.LlamaIndexCallbackHandler', ([], {}), '()\n', (344, 346), True, 'import chainlit as cl\n'), ((415, 428), 'chainlit.sleep', 'cl.sleep', (['(0.2)'], {}), '(0.2)\n', (423, 428), True, 'import chainlit as cl\n'), ((691, 704), 'chainlit.sleep', 'cl.sleep', (['(0.2)'], {}), '(0.2)\n', (699, 704), True, 'import chainlit as cl\n'), ((742, 789), 'llama_index.core.llms.ChatMessage', 'ChatMessage', ([], {'content': '"""This is the LLM response"""'}), "(content='This is the LLM response')\n", (753, 789), False, 'from llama_index.core.llms import ChatMessage, ChatResponse\n'), ((264, 298), 'chainlit.Message', 'cl.Message', ([], {'content': '"""LlamaIndexCb"""'}), "(content='LlamaIndexCb')\n", (274, 298), True, 'import chainlit as cl\n'), ((568, 598), 'llama_index.core.schema.TextNode', 'TextNode', ([], {'text': '"""This is text1"""'}), "(text='This is text1')\n", (576, 598), False, 'from llama_index.core.schema import NodeWithScore, TextNode\n')]
import requests from bs4 import BeautifulSoup from llama_index import GPTSimpleVectorIndex from llama_index.readers.database import DatabaseReader from env import settings from logger import logger from .base import BaseToolSet, SessionGetter, ToolScope, tool class RequestsGet(BaseToolSet): @tool( name="Requests Get", description="A portal to the internet. " "Use this when you need to get specific content from a website." "Input should be a url (i.e. https://www.google.com)." "The output will be the text response of the GET request.", ) def get(self, url: str) -> str: """Run the tool.""" html = requests.get(url).text soup = BeautifulSoup(html) non_readable_tags = soup.find_all( ["script", "style", "header", "footer", "form"] ) for non_readable_tag in non_readable_tags: non_readable_tag.extract() content = soup.get_text("\n", strip=True) if len(content) > 300: content = content[:300] + "..." logger.debug( f"\nProcessed RequestsGet, Input Url: {url} " f"Output Contents: {content}" ) return content class WineDB(BaseToolSet): def __init__(self): db = DatabaseReader( scheme="postgresql", # Database Scheme host=settings["WINEDB_HOST"], # Database Host port="5432", # Database Port user="alphadom", # Database User password=settings["WINEDB_PASSWORD"], # Database Password dbname="postgres", # Database Name ) self.columns = ["nameEn", "nameKo", "description"] concat_columns = str(",'-',".join([f'"{i}"' for i in self.columns])) query = f""" SELECT Concat({concat_columns}) FROM wine """ documents = db.load_data(query=query) self.index = GPTSimpleVectorIndex(documents) @tool( name="Wine Recommendation", description="A tool to recommend wines based on a user's input. " "Inputs are necessary factors for wine recommendations, such as the user's mood today, side dishes to eat with wine, people to drink wine with, what things you want to do, the scent and taste of their favorite wine." "The output will be a list of recommended wines." "The tool is based on a database of wine reviews, which is stored in a database.", ) def recommend(self, query: str) -> str: """Run the tool.""" results = self.index.query(query) wine = "\n".join( [ f"{i}:{j}" for i, j in zip( self.columns, results.source_nodes[0].source_text.split("-") ) ] ) output = results.response + "\n\n" + wine logger.debug( f"\nProcessed WineDB, Input Query: {query} " f"Output Wine: {wine}" ) return output class ExitConversation(BaseToolSet): @tool( name="Exit Conversation", description="A tool to exit the conversation. " "Use this when you want to exit the conversation. " "The input should be a message that the conversation is over.", scope=ToolScope.SESSION, ) def exit(self, message: str, get_session: SessionGetter) -> str: """Run the tool.""" _, executor = get_session() del executor logger.debug(f"\nProcessed ExitConversation.") return message
[ "llama_index.GPTSimpleVectorIndex", "llama_index.readers.database.DatabaseReader" ]
[((713, 732), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html'], {}), '(html)\n', (726, 732), False, 'from bs4 import BeautifulSoup\n'), ((1073, 1166), 'logger.logger.debug', 'logger.debug', (['f"""\nProcessed RequestsGet, Input Url: {url} Output Contents: {content}"""'], {}), '(\n f"""\nProcessed RequestsGet, Input Url: {url} Output Contents: {content}""")\n', (1085, 1166), False, 'from logger import logger\n'), ((1275, 1437), 'llama_index.readers.database.DatabaseReader', 'DatabaseReader', ([], {'scheme': '"""postgresql"""', 'host': "settings['WINEDB_HOST']", 'port': '"""5432"""', 'user': '"""alphadom"""', 'password': "settings['WINEDB_PASSWORD']", 'dbname': '"""postgres"""'}), "(scheme='postgresql', host=settings['WINEDB_HOST'], port=\n '5432', user='alphadom', password=settings['WINEDB_PASSWORD'], dbname=\n 'postgres')\n", (1289, 1437), False, 'from llama_index.readers.database import DatabaseReader\n'), ((1937, 1968), 'llama_index.GPTSimpleVectorIndex', 'GPTSimpleVectorIndex', (['documents'], {}), '(documents)\n', (1957, 1968), False, 'from llama_index import GPTSimpleVectorIndex\n'), ((2867, 2952), 'logger.logger.debug', 'logger.debug', (['f"""\nProcessed WineDB, Input Query: {query} Output Wine: {wine}"""'], {}), '(f"""\nProcessed WineDB, Input Query: {query} Output Wine: {wine}"""\n )\n', (2879, 2952), False, 'from logger import logger\n'), ((3468, 3517), 'logger.logger.debug', 'logger.debug', (['f"""\nProcessed ExitConversation."""'], {}), '(f"""\nProcessed ExitConversation.""")\n', (3480, 3517), False, 'from logger import logger\n'), ((675, 692), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (687, 692), False, 'import requests\n')]
try: from llama_index import Document from llama_index.text_splitter import SentenceSplitter except ImportError: from llama_index.core import Document from llama_index.core.text_splitter import SentenceSplitter def llama_index_sentence_splitter( documents: list[str], document_ids: list[str], chunk_size=256 ): chunk_overlap = min(chunk_size / 4, min(chunk_size / 2, 64)) chunks = [] node_parser = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) docs = [[Document(text=doc)] for doc in documents] for doc_id, doc in zip(document_ids, docs): chunks += [ {"document_id": doc_id, "content": node.text} for node in node_parser(doc) ] return chunks
[ "llama_index.core.text_splitter.SentenceSplitter", "llama_index.core.Document" ]
[((432, 500), 'llama_index.core.text_splitter.SentenceSplitter', 'SentenceSplitter', ([], {'chunk_size': 'chunk_size', 'chunk_overlap': 'chunk_overlap'}), '(chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n', (448, 500), False, 'from llama_index.core.text_splitter import SentenceSplitter\n'), ((514, 532), 'llama_index.core.Document', 'Document', ([], {'text': 'doc'}), '(text=doc)\n', (522, 532), False, 'from llama_index.core import Document\n')]
""" Creates RAG dataset for tutorial notebooks and persists to disk. """ import argparse import logging import sys from typing import List, Optional import llama_index import numpy as np import pandas as pd from gcsfs import GCSFileSystem from llama_index import ServiceContext, StorageContext, load_index_from_storage from llama_index.callbacks import CallbackManager, OpenInferenceCallbackHandler from llama_index.callbacks.open_inference_callback import as_dataframe from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.llms import OpenAI from phoenix.experimental.evals.retrievals import ( classify_relevance, compute_precisions_at_k, ) from tqdm import tqdm def create_user_feedback( first_document_relevances: List[Optional[bool]], second_document_relevances: List[Optional[bool]], ) -> List[Optional[bool]]: """_summary_ Args: first_document_relevances (List[Optional[bool]]): _description_ second_document_relevances (List[Optional[bool]]): _description_ Returns: List[Optional[bool]]: _description_ """ if len(first_document_relevances) != len(second_document_relevances): raise ValueError() first_document_relevances_array = np.array(first_document_relevances) second_document_relevances_array = np.array(second_document_relevances) failed_retrieval_mask = ~first_document_relevances_array & ~second_document_relevances_array num_failed_retrievals = failed_retrieval_mask.sum() num_thumbs_down = int(0.75 * num_failed_retrievals) failed_retrieval_indexes = np.where(failed_retrieval_mask)[0] thumbs_down_mask = np.random.choice( failed_retrieval_indexes, size=num_thumbs_down, replace=False ) successful_retrieval_mask = ~failed_retrieval_mask num_successful_retrievals = successful_retrieval_mask.sum() num_thumbs_up = int(0.25 * num_successful_retrievals) successful_retrieval_indexes = np.where(successful_retrieval_mask)[0] thumbs_up_mask = np.random.choice( successful_retrieval_indexes, size=num_thumbs_up, replace=False ) user_feedback_array = np.full(len(first_document_relevances), np.nan, dtype=np.float32) user_feedback_array[thumbs_down_mask] = -1.0 user_feedback_array[thumbs_up_mask] = 1.0 return [None if np.isnan(value) else value for value in user_feedback_array.tolist()] if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) parser = argparse.ArgumentParser() parser.add_argument("--index-path", type=str, required=True, help="Path to persisted index.") parser.add_argument( "--use-gcs", action="store_true", help="If this flag is set, the index will be loaded from GCS.", ) parser.add_argument( "--query-path", type=str, required=True, help="Path to CSV file containing queries." ) parser.add_argument( "--output-path", type=str, required=True, help="Path to output Parquet file." ) args = parser.parse_args() llama_index.prompts.default_prompts.DEFAULT_TEXT_QA_PROMPT_TMPL = ( "Context information is below.\n" "---------------------\n" "{context_str}\n" "---------------------\n" "Given the context information, " "answer the question and be as helpful as possible: {query_str}\n" ) # This prompt has been tweaked to make the system less conservative for demo purposes. queries = pd.read_csv(args.query_path)["Question"].tolist() file_system = GCSFileSystem(project="public-assets-275721") if args.use_gcs else None storage_context = StorageContext.from_defaults( fs=file_system, persist_dir=args.index_path, ) callback_handler = OpenInferenceCallbackHandler() service_context = ServiceContext.from_defaults( llm=OpenAI(model="text-davinci-003"), embed_model=OpenAIEmbedding(model="text-embedding-ada-002"), callback_manager=CallbackManager(handlers=[callback_handler]), ) index = load_index_from_storage( storage_context, service_context=service_context, ) query_engine = index.as_query_engine() logging.info("Running queries") for query in tqdm(queries): query_engine.query(query) query_dataframe = as_dataframe(callback_handler.flush_query_data_buffer()) document_dataframe = as_dataframe(callback_handler.flush_node_data_buffer()) query_texts = query_dataframe[":feature.text:prompt"].tolist() list_of_document_id_lists = query_dataframe[ ":feature.[str].retrieved_document_ids:prompt" ].tolist() document_id_to_text = dict( zip(document_dataframe["id"].to_list(), document_dataframe["node_text"].to_list()) ) first_document_texts, second_document_texts = [ [ document_id_to_text[document_ids[document_index]] for document_ids in list_of_document_id_lists ] for document_index in [0, 1] ] logging.info("Computing LLM-assisted ranking metrics") first_document_relevances, second_document_relevances = [ [ classify_relevance(query_text, document_text, model_name="gpt-4") for query_text, document_text in tqdm(zip(query_texts, first_document_texts)) ] for document_texts in [first_document_texts, second_document_texts] ] list_of_precisions_at_k_lists = [ compute_precisions_at_k([rel0, rel1]) for rel0, rel1 in zip(first_document_relevances, second_document_relevances) ] precisions_at_1, precisions_at_2 = [ [precisions_at_k[index] for precisions_at_k in list_of_precisions_at_k_lists] for index in [0, 1] ] document_similarity_0, document_similarity_1 = [ [ scores[index] for scores in query_dataframe[ ":feature.[float].retrieved_document_scores:prompt" ].tolist() ] for index in [0, 1] ] user_feedback = create_user_feedback(first_document_relevances, second_document_relevances) logging.info( f"Thumbs up: {sum([value == 1.0 for value in user_feedback]) / len(user_feedback)}" ) logging.info( f"Thumbs down: {sum([value == -1.0 for value in user_feedback]) / len(user_feedback)}" ) query_dataframe = query_dataframe.assign( **{ ":tag.bool:relevance_0": first_document_relevances, ":tag.bool:relevance_1": second_document_relevances, ":tag.float:precision_at_1": precisions_at_1, ":tag.float:precision_at_2": precisions_at_2, ":tag.float:document_similarity_0": document_similarity_0, ":tag.float:document_similarity_1": document_similarity_1, ":tag.float:user_feedback": user_feedback, } ) query_dataframe.to_parquet(args.output_path)
[ "llama_index.llms.OpenAI", "llama_index.StorageContext.from_defaults", "llama_index.callbacks.OpenInferenceCallbackHandler", "llama_index.load_index_from_storage", "llama_index.callbacks.CallbackManager", "llama_index.embeddings.openai.OpenAIEmbedding" ]
[((1235, 1270), 'numpy.array', 'np.array', (['first_document_relevances'], {}), '(first_document_relevances)\n', (1243, 1270), True, 'import numpy as np\n'), ((1310, 1346), 'numpy.array', 'np.array', (['second_document_relevances'], {}), '(second_document_relevances)\n', (1318, 1346), True, 'import numpy as np\n'), ((1645, 1724), 'numpy.random.choice', 'np.random.choice', (['failed_retrieval_indexes'], {'size': 'num_thumbs_down', 'replace': '(False)'}), '(failed_retrieval_indexes, size=num_thumbs_down, replace=False)\n', (1661, 1724), True, 'import numpy as np\n'), ((2011, 2097), 'numpy.random.choice', 'np.random.choice', (['successful_retrieval_indexes'], {'size': 'num_thumbs_up', 'replace': '(False)'}), '(successful_retrieval_indexes, size=num_thumbs_up, replace=\n False)\n', (2027, 2097), True, 'import numpy as np\n'), ((2417, 2476), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'stream': 'sys.stdout'}), '(level=logging.DEBUG, stream=sys.stdout)\n', (2436, 2476), False, 'import logging\n'), ((2491, 2516), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2514, 2516), False, 'import argparse\n'), ((3637, 3710), 'llama_index.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'fs': 'file_system', 'persist_dir': 'args.index_path'}), '(fs=file_system, persist_dir=args.index_path)\n', (3665, 3710), False, 'from llama_index import ServiceContext, StorageContext, load_index_from_storage\n'), ((3757, 3787), 'llama_index.callbacks.OpenInferenceCallbackHandler', 'OpenInferenceCallbackHandler', ([], {}), '()\n', (3785, 3787), False, 'from llama_index.callbacks import CallbackManager, OpenInferenceCallbackHandler\n'), ((4044, 4117), 'llama_index.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {'service_context': 'service_context'}), '(storage_context, service_context=service_context)\n', (4067, 4117), False, 'from llama_index import ServiceContext, StorageContext, load_index_from_storage\n'), ((4189, 4220), 'logging.info', 'logging.info', (['"""Running queries"""'], {}), "('Running queries')\n", (4201, 4220), False, 'import logging\n'), ((4238, 4251), 'tqdm.tqdm', 'tqdm', (['queries'], {}), '(queries)\n', (4242, 4251), False, 'from tqdm import tqdm\n'), ((5004, 5058), 'logging.info', 'logging.info', (['"""Computing LLM-assisted ranking metrics"""'], {}), "('Computing LLM-assisted ranking metrics')\n", (5016, 5058), False, 'import logging\n'), ((1587, 1618), 'numpy.where', 'np.where', (['failed_retrieval_mask'], {}), '(failed_retrieval_mask)\n', (1595, 1618), True, 'import numpy as np\n'), ((1951, 1986), 'numpy.where', 'np.where', (['successful_retrieval_mask'], {}), '(successful_retrieval_mask)\n', (1959, 1986), True, 'import numpy as np\n'), ((3543, 3588), 'gcsfs.GCSFileSystem', 'GCSFileSystem', ([], {'project': '"""public-assets-275721"""'}), "(project='public-assets-275721')\n", (3556, 3588), False, 'from gcsfs import GCSFileSystem\n'), ((5437, 5474), 'phoenix.experimental.evals.retrievals.compute_precisions_at_k', 'compute_precisions_at_k', (['[rel0, rel1]'], {}), '([rel0, rel1])\n', (5460, 5474), False, 'from phoenix.experimental.evals.retrievals import classify_relevance, compute_precisions_at_k\n'), ((2314, 2329), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (2322, 2329), True, 'import numpy as np\n'), ((3852, 3884), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'model': '"""text-davinci-003"""'}), "(model='text-davinci-003')\n", (3858, 3884), False, 'from llama_index.llms import OpenAI\n'), ((3906, 3953), 'llama_index.embeddings.openai.OpenAIEmbedding', 'OpenAIEmbedding', ([], {'model': '"""text-embedding-ada-002"""'}), "(model='text-embedding-ada-002')\n", (3921, 3953), False, 'from llama_index.embeddings.openai import OpenAIEmbedding\n'), ((3980, 4024), 'llama_index.callbacks.CallbackManager', 'CallbackManager', ([], {'handlers': '[callback_handler]'}), '(handlers=[callback_handler])\n', (3995, 4024), False, 'from llama_index.callbacks import CallbackManager, OpenInferenceCallbackHandler\n'), ((5143, 5208), 'phoenix.experimental.evals.retrievals.classify_relevance', 'classify_relevance', (['query_text', 'document_text'], {'model_name': '"""gpt-4"""'}), "(query_text, document_text, model_name='gpt-4')\n", (5161, 5208), False, 'from phoenix.experimental.evals.retrievals import classify_relevance, compute_precisions_at_k\n'), ((3475, 3503), 'pandas.read_csv', 'pd.read_csv', (['args.query_path'], {}), '(args.query_path)\n', (3486, 3503), True, 'import pandas as pd\n')]
import logging import os import time import typing import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional import numpy as np from llama_index.core.schema import BaseNode, MetadataMode, TextNode from llama_index.core.vector_stores.types import ( VectorStore, VectorStoreQuery, VectorStoreQueryResult, ) from llama_index.core.vector_stores.utils import ( legacy_metadata_dict_to_node, metadata_dict_to_node, node_to_metadata_dict, ) if TYPE_CHECKING: import vearch logger = logging.getLogger(__name__) class VearchVectorStore(VectorStore): """ Vearch vector store: embeddings are stored within a Vearch table. when query, the index uses Vearch to query for the top k most similar nodes. Args: chroma_collection (chromadb.api.models.Collection.Collection): ChromaDB collection instance """ flat_metadata: bool = True stores_text: bool = True _DEFAULT_TABLE_NAME = "liama_index_vearch" _DEFAULT_CLUSTER_DB_NAME = "liama_index_vearch_client_db" _DEFAULT_VERSION = 1 def __init__( self, path_or_url: Optional[str] = None, table_name: str = _DEFAULT_TABLE_NAME, db_name: str = _DEFAULT_CLUSTER_DB_NAME, flag: int = _DEFAULT_VERSION, **kwargs: Any, ) -> None: """ Initialize vearch vector store flag 1 for cluster,0 for standalone. """ try: if flag: import vearch_cluster else: import vearch except ImportError: raise ValueError( "Could not import suitable python package." "Please install it with `pip install vearch or vearch_cluster." ) if flag: if path_or_url is None: raise ValueError("Please input url of cluster") if not db_name: db_name = self._DEFAULT_CLUSTER_DB_NAME db_name += "_" db_name += str(uuid.uuid4()).split("-")[-1] self.using_db_name = db_name self.url = path_or_url self.vearch = vearch_cluster.VearchCluster(path_or_url) else: if path_or_url is None: metadata_path = os.getcwd().replace("\\", "/") else: metadata_path = path_or_url if not os.path.isdir(metadata_path): os.makedirs(metadata_path) log_path = os.path.join(metadata_path, "log") if not os.path.isdir(log_path): os.makedirs(log_path) self.vearch = vearch.Engine(metadata_path, log_path) self.using_metapath = metadata_path if not table_name: table_name = self._DEFAULT_TABLE_NAME table_name += "_" table_name += str(uuid.uuid4()).split("-")[-1] self.using_table_name = table_name self.flag = flag @property def client(self) -> Any: """Get client.""" return self.vearch def _get_matadata_field(self, metadatas: Optional[List[dict]] = None) -> None: field_list = [] if metadatas: for key, value in metadatas[0].items(): if isinstance(value, int): field_list.append({"field": key, "type": "int"}) continue if isinstance(value, str): field_list.append({"field": key, "type": "str"}) continue if isinstance(value, float): field_list.append({"field": key, "type": "float"}) continue else: raise ValueError("Please check data type,support int, str, float") self.field_list = field_list def _add_texts( self, ids: Iterable[str], texts: Iterable[str], metadatas: Optional[List[dict]] = None, embeddings: Optional[List[List[float]]] = None, **kwargs: Any, ) -> List[str]: """ Returns: List of ids from adding the texts into the vectorstore. """ if embeddings is None: raise ValueError("embeddings is None") self._get_matadata_field(metadatas) if self.flag: dbs_list = self.vearch.list_dbs() if self.using_db_name not in dbs_list: create_db_code = self.vearch.create_db(self.using_db_name) if not create_db_code: raise ValueError("create db failed!!!") space_list = self.vearch.list_spaces(self.using_db_name) if self.using_table_name not in space_list: create_space_code = self._create_space(len(embeddings[0])) if not create_space_code: raise ValueError("create space failed!!!") docid = [] if embeddings is not None and metadatas is not None: meta_field_list = [i["field"] for i in self.field_list] for text, metadata, embed, id_d in zip( texts, metadatas, embeddings, ids ): profiles: typing.Dict[str, Any] = {} profiles["text"] = text for f in meta_field_list: profiles[f] = metadata[f] embed_np = np.array(embed) profiles["text_embedding"] = { "feature": (embed_np / np.linalg.norm(embed_np)).tolist() } insert_res = self.vearch.insert_one( self.using_db_name, self.using_table_name, profiles, id_d ) if insert_res["status"] == 200: docid.append(insert_res["_id"]) continue else: retry_insert = self.vearch.insert_one( self.using_db_name, self.using_table_name, profiles ) docid.append(retry_insert["_id"]) continue else: table_path = os.path.join( self.using_metapath, self.using_table_name + ".schema" ) if not os.path.exists(table_path): dim = len(embeddings[0]) response_code = self._create_table(dim) if response_code: raise ValueError("create table failed!!!") if embeddings is not None and metadatas is not None: doc_items = [] meta_field_list = [i["field"] for i in self.field_list] for text, metadata, embed, id_d in zip( texts, metadatas, embeddings, ids ): profiles_v: typing.Dict[str, Any] = {} profiles_v["text"] = text profiles_v["_id"] = id_d for f in meta_field_list: profiles_v[f] = metadata[f] embed_np = np.array(embed) profiles_v["text_embedding"] = embed_np / np.linalg.norm(embed_np) doc_items.append(profiles_v) docid = self.vearch.add(doc_items) t_time = 0 while len(docid) != len(embeddings): time.sleep(0.5) if t_time > 6: break t_time += 1 self.vearch.dump() return docid def _create_table( self, dim: int = 1024, ) -> int: """ Create Standalone VectorStore Table. Args: dim:dimension of vector. fields_list: the field you want to store. Return: code,0 for success,1 for failed. """ type_dict = { "int": vearch.dataType.INT, "str": vearch.dataType.STRING, "float": vearch.dataType.FLOAT, } engine_info = { "index_size": 1, "retrieval_type": "HNSW", "retrieval_param": { "metric_type": "InnerProduct", "nlinks": -1, "efConstruction": -1, }, } filed_list_add = self.field_list.append({"field": "text", "type": "str"}) fields = [ vearch.GammaFieldInfo(fi["field"], type_dict[fi["type"]]) for fi in filed_list_add ] vector_field = vearch.GammaVectorInfo( name="text_embedding", type=vearch.dataType.VECTOR, is_index=True, dimension=dim, model_id="", store_type="MemoryOnly", store_param={"cache_size": 10000}, ) return self.vearch.create_table( engine_info, name=self.using_table_name, fields=fields, vector_field=vector_field, ) def _create_space( self, dim: int = 1024, ) -> int: """ Create Cluster VectorStore space. Args: dim:dimension of vector. Return: code,0 failed for ,1 for success. """ type_dict = {"int": "integer", "str": "string", "float": "float"} space_config = { "name": self.using_table_name, "partition_num": 1, "replica_num": 1, "engine": { "index_size": 1, "retrieval_type": "HNSW", "retrieval_param": { "metric_type": "InnerProduct", "nlinks": -1, "efConstruction": -1, }, }, } tmp_proer = { "text": {"type": "string"}, "text_embedding": { "type": "vector", "index": True, "dimension": dim, "store_type": "MemoryOnly", }, } for item in self.field_list: tmp_proer[item["field"]] = {"type": type_dict[item["type"]]} space_config["properties"] = tmp_proer return self.vearch.create_space(self.using_db_name, space_config) def add( self, nodes: List[BaseNode], **add_kwargs: Any, ) -> List[str]: if not self.vearch: raise ValueError("Vearch Engine is not initialized") embeddings = [] metadatas = [] ids = [] texts = [] for node in nodes: embeddings.append(node.get_embedding()) metadatas.append( node_to_metadata_dict( node, remove_text=True, flat_metadata=self.flat_metadata ) ) ids.append(node.node_id) texts.append(node.get_content(metadata_mode=MetadataMode.NONE) or "") return self._add_texts( ids=ids, texts=texts, metadatas=metadatas, embeddings=embeddings, ) def query( self, query: VectorStoreQuery, **kwargs: Any, ) -> VectorStoreQueryResult: """ Query index for top k most similar nodes. Args: query : vector store query. Returns: VectorStoreQueryResult: Query results. """ meta_filters = {} if query.filters is not None: for filter_ in query.filters.legacy_filters(): meta_filters[filter_.key] = filter_.value if self.flag: meta_field_list = self.vearch.get_space( self.using_db_name, self.using_table_name ) meta_field_list.remove("text_embedding") embed = query.query_embedding if embed is None: raise ValueError("query.query_embedding is None") k = query.similarity_top_k if self.flag: query_data = { "query": { "sum": [ { "field": "text_embedding", "feature": (embed / np.linalg.norm(embed)).tolist(), } ], }, "retrieval_param": {"metric_type": "InnerProduct", "efSearch": 64}, "size": k, "fields": meta_field_list, } query_result = self.vearch.search( self.using_db_name, self.using_table_name, query_data ) res = query_result["hits"]["hits"] else: query_data = { "vector": [ { "field": "text_embedding", "feature": embed / np.linalg.norm(embed), } ], "fields": [], "retrieval_param": {"metric_type": "InnerProduct", "efSearch": 64}, "topn": k, } query_result = self.vearch.search(query_data) res = query_result[0]["result_items"] nodes = [] similarities = [] ids = [] for item in res: content = "" meta_data = {} node_id = "" if self.flag: score = item["_score"] item = item["_source"] for item_key in item: if item_key == "text": content = item[item_key] continue elif item_key == "_id": node_id = item[item_key] ids.append(node_id) continue if self.flag != 1 and item_key == "score": score = item[item_key] continue meta_data[item_key] = item[item_key] similarities.append(score) try: node = metadata_dict_to_node(meta_data) node.set_content(content) except Exception: metadata, node_info, relationships = legacy_metadata_dict_to_node( meta_data ) node = TextNode( text=content, id_=node_id, metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) nodes.append(node) return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids) def _delete( self, ids: Optional[List[str]] = None, **kwargs: Any, ) -> Optional[bool]: """ Delete the documents which have the specified ids. Args: ids: The ids of the embedding vectors. **kwargs: Other keyword arguments that subclasses might use. Returns: Optional[bool]: True if deletion is successful. False otherwise, None if not implemented. """ ret: Optional[bool] = None tmp_res = [] if ids is None or len(ids) == 0: return ret for _id in ids: if self.flag: ret = self.vearch.delete(self.using_db_name, self.using_table_name, _id) else: ret = self.vearch.del_doc(_id) tmp_res.append(ret) return all(i == 0 for i in tmp_res) def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: """Delete nodes using with ref_doc_id. Args: ref_doc_id (str): The doc_id of the document to delete. Returns: None """ if len(ref_doc_id) == 0: return ids: List[str] = [] ids.append(ref_doc_id) self._delete(ids)
[ "llama_index.core.vector_stores.utils.metadata_dict_to_node", "llama_index.core.vector_stores.types.VectorStoreQueryResult", "llama_index.core.vector_stores.utils.legacy_metadata_dict_to_node", "llama_index.core.vector_stores.utils.node_to_metadata_dict" ]
[((524, 551), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (541, 551), False, 'import logging\n'), ((8582, 8767), 'vearch.GammaVectorInfo', 'vearch.GammaVectorInfo', ([], {'name': '"""text_embedding"""', 'type': 'vearch.dataType.VECTOR', 'is_index': '(True)', 'dimension': 'dim', 'model_id': '""""""', 'store_type': '"""MemoryOnly"""', 'store_param': "{'cache_size': 10000}"}), "(name='text_embedding', type=vearch.dataType.VECTOR,\n is_index=True, dimension=dim, model_id='', store_type='MemoryOnly',\n store_param={'cache_size': 10000})\n", (8604, 8767), False, 'import vearch\n'), ((14615, 14686), 'llama_index.core.vector_stores.types.VectorStoreQueryResult', 'VectorStoreQueryResult', ([], {'nodes': 'nodes', 'similarities': 'similarities', 'ids': 'ids'}), '(nodes=nodes, similarities=similarities, ids=ids)\n', (14637, 14686), False, 'from llama_index.core.vector_stores.types import VectorStore, VectorStoreQuery, VectorStoreQueryResult\n'), ((2180, 2221), 'vearch_cluster.VearchCluster', 'vearch_cluster.VearchCluster', (['path_or_url'], {}), '(path_or_url)\n', (2208, 2221), False, 'import vearch_cluster\n'), ((2512, 2546), 'os.path.join', 'os.path.join', (['metadata_path', '"""log"""'], {}), "(metadata_path, 'log')\n", (2524, 2546), False, 'import os\n'), ((2655, 2693), 'vearch.Engine', 'vearch.Engine', (['metadata_path', 'log_path'], {}), '(metadata_path, log_path)\n', (2668, 2693), False, 'import vearch\n'), ((6216, 6284), 'os.path.join', 'os.path.join', (['self.using_metapath', "(self.using_table_name + '.schema')"], {}), "(self.using_metapath, self.using_table_name + '.schema')\n", (6228, 6284), False, 'import os\n'), ((8454, 8511), 'vearch.GammaFieldInfo', 'vearch.GammaFieldInfo', (["fi['field']", "type_dict[fi['type']]"], {}), "(fi['field'], type_dict[fi['type']])\n", (8475, 8511), False, 'import vearch\n'), ((2416, 2444), 'os.path.isdir', 'os.path.isdir', (['metadata_path'], {}), '(metadata_path)\n', (2429, 2444), False, 'import os\n'), ((2462, 2488), 'os.makedirs', 'os.makedirs', (['metadata_path'], {}), '(metadata_path)\n', (2473, 2488), False, 'import os\n'), ((2566, 2589), 'os.path.isdir', 'os.path.isdir', (['log_path'], {}), '(log_path)\n', (2579, 2589), False, 'import os\n'), ((2607, 2628), 'os.makedirs', 'os.makedirs', (['log_path'], {}), '(log_path)\n', (2618, 2628), False, 'import os\n'), ((6334, 6360), 'os.path.exists', 'os.path.exists', (['table_path'], {}), '(table_path)\n', (6348, 6360), False, 'import os\n'), ((10709, 10788), 'llama_index.core.vector_stores.utils.node_to_metadata_dict', 'node_to_metadata_dict', (['node'], {'remove_text': '(True)', 'flat_metadata': 'self.flat_metadata'}), '(node, remove_text=True, flat_metadata=self.flat_metadata)\n', (10730, 10788), False, 'from llama_index.core.vector_stores.utils import legacy_metadata_dict_to_node, metadata_dict_to_node, node_to_metadata_dict\n'), ((14001, 14033), 'llama_index.core.vector_stores.utils.metadata_dict_to_node', 'metadata_dict_to_node', (['meta_data'], {}), '(meta_data)\n', (14022, 14033), False, 'from llama_index.core.vector_stores.utils import legacy_metadata_dict_to_node, metadata_dict_to_node, node_to_metadata_dict\n'), ((5418, 5433), 'numpy.array', 'np.array', (['embed'], {}), '(embed)\n', (5426, 5433), True, 'import numpy as np\n'), ((7132, 7147), 'numpy.array', 'np.array', (['embed'], {}), '(embed)\n', (7140, 7147), True, 'import numpy as np\n'), ((7435, 7450), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (7445, 7450), False, 'import time\n'), ((14159, 14198), 'llama_index.core.vector_stores.utils.legacy_metadata_dict_to_node', 'legacy_metadata_dict_to_node', (['meta_data'], {}), '(meta_data)\n', (14187, 14198), False, 'from llama_index.core.vector_stores.utils import legacy_metadata_dict_to_node, metadata_dict_to_node, node_to_metadata_dict\n'), ((2304, 2315), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2313, 2315), False, 'import os\n'), ((7210, 7234), 'numpy.linalg.norm', 'np.linalg.norm', (['embed_np'], {}), '(embed_np)\n', (7224, 7234), True, 'import numpy as np\n'), ((2879, 2891), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2889, 2891), False, 'import uuid\n'), ((12842, 12863), 'numpy.linalg.norm', 'np.linalg.norm', (['embed'], {}), '(embed)\n', (12856, 12863), True, 'import numpy as np\n'), ((2049, 2061), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2059, 2061), False, 'import uuid\n'), ((5532, 5556), 'numpy.linalg.norm', 'np.linalg.norm', (['embed_np'], {}), '(embed_np)\n', (5546, 5556), True, 'import numpy as np\n'), ((12210, 12231), 'numpy.linalg.norm', 'np.linalg.norm', (['embed'], {}), '(embed)\n', (12224, 12231), True, 'import numpy as np\n')]
# ENTER YOUR OPENAPI KEY IN OPENAI_API_KEY ENV VAR FIRST from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, download_loader savePath = f'/{os.path.dirname(__file__)}/indexes/index.json' # # index = GPTSimpleVectorIndex(documents)#, llm_predictor=llm_predictor) index = GPTSimpleVectorIndex.load_from_disk(savePath) response = index.query("Summarize the vulnerability CVE-2021-23406", response_mode="tree_summarize") print(response) print('Sources are ', response.get_formatted_sources())
[ "llama_index.GPTSimpleVectorIndex.load_from_disk" ]
[((303, 348), 'llama_index.GPTSimpleVectorIndex.load_from_disk', 'GPTSimpleVectorIndex.load_from_disk', (['savePath'], {}), '(savePath)\n', (338, 348), False, 'from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, download_loader\n')]
from typing import Optional, Union from llama_index import ServiceContext from llama_index.callbacks import CallbackManager from llama_index.embeddings.utils import EmbedType from llama_index.extractors import ( EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor, ) from llama_index.llms.utils import LLMType from llama_index.prompts import PromptTemplate from llama_index.prompts.base import BasePromptTemplate from llama_index.text_splitter import SentenceSplitter from autollm.callbacks.cost_calculating import CostCalculatingHandler from autollm.utils.llm_utils import set_default_prompt_template class AutoServiceContext: """AutoServiceContext extends the functionality of LlamaIndex's ServiceContext to include token counting. """ @staticmethod def from_defaults( llm: Optional[LLMType] = "default", embed_model: Optional[EmbedType] = "default", system_prompt: str = None, query_wrapper_prompt: Union[str, BasePromptTemplate] = None, enable_cost_calculator: bool = False, chunk_size: Optional[int] = 512, chunk_overlap: Optional[int] = 100, context_window: Optional[int] = None, enable_title_extractor: bool = False, enable_summary_extractor: bool = False, enable_qa_extractor: bool = False, enable_keyword_extractor: bool = False, enable_entity_extractor: bool = False, **kwargs) -> ServiceContext: """ Create a ServiceContext with default parameters with extended enable_token_counting functionality. If enable_token_counting is True, tracks the number of tokens used by the LLM for each query. Parameters: llm (LLM): The LLM to use for the query engine. Defaults to gpt-3.5-turbo. embed_model (BaseEmbedding): The embedding model to use for the query engine. Defaults to OpenAIEmbedding. system_prompt (str): The system prompt to use for the query engine. query_wrapper_prompt (Union[str, BasePromptTemplate]): The query wrapper prompt to use for the query engine. enable_cost_calculator (bool): Flag to enable cost calculator logging. chunk_size (int): The token chunk size for each chunk. chunk_overlap (int): The token overlap between each chunk. context_window (int): The maximum context size that will get sent to the LLM. enable_title_extractor (bool): Flag to enable title extractor. enable_summary_extractor (bool): Flag to enable summary extractor. enable_qa_extractor (bool): Flag to enable question answering extractor. enable_keyword_extractor (bool): Flag to enable keyword extractor. enable_entity_extractor (bool): Flag to enable entity extractor. **kwargs: Arbitrary keyword arguments. Returns: ServiceContext: The initialized ServiceContext from default parameters with extra token counting functionality. """ if not system_prompt and not query_wrapper_prompt: system_prompt, query_wrapper_prompt = set_default_prompt_template() # Convert query_wrapper_prompt to PromptTemplate if it is a string if isinstance(query_wrapper_prompt, str): query_wrapper_prompt = PromptTemplate(template=query_wrapper_prompt) callback_manager: CallbackManager = kwargs.get('callback_manager', CallbackManager()) kwargs.pop( 'callback_manager', None) # Make sure callback_manager is not passed to ServiceContext twice if enable_cost_calculator: llm_model_name = llm.metadata.model_name if not "default" else "gpt-3.5-turbo" callback_manager.add_handler(CostCalculatingHandler(model_name=llm_model_name, verbose=True)) sentence_splitter = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) transformations = [sentence_splitter] if enable_entity_extractor: transformations.append(EntityExtractor()) if enable_keyword_extractor: transformations.append(KeywordExtractor(llm=llm, keywords=5)) if enable_summary_extractor: transformations.append(SummaryExtractor(llm=llm, summaries=["prev", "self"])) if enable_title_extractor: transformations.append(TitleExtractor(llm=llm, nodes=5)) if enable_qa_extractor: transformations.append(QuestionsAnsweredExtractor(llm=llm, questions=5)) service_context = ServiceContext.from_defaults( llm=llm, embed_model=embed_model, transformations=transformations, system_prompt=system_prompt, query_wrapper_prompt=query_wrapper_prompt, chunk_size=chunk_size, chunk_overlap=chunk_overlap, context_window=context_window, callback_manager=callback_manager, **kwargs) return service_context
[ "llama_index.extractors.TitleExtractor", "llama_index.ServiceContext.from_defaults", "llama_index.prompts.PromptTemplate", "llama_index.extractors.KeywordExtractor", "llama_index.extractors.QuestionsAnsweredExtractor", "llama_index.callbacks.CallbackManager", "llama_index.text_splitter.SentenceSplitter", "llama_index.extractors.EntityExtractor", "llama_index.extractors.SummaryExtractor" ]
[((3952, 4020), 'llama_index.text_splitter.SentenceSplitter', 'SentenceSplitter', ([], {'chunk_size': 'chunk_size', 'chunk_overlap': 'chunk_overlap'}), '(chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n', (3968, 4020), False, 'from llama_index.text_splitter import SentenceSplitter\n'), ((4643, 4954), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'llm': 'llm', 'embed_model': 'embed_model', 'transformations': 'transformations', 'system_prompt': 'system_prompt', 'query_wrapper_prompt': 'query_wrapper_prompt', 'chunk_size': 'chunk_size', 'chunk_overlap': 'chunk_overlap', 'context_window': 'context_window', 'callback_manager': 'callback_manager'}), '(llm=llm, embed_model=embed_model,\n transformations=transformations, system_prompt=system_prompt,\n query_wrapper_prompt=query_wrapper_prompt, chunk_size=chunk_size,\n chunk_overlap=chunk_overlap, context_window=context_window,\n callback_manager=callback_manager, **kwargs)\n', (4671, 4954), False, 'from llama_index import ServiceContext\n'), ((3233, 3262), 'autollm.utils.llm_utils.set_default_prompt_template', 'set_default_prompt_template', ([], {}), '()\n', (3260, 3262), False, 'from autollm.utils.llm_utils import set_default_prompt_template\n'), ((3423, 3468), 'llama_index.prompts.PromptTemplate', 'PromptTemplate', ([], {'template': 'query_wrapper_prompt'}), '(template=query_wrapper_prompt)\n', (3437, 3468), False, 'from llama_index.prompts import PromptTemplate\n'), ((3545, 3562), 'llama_index.callbacks.CallbackManager', 'CallbackManager', ([], {}), '()\n', (3560, 3562), False, 'from llama_index.callbacks import CallbackManager\n'), ((3858, 3921), 'autollm.callbacks.cost_calculating.CostCalculatingHandler', 'CostCalculatingHandler', ([], {'model_name': 'llm_model_name', 'verbose': '(True)'}), '(model_name=llm_model_name, verbose=True)\n', (3880, 3921), False, 'from autollm.callbacks.cost_calculating import CostCalculatingHandler\n'), ((4138, 4155), 'llama_index.extractors.EntityExtractor', 'EntityExtractor', ([], {}), '()\n', (4153, 4155), False, 'from llama_index.extractors import EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor\n'), ((4229, 4266), 'llama_index.extractors.KeywordExtractor', 'KeywordExtractor', ([], {'llm': 'llm', 'keywords': '(5)'}), '(llm=llm, keywords=5)\n', (4245, 4266), False, 'from llama_index.extractors import EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor\n'), ((4340, 4393), 'llama_index.extractors.SummaryExtractor', 'SummaryExtractor', ([], {'llm': 'llm', 'summaries': "['prev', 'self']"}), "(llm=llm, summaries=['prev', 'self'])\n", (4356, 4393), False, 'from llama_index.extractors import EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor\n'), ((4465, 4497), 'llama_index.extractors.TitleExtractor', 'TitleExtractor', ([], {'llm': 'llm', 'nodes': '(5)'}), '(llm=llm, nodes=5)\n', (4479, 4497), False, 'from llama_index.extractors import EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor\n'), ((4566, 4614), 'llama_index.extractors.QuestionsAnsweredExtractor', 'QuestionsAnsweredExtractor', ([], {'llm': 'llm', 'questions': '(5)'}), '(llm=llm, questions=5)\n', (4592, 4614), False, 'from llama_index.extractors import EntityExtractor, KeywordExtractor, QuestionsAnsweredExtractor, SummaryExtractor, TitleExtractor\n')]
from rag.agents.interface import Pipeline from llama_index.core.program import LLMTextCompletionProgram import json from llama_index.llms.ollama import Ollama from typing import List from pydantic import create_model from rich.progress import Progress, SpinnerColumn, TextColumn import requests import warnings import box import yaml import timeit from rich import print from typing import Any warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", category=UserWarning) # Import config vars with open('config.yml', 'r', encoding='utf8') as ymlfile: cfg = box.Box(yaml.safe_load(ymlfile)) class VProcessorPipeline(Pipeline): def run_pipeline(self, payload: str, query_inputs: [str], query_types: [str], query: str, file_path: str, index_name: str, debug: bool = False, local: bool = True) -> Any: print(f"\nRunning pipeline with {payload}\n") start = timeit.default_timer() if file_path is None: raise ValueError("File path is required for vprocessor pipeline") with open(file_path, "rb") as file: files = {'file': (file_path, file, 'image/jpeg')} data = { 'image_url': '' } response = self.invoke_pipeline_step(lambda: requests.post(cfg.VPROCESSOR_OCR_ENDPOINT, data=data, files=files, timeout=180), "Running OCR...", local) if response.status_code != 200: print('Request failed with status code:', response.status_code) print('Response:', response.text) return "Failed to process file. Please try again." end = timeit.default_timer() print(f"Time to run OCR: {end - start}") start = timeit.default_timer() data = response.json() ResponseModel = self.invoke_pipeline_step(lambda: self.build_response_class(query_inputs, query_types), "Building dynamic response class...", local) prompt_template_str = """\ """ + query + """\ using this structured data, coming from OCR {document_data}.\ """ llm_ollama = self.invoke_pipeline_step(lambda: Ollama(model=cfg.LLM_VPROCESSOR, base_url=cfg.OLLAMA_BASE_URL_VPROCESSOR, temperature=0, request_timeout=900), "Loading Ollama...", local) program = LLMTextCompletionProgram.from_defaults( output_cls=ResponseModel, prompt_template_str=prompt_template_str, llm=llm_ollama, verbose=True, ) output = self.invoke_pipeline_step(lambda: program(document_data=data), "Running inference...", local) answer = self.beautify_json(output.model_dump_json()) end = timeit.default_timer() print(f"\nJSON response:\n") print(answer + '\n') print('=' * 50) print(f"Time to retrieve answer: {end - start}") return answer def prepare_files(self, file_path, file): if file_path is not None: with open(file_path, "rb") as file: files = {'file': (file_path, file, 'image/jpeg')} data = { 'image_url': '' } else: files = {'file': (file.filename, file.file, file.content_type)} data = { 'image_url': '' } return data, files # Function to safely evaluate type strings def safe_eval_type(self, type_str, context): try: return eval(type_str, {}, context) except NameError: raise ValueError(f"Type '{type_str}' is not recognized") def build_response_class(self, query_inputs, query_types_as_strings): # Controlled context for eval context = { 'List': List, 'str': str, 'int': int, 'float': float # Include other necessary types or typing constructs here } # Convert string representations to actual types query_types = [self.safe_eval_type(type_str, context) for type_str in query_types_as_strings] # Create fields dictionary fields = {name: (type_, ...) for name, type_ in zip(query_inputs, query_types)} DynamicModel = create_model('DynamicModel', **fields) return DynamicModel def invoke_pipeline_step(self, task_call, task_description, local): if local: with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=False, ) as progress: progress.add_task(description=task_description, total=None) ret = task_call() else: print(task_description) ret = task_call() return ret def beautify_json(self, result): try: # Convert and pretty print data = json.loads(str(result)) data = json.dumps(data, indent=4) return data except (json.decoder.JSONDecodeError, TypeError): print("The response is not in JSON format:\n") print(result) return {}
[ "llama_index.core.program.LLMTextCompletionProgram.from_defaults", "llama_index.llms.ollama.Ollama" ]
[((396, 458), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (419, 458), False, 'import warnings\n'), ((459, 514), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (482, 514), False, 'import warnings\n'), ((614, 637), 'yaml.safe_load', 'yaml.safe_load', (['ymlfile'], {}), '(ymlfile)\n', (628, 637), False, 'import yaml\n'), ((1029, 1076), 'rich.print', 'print', (['f"""\nRunning pipeline with {payload}\n"""'], {}), '(f"""\nRunning pipeline with {payload}\n""")\n', (1034, 1076), False, 'from rich import print\n'), ((1092, 1114), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (1112, 1114), False, 'import timeit\n'), ((2116, 2138), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2136, 2138), False, 'import timeit\n'), ((2147, 2187), 'rich.print', 'print', (['f"""Time to run OCR: {end - start}"""'], {}), "(f'Time to run OCR: {end - start}')\n", (2152, 2187), False, 'from rich import print\n'), ((2205, 2227), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2225, 2227), False, 'import timeit\n'), ((3157, 3296), 'llama_index.core.program.LLMTextCompletionProgram.from_defaults', 'LLMTextCompletionProgram.from_defaults', ([], {'output_cls': 'ResponseModel', 'prompt_template_str': 'prompt_template_str', 'llm': 'llm_ollama', 'verbose': '(True)'}), '(output_cls=ResponseModel,\n prompt_template_str=prompt_template_str, llm=llm_ollama, verbose=True)\n', (3195, 3296), False, 'from llama_index.core.program import LLMTextCompletionProgram\n'), ((3628, 3650), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3648, 3650), False, 'import timeit\n'), ((3660, 3690), 'rich.print', 'print', (['f"""\nJSON response:\n"""'], {}), '(f"""\nJSON response:\n""")\n', (3665, 3690), False, 'from rich import print\n'), ((3697, 3717), 'rich.print', 'print', (["(answer + '\\n')"], {}), "(answer + '\\n')\n", (3702, 3717), False, 'from rich import print\n'), ((3726, 3741), 'rich.print', 'print', (["('=' * 50)"], {}), "('=' * 50)\n", (3731, 3741), False, 'from rich import print\n'), ((3751, 3799), 'rich.print', 'print', (['f"""Time to retrieve answer: {end - start}"""'], {}), "(f'Time to retrieve answer: {end - start}')\n", (3756, 3799), False, 'from rich import print\n'), ((5158, 5196), 'pydantic.create_model', 'create_model', (['"""DynamicModel"""'], {}), "('DynamicModel', **fields)\n", (5170, 5196), False, 'from pydantic import create_model\n'), ((1927, 1990), 'rich.print', 'print', (['"""Request failed with status code:"""', 'response.status_code'], {}), "('Request failed with status code:', response.status_code)\n", (1932, 1990), False, 'from rich import print\n'), ((2003, 2036), 'rich.print', 'print', (['"""Response:"""', 'response.text'], {}), "('Response:', response.text)\n", (2008, 2036), False, 'from rich import print\n'), ((5657, 5680), 'rich.print', 'print', (['task_description'], {}), '(task_description)\n', (5662, 5680), False, 'from rich import print\n'), ((5884, 5910), 'json.dumps', 'json.dumps', (['data'], {'indent': '(4)'}), '(data, indent=4)\n', (5894, 5910), False, 'import json\n'), ((2719, 2832), 'llama_index.llms.ollama.Ollama', 'Ollama', ([], {'model': 'cfg.LLM_VPROCESSOR', 'base_url': 'cfg.OLLAMA_BASE_URL_VPROCESSOR', 'temperature': '(0)', 'request_timeout': '(900)'}), '(model=cfg.LLM_VPROCESSOR, base_url=cfg.OLLAMA_BASE_URL_VPROCESSOR,\n temperature=0, request_timeout=900)\n', (2725, 2832), False, 'from llama_index.llms.ollama import Ollama\n'), ((6005, 6051), 'rich.print', 'print', (['"""The response is not in JSON format:\n"""'], {}), "('The response is not in JSON format:\\n')\n", (6010, 6051), False, 'from rich import print\n'), ((6064, 6077), 'rich.print', 'print', (['result'], {}), '(result)\n', (6069, 6077), False, 'from rich import print\n'), ((1457, 1536), 'requests.post', 'requests.post', (['cfg.VPROCESSOR_OCR_ENDPOINT'], {'data': 'data', 'files': 'files', 'timeout': '(180)'}), '(cfg.VPROCESSOR_OCR_ENDPOINT, data=data, files=files, timeout=180)\n', (1470, 1536), False, 'import requests\n'), ((5364, 5379), 'rich.progress.SpinnerColumn', 'SpinnerColumn', ([], {}), '()\n', (5377, 5379), False, 'from rich.progress import Progress, SpinnerColumn, TextColumn\n'), ((5401, 5455), 'rich.progress.TextColumn', 'TextColumn', (['"""[progress.description]{task.description}"""'], {}), "('[progress.description]{task.description}')\n", (5411, 5455), False, 'from rich.progress import Progress, SpinnerColumn, TextColumn\n')]