|
1 | 1 | """Module to interface with various language models through their respective APIs.""" |
2 | 2 |
|
3 | | -import asyncio |
4 | | -import time |
5 | | -from logging import Logger |
6 | | -from typing import Any, List |
7 | 3 |
|
8 | | -import nest_asyncio |
9 | | -import openai |
10 | | -import requests |
11 | | -from langchain_anthropic import ChatAnthropic |
12 | | -from langchain_community.chat_models.deepinfra import ChatDeepInfra, ChatDeepInfraException |
13 | | -from langchain_core.messages import HumanMessage, SystemMessage |
14 | | -from langchain_openai import ChatOpenAI |
| 4 | +try: |
| 5 | + import asyncio |
15 | 6 |
|
16 | | -from promptolution.llms.base_llm import BaseLLM |
| 7 | + from openai import AsyncOpenAI |
17 | 8 |
|
18 | | -logger = Logger(__name__) |
| 9 | + import_successful = True |
| 10 | +except ImportError: |
| 11 | + import_successful = False |
19 | 12 |
|
| 13 | +from logging import Logger |
| 14 | +from typing import Any, List |
20 | 15 |
|
21 | | -async def invoke_model(prompt, system_prompt, model, semaphore): |
22 | | - """Asynchronously invoke a language model with retry logic. |
| 16 | +from promptolution.llms.base_llm import BaseLLM |
23 | 17 |
|
24 | | - Args: |
25 | | - prompt (str): The input prompt for the model. |
26 | | - system_prompt (str): The system prompt for the model. |
27 | | - model: The language model to invoke. |
28 | | - semaphore (asyncio.Semaphore): Semaphore to limit concurrent calls. |
| 18 | +logger = Logger(__name__) |
29 | 19 |
|
30 | | - Returns: |
31 | | - str: The model's response content. |
32 | 20 |
|
33 | | - Raises: |
34 | | - ChatDeepInfraException: If all retry attempts fail. |
35 | | - """ |
| 21 | +async def _invoke_model(prompt, system_prompt, max_tokens, model_id, client, semaphore): |
36 | 22 | async with semaphore: |
37 | | - max_retries = 100 |
38 | | - delay = 3 |
39 | | - attempts = 0 |
40 | | - |
41 | | - while attempts < max_retries: |
42 | | - try: |
43 | | - response = await model.ainvoke([SystemMessage(content=system_prompt), HumanMessage(content=prompt)]) |
44 | | - return response.content |
45 | | - except ChatDeepInfraException as e: |
46 | | - print(f"DeepInfra error: {e}. Attempt {attempts}/{max_retries}. Retrying in {delay} seconds...") |
47 | | - attempts += 1 |
48 | | - await asyncio.sleep(delay) |
| 23 | + messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}] |
| 24 | + response = await client.chat.completions.create( |
| 25 | + model=model_id, |
| 26 | + messages=messages, |
| 27 | + max_tokens=max_tokens, |
| 28 | + ) |
| 29 | + return response |
49 | 30 |
|
50 | 31 |
|
51 | 32 | class APILLM(BaseLLM): |
52 | | - """A class to interface with various language models through their respective APIs. |
| 33 | + """A class to interface with language models through their respective APIs. |
53 | 34 |
|
54 | | - This class supports Claude (Anthropic), GPT (OpenAI), and LLaMA (DeepInfra) models. |
55 | | - It handles API key management, model initialization, and provides methods for |
56 | | - both synchronous and asynchronous inference. |
| 35 | + This class provides a unified interface for making API calls to language models |
| 36 | + using the OpenAI client library. It handles rate limiting through semaphores |
| 37 | + and supports both synchronous and asynchronous operations. |
57 | 38 |
|
58 | 39 | Attributes: |
59 | | - model: The initialized language model instance. |
60 | | -
|
61 | | - Methods: |
62 | | - get_response: Synchronously get responses for a list of prompts. |
63 | | - get_response_async: Asynchronously get responses for a list of prompts. |
| 40 | + model_id (str): Identifier for the model to use. |
| 41 | + client (AsyncOpenAI): The initialized API client. |
| 42 | + max_tokens (int): Maximum number of tokens in model responses. |
| 43 | + semaphore (asyncio.Semaphore): Semaphore to limit concurrent API calls. |
64 | 44 | """ |
65 | 45 |
|
66 | | - def __init__(self, model_id: str, token: str = None, **kwargs: Any): |
67 | | - """Initialize the APILLM with a specific model. |
| 46 | + def __init__( |
| 47 | + self, api_url: str, model_id: str, token: str = None, max_concurrent_calls=50, max_tokens=512, **kwargs: Any |
| 48 | + ): |
| 49 | + """Initialize the APILLM with a specific model and API configuration. |
68 | 50 |
|
69 | 51 | Args: |
| 52 | + api_url (str): The base URL for the API endpoint. |
70 | 53 | model_id (str): Identifier for the model to use. |
71 | | - token (str): API key for the model. |
| 54 | + token (str, optional): API key for authentication. Defaults to None. |
| 55 | + max_concurrent_calls (int, optional): Maximum number of concurrent API calls. Defaults to 50. |
| 56 | + max_tokens (int, optional): Maximum number of tokens in model responses. Defaults to 512. |
| 57 | + **kwargs (Any): Additional parameters to pass to the API client. |
72 | 58 |
|
73 | 59 | Raises: |
74 | | - ValueError: If an unknown model identifier is provided. |
| 60 | + ImportError: If required libraries are not installed. |
75 | 61 | """ |
| 62 | + if not import_successful: |
| 63 | + raise ImportError( |
| 64 | + "Could not import at least one of the required libraries: openai, asyncio. " |
| 65 | + "Please ensure they are installed in your environment." |
| 66 | + ) |
76 | 67 | super().__init__() |
77 | | - if "claude" in model_id: |
78 | | - self.model = ChatAnthropic(model=model_id, api_key=token) |
79 | | - elif "gpt" in model_id: |
80 | | - self.model = ChatOpenAI(model=model_id, api_key=token) |
81 | | - else: |
82 | | - self.model = ChatDeepInfra(model_name=model_id, deepinfra_api_token=token) |
83 | | - |
84 | | - def _get_response(self, prompts: List[str], system_prompts: List[str] = None) -> List[str]: |
85 | | - """Get responses for a list of prompts in a synchronous manner. |
| 68 | + self.model_id = model_id |
| 69 | + self.client = AsyncOpenAI(base_url=api_url, api_key=token, **kwargs) |
| 70 | + self.max_tokens = max_tokens |
86 | 71 |
|
87 | | - This method includes retry logic for handling connection errors and rate limits. |
| 72 | + self.semaphore = asyncio.Semaphore(max_concurrent_calls) |
88 | 73 |
|
89 | | - Args: |
90 | | - prompts (list[str]): List of input prompts. |
91 | | - system_prompts (list[str]): List of system prompts. If not provided, uses default system_prompts |
92 | | -
|
93 | | - Returns: |
94 | | - list[str]: List of model responses. |
95 | | -
|
96 | | - Raises: |
97 | | - requests.exceptions.ConnectionError: If max retries are exceeded. |
98 | | - """ |
99 | | - max_retries = 100 |
100 | | - delay = 3 |
101 | | - attempts = 0 |
102 | | - |
103 | | - nest_asyncio.apply() |
104 | | - |
105 | | - while attempts < max_retries: |
106 | | - try: |
107 | | - responses = asyncio.run(self.get_response_async(prompts)) |
108 | | - return responses |
109 | | - except requests.exceptions.ConnectionError as e: |
110 | | - attempts += 1 |
111 | | - logger.critical( |
112 | | - f"Connection error: {e}. Attempt {attempts}/{max_retries}. Retrying in {delay} seconds..." |
113 | | - ) |
114 | | - time.sleep(delay) |
115 | | - except openai.RateLimitError as e: |
116 | | - attempts += 1 |
117 | | - logger.critical( |
118 | | - f"Rate limit error: {e}. Attempt {attempts}/{max_retries}. Retrying in {delay} seconds..." |
119 | | - ) |
120 | | - time.sleep(delay) |
121 | | - |
122 | | - # If the loop exits, it means max retries were reached |
123 | | - raise requests.exceptions.ConnectionError("Max retries exceeded. Connection could not be established.") |
124 | | - |
125 | | - async def get_response_async(self, prompts: list[str], max_concurrent_calls=200) -> list[str]: |
126 | | - """Asynchronously get responses for a list of prompts. |
127 | | -
|
128 | | - This method uses a semaphore to limit the number of concurrent API calls. |
129 | | -
|
130 | | - Args: |
131 | | - prompts (list[str]): List of input prompts. |
132 | | - max_concurrent_calls (int): Maximum number of concurrent API calls allowed. |
133 | | -
|
134 | | - Returns: |
135 | | - list[str]: List of model responses. |
136 | | - """ |
137 | | - semaphore = asyncio.Semaphore(max_concurrent_calls) |
138 | | - tasks = [] |
139 | | - |
140 | | - for prompt in prompts: |
141 | | - tasks.append(invoke_model(prompt, self.model, semaphore)) |
| 74 | + def _get_response(self, prompts: List[str], system_prompts: List[str]) -> List[str]: |
| 75 | + # Setup for async execution in sync context |
| 76 | + loop = asyncio.get_event_loop() |
| 77 | + responses = loop.run_until_complete(self._get_response_async(prompts, system_prompts)) |
| 78 | + return responses |
142 | 79 |
|
| 80 | + async def _get_response_async(self, prompts: List[str], system_prompts: List[str]) -> List[str]: |
| 81 | + tasks = [ |
| 82 | + _invoke_model(prompt, system_prompt, self.max_tokens, self.model_id, self.client, self.semaphore) |
| 83 | + for prompt, system_prompt in zip(prompts, system_prompts) |
| 84 | + ] |
143 | 85 | responses = await asyncio.gather(*tasks) |
144 | | - return responses |
| 86 | + return [response.choices[0].message.content for response in responses] |
0 commit comments