Distributes the load across multiple language models. Useful for circumventing low rate limits with certain api providers especially if you are on the free tier. Could also be used for spliting across diffrent models or providers. Attributes: models (List[Model]): A list of lan
| 750 | |
| 751 | |
| 752 | class MultiModel: |
| 753 | """ |
| 754 | Distributes the load across multiple language models. Useful for circumventing low rate limits with certain api providers especially if you are on the free tier. |
| 755 | Could also be used for spliting across diffrent models or providers. |
| 756 | |
| 757 | Attributes: |
| 758 | models (List[Model]): A list of language models to be used. |
| 759 | |
| 760 | Usage example: |
| 761 | ```python |
| 762 | models = [ |
| 763 | Model(gen_func=openai_complete_if_cache, kwargs={"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY_1"]}), |
| 764 | Model(gen_func=openai_complete_if_cache, kwargs={"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY_2"]}), |
| 765 | Model(gen_func=openai_complete_if_cache, kwargs={"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY_3"]}), |
| 766 | Model(gen_func=openai_complete_if_cache, kwargs={"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY_4"]}), |
| 767 | Model(gen_func=openai_complete_if_cache, kwargs={"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY_5"]}), |
| 768 | ] |
| 769 | multi_model = MultiModel(models) |
| 770 | rag = LightRAG( |
| 771 | llm_model_func=multi_model.llm_model_func |
| 772 | / ..other args |
| 773 | ) |
| 774 | ``` |
| 775 | """ |
| 776 | |
| 777 | def __init__(self, models: List[Model]): |
| 778 | self._models = models |
| 779 | self._current_model = 0 |
| 780 | |
| 781 | def _next_model(self): |
| 782 | self._current_model = (self._current_model + 1) % len(self._models) |
| 783 | return self._models[self._current_model] |
| 784 | |
| 785 | async def llm_model_func( |
| 786 | self, prompt, system_prompt=None, history_messages=[], **kwargs |
| 787 | ) -> str: |
| 788 | kwargs.pop("model", None) # stop from overwriting the custom model name |
| 789 | next_model = self._next_model() |
| 790 | args = dict( |
| 791 | prompt=prompt, |
| 792 | system_prompt=system_prompt, |
| 793 | history_messages=history_messages, |
| 794 | **kwargs, |
| 795 | **next_model.kwargs, |
| 796 | ) |
| 797 | |
| 798 | return await next_model.gen_func(**args) |
| 799 | |
| 800 | |
| 801 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected