Skip to content

Commit a06bc25

Browse files
committed
docstrs
1 parent c035edc commit a06bc25

File tree

2 files changed

+78
-67
lines changed

2 files changed

+78
-67
lines changed

ovos_solver_openai_persona/engines.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,10 @@ def __init__(self, config=None,
101101
enable_cache: bool = False,
102102
internal_lang: Optional[str] = None):
103103
"""
104-
Initializes the OpenAIChatCompletionsSolver with API configuration, memory settings, and system prompt.
105-
104+
Initialize an OpenAIChatCompletionsSolver instance with API configuration, conversation memory settings, and system prompt.
105+
106106
Raises:
107-
ValueError: If the API key is not provided in the configuration.
107+
ValueError: If the API key is missing from the configuration.
108108
"""
109109
super().__init__(config=config, translator=translator,
110110
detector=detector, priority=priority,
@@ -131,16 +131,16 @@ def __init__(self, config=None,
131131
# OpenAI API integration
132132
def _do_api_request(self, messages):
133133
"""
134-
Sends a chat completion request to the OpenAI API and returns the assistant's reply.
134+
Send a chat completion request to the OpenAI API using the provided conversation history and return the assistant's reply.
135135
136-
Args:
137-
messages: A list of message dictionaries representing the conversation history.
136+
Parameters:
137+
messages (list): Conversation history as a list of message dictionaries.
138138
139139
Returns:
140-
The content of the assistant's reply as a string.
140+
str: The assistant's reply content.
141141
142142
Raises:
143-
RequestException: If the OpenAI API returns an error in the response.
143+
RequestException: If the OpenAI API response contains an error.
144144
"""
145145
s = requests.Session()
146146
headers = {
@@ -243,14 +243,14 @@ def get_chat_history(self, system_prompt=None):
243243

244244
def get_messages(self, utt, system_prompt=None) -> MessageList:
245245
"""
246-
Builds a list of chat messages including the system prompt, recent conversation history, and the current user utterance.
246+
Constructs a list of chat messages for the API, including the system prompt, recent conversation history, and the current user utterance.
247247
248-
Args:
249-
utt: The current user input to be appended as the latest message.
248+
Parameters:
249+
utt: The current user input to be added as the latest message.
250250
system_prompt: Optional system prompt to use as the initial message.
251251
252252
Returns:
253-
A list of message dictionaries representing the chat context for the API.
253+
A list of message dictionaries representing the chat context.
254254
"""
255255
messages = self.get_chat_history(system_prompt)
256256
messages.append({"role": "user", "content": utt})
@@ -261,17 +261,17 @@ def continue_chat(self, messages: MessageList,
261261
lang: Optional[str],
262262
units: Optional[str] = None) -> Optional[str]:
263263
"""
264-
Generates a chat response using the provided message history and updates memory if enabled.
264+
Generate a chat response based on the provided message history and update conversation memory if enabled.
265265
266-
If the first message is not a system prompt, prepends the system prompt. Processes the API response and returns a cleaned answer, or None if the answer is empty or only punctuation/underscores. Updates internal memory with the latest question and answer if memory is enabled.
266+
If the first message is not a system prompt, prepends the system prompt. Returns a cleaned response string, or None if the response is empty or contains only punctuation or underscores. Updates internal memory with the latest user message and answer when memory is enabled.
267267
268-
Args:
269-
messages: List of chat messages with 'role' and 'content' keys.
270-
lang: Optional language code for the response.
271-
units: Optional unit system for numerical values.
268+
Parameters:
269+
messages (MessageList): List of chat messages, each with 'role' and 'content' keys.
270+
lang (Optional[str]): Language code for the response.
271+
units (Optional[str]): Unit system for numerical values.
272272
273273
Returns:
274-
The generated response as a string, or None if no valid response is produced.
274+
Optional[str]: The generated response string, or None if no valid response is produced.
275275
"""
276276
if messages[0]["role"] != "system":
277277
messages = [{"role": "system", "content": self.system_prompt }] + messages
@@ -322,15 +322,15 @@ def stream_utterances(self, query: str,
322322
lang: Optional[str] = None,
323323
units: Optional[str] = None) -> Iterable[str]:
324324
"""
325-
Stream utterances for the given query as they become available.
325+
Yields partial responses for a query as they are generated by the chat completions API.
326326
327-
Args:
328-
query (str): The query text.
329-
lang (Optional[str]): Optional language code. Defaults to None.
330-
units (Optional[str]): Optional units for the query. Defaults to None.
327+
Parameters:
328+
query (str): The user query to send to the chat model.
329+
lang (Optional[str]): Language code for the response, if applicable.
330+
units (Optional[str]): Units relevant to the query, if applicable.
331331
332332
Returns:
333-
Iterable[str]: An iterable of utterances.
333+
Iterable[str]: An iterator yielding segments of the model's response as they become available.
334334
"""
335335
messages = self.get_messages(query)
336336
yield from self.stream_chat_utterances(messages, lang, units)

ovos_solver_openai_persona/rag.py

Lines changed: 53 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -100,16 +100,16 @@ def __init__(self, config: Optional[Dict[str, Any]] = None,
100100

101101
def _search_vector_store(self, query: str) -> List[str]:
102102
"""
103-
Performs a search against the ovos-persona-server's vector store.
103+
Searches the configured vector store for relevant text chunks matching the user query.
104104
105-
Args:
106-
query (str): The user's query string.
105+
Parameters:
106+
query (str): The user's query string to search for relevant context.
107107
108108
Returns:
109-
List[str]: A list of relevant text chunks (content) retrieved from the vector store.
109+
List[str]: A list of text chunks retrieved from the vector store that are relevant to the query.
110110
111111
Raises:
112-
RequestException: If the search API call fails or returns an error.
112+
RequestException: If the search request fails or the response format is invalid.
113113
"""
114114
search_url = f"{self.api_url}/vector_stores/{self.vector_store_id}/search"
115115
headers = {"Content-Type": "application/json"}
@@ -140,15 +140,17 @@ def _search_vector_store(self, query: str) -> List[str]:
140140

141141
def _build_llm_messages(self, user_query: str, retrieved_context_chunks: List[str], chat_history: List[Dict[str, str]]) -> List[Dict[str, str]]:
142142
"""
143-
Constructs the complete message list for the LLM, including RAG context and chat history.
143+
Constructs the message list for the LLM by combining retrieved context, recent chat history, and the current user query.
144144
145-
Args:
146-
user_query (str): The current user's utterance.
147-
retrieved_context_chunks (List[str]): List of text chunks retrieved from the vector store.
148-
chat_history (List[Dict[str, str]]): The conversation history from `self.qa_pairs`.
145+
The method concatenates relevant context chunks (up to a token limit), formats the system prompt with this context and the user's question, appends recent Q&A pairs from memory, and adds the current user query as the final message.
146+
147+
Parameters:
148+
user_query (str): The user's current question or utterance.
149+
retrieved_context_chunks (List[str]): Relevant text segments retrieved from the vector store.
150+
chat_history (List[Dict[str, str]]): Previous conversation history.
149151
150152
Returns:
151-
List[Dict[str, str]]: A new list of messages, augmented with the RAG context and history.
153+
List[Dict[str, str]]: The complete list of messages to send to the LLM, including system prompt, chat history, and user query.
152154
"""
153155
context_str = ""
154156
current_context_tokens = 0
@@ -186,8 +188,10 @@ def _build_llm_messages(self, user_query: str, retrieved_context_chunks: List[st
186188

187189
def get_chat_history(self) -> List[Dict[str, str]]:
188190
"""
189-
Returns the chat history managed by this RAG solver.
190-
This method is called by the base ChatMessageSolver.
191+
Return the recent chat history as a list of user and assistant messages.
192+
193+
Returns:
194+
List of message dictionaries representing the most recent question-answer pairs, formatted with roles 'user' and 'assistant'.
191195
"""
192196
# The base class expects a list of messages (role, content).
193197
# We store (query, answer) tuples.
@@ -202,17 +206,18 @@ def continue_chat(self, messages: List[Dict[str, str]],
202206
lang: Optional[str],
203207
units: Optional[str] = None) -> Optional[str]:
204208
"""
205-
Generates a chat response using RAG by directly calling the Persona Server's
206-
chat completions endpoint.
209+
Generate a chat response by augmenting the user query with retrieved context from a vector store and sending the constructed prompt to the Persona Server's chat completions endpoint.
207210
208-
Args:
209-
messages: List of chat messages with 'role' and 'content' keys.
210-
The last user message is used for RAG retrieval and as the current query.
211-
lang: Optional language code for the response.
212-
units: Optional unit system for numerical values.
211+
Parameters:
212+
messages (List[Dict[str, str]]): List of chat messages, where the last message is treated as the current user query.
213+
lang (Optional[str]): Optional language code for the response.
214+
units (Optional[str]): Optional unit system for numerical values.
213215
214216
Returns:
215-
The generated response as a string, or None if no valid response is produced.
217+
Optional[str]: The generated response as a string, or None if no valid response is produced.
218+
219+
Raises:
220+
RequestException: If the Persona Server's chat completions endpoint returns an error or an invalid response.
216221
"""
217222
user_query = messages[-1]["content"] # Get the current user query
218223

@@ -265,16 +270,17 @@ def stream_chat_utterances(self, messages: List[Dict[str, str]],
265270
lang: Optional[str] = None,
266271
units: Optional[str] = None) -> Iterable[str]: # Yields raw data: lines
267272
"""
268-
Stream utterances for the given chat history using RAG by directly calling the Persona Server's
269-
chat completions endpoint in streaming mode.
273+
Streams chat completion responses from the Persona Server using Retrieval Augmented Generation (RAG), yielding each line of streamed data as it arrives.
270274
271-
Args:
272-
messages: The chat messages. The last user message is used for RAG retrieval and as the current query.
273-
lang (Optional[str]): Optional language code. Defaults to None.
274-
units (Optional[str]): Optional units for the query. Defaults to None.
275+
The method retrieves relevant context from the vector store based on the latest user query, augments the chat history, and streams the LLM's response line by line. If enabled, it stores the full answer in memory for multi-turn conversations.
276+
277+
Parameters:
278+
messages (List[Dict[str, str]]): The chat history, with the last message as the current user query.
279+
lang (Optional[str]): Optional language code for the query.
280+
units (Optional[str]): Optional units for the query.
275281
276282
Returns:
277-
Iterable[str]: An iterable of raw data: [JSON] strings from the streaming API.
283+
Iterable[str]: Yields each raw data line (as a string) from the streaming API response.
278284
"""
279285
user_query = messages[-1]["content"] # Get the current user query
280286

@@ -339,15 +345,15 @@ def stream_utterances(self, query: str,
339345
lang: Optional[str] = None,
340346
units: Optional[str] = None) -> Iterable[str]:
341347
"""
342-
Stream utterances for the given query using RAG.
348+
Streams the assistant's response for a given user query, incorporating current chat history and Retrieval Augmented Generation context.
343349
344-
Args:
345-
query (str): The query text.
346-
lang (Optional[str]): Optional language code. Defaults to None.
347-
units (Optional[str]): Optional units for the query. Defaults to None.
350+
Parameters:
351+
query (str): The user's input query.
352+
lang (Optional[str]): Language code for the response, if applicable.
353+
units (Optional[str]): Units relevant to the query, if applicable.
348354
349355
Returns:
350-
Iterable[str]: An iterable of raw data: [JSON] strings from the streaming API.
356+
Iterable[str]: Yields raw data chunks from the streaming chat completions API.
351357
"""
352358
# For stream_utterances, we directly build a single-turn message list
353359
# We need to include existing chat history here as well for proper context
@@ -359,15 +365,15 @@ def get_spoken_answer(self, query: str,
359365
lang: Optional[str] = None,
360366
units: Optional[str] = None) -> Optional[str]:
361367
"""
362-
Obtain the spoken answer for a given query using RAG.
368+
Return the assistant's spoken answer to a user query, incorporating recent chat history for context.
363369
364-
Args:
365-
query (str): The query text.
366-
lang (Optional[str]): Optional language code. Defaults to None.
367-
units (Optional[str]): Optional units for the query. Defaults to None.
370+
Parameters:
371+
query (str): The user's input question.
372+
lang (Optional[str]): Language code for the response, if specified.
373+
units (Optional[str]): Units relevant to the query, if specified.
368374
369375
Returns:
370-
str: The spoken answer as a text response.
376+
Optional[str]: The assistant's text response, or None if no answer is generated.
371377
"""
372378
# For get_spoken_answer, we need to include existing chat history
373379
messages: List[Dict[str, str]] = self.get_chat_history()
@@ -376,8 +382,13 @@ def get_spoken_answer(self, query: str,
376382

377383
def get_messages(self, utt: str, system_prompt: Optional[str] = None) -> List[Dict[str, str]]:
378384
"""
379-
Builds a message list including the RAG solver's chat history and the current user utterance.
380-
The system prompt for the LLM is constructed dynamically in _build_llm_messages.
385+
Return the current chat history messages with the latest user utterance appended.
386+
387+
Parameters:
388+
utt (str): The current user utterance to add to the message list.
389+
390+
Returns:
391+
List of message dictionaries representing the conversation history plus the new user message.
381392
"""
382393
messages = self.get_chat_history()
383394
messages.append({"role": "user", "content": utt})

0 commit comments

Comments
 (0)