ThalamOS
a powerful Flask web application designed to enhance your storage management.
Loading...
Searching...
No Matches
ollama_manager Namespace Reference

Classes

class  SQLQuery
 

Functions

 setup_ollama ()
 
 pre_check_ollama_enabled ()
 
 check_ollama_enabled (func)
 
 get_ollama_models ()
 
pd.DataFrame storage_table_to_csv (str path)
 
 ask_question (msg)
 

Variables

Annotated ENV_PATH
 
 dotenv_path
 
tuple is_ollama_enabled
 
Annotated ollama_host
 
Annotated default_model
 
Annotated DATABASE_PATH
 
 prompt_instance
 
 fallback_prompt_instance
 
 global_Pipeline = setup_ollama()
 

Detailed Description

This module manages interactions with the Ollama model and the SQLite database.

It includes functions to set up the Ollama pipeline, check if the Ollama feature is enabled,
fetch Ollama models, convert the storage table to a CSV file, and ask questions to the Ollama model.

Classes:
    SQLQuery: A class to execute SQL queries on the SQLite database.

Functions:
    setup_ollama: Sets up the Ollama pipeline.
    pre_check_ollama_enabled: Checks if the Ollama feature is enabled.
    check_ollama_enabled: A decorator to check if Ollama is enabled before executing a function.
    get_ollama_models: Fetches a list of Ollama models from a specified API endpoint.
    storage_table_to_csv: Converts the 'storage' table from the SQLite database to a CSV file.
    ask_question: Asks a question to the Ollama model using a haystack pipeline.

Function Documentation

◆ ask_question()

ollama_manager.ask_question ( msg)
Asks a question to the Ollama model using a haystack pipeline.

Args:
    msg (str): The question to ask the Ollama model.

Returns:
    tuple: A tuple containing the type of response ("Item" or "Fallback") and the response itself.

Definition at line 253 of file ollama_manager.py.

253def ask_question(msg):
254 """
255 Asks a question to the Ollama model using a haystack pipeline.
256
257 Args:
258 msg (str): The question to ask the Ollama model.
259
260 Returns:
261 tuple: A tuple containing the type of response ("Item" or "Fallback") and the response itself.
262 """
263 table = storage_table_to_csv(DATABASE_PATH)
264 columns = table.columns.tolist()
265 result = global_Pipeline.run(
266 {
267 "prompt": {"question": msg, "columns": columns},
268 "router": {"question": msg},
269 "fallback_prompt": {"columns": columns},
270 }
271 )
272
273 if "sql_querier" in result:
274 result = result["sql_querier"]["results"][0]
275 logger.info(
276 f"llm answered with the following SQL query: {result} with type {type(result)}"
277 )
278 return "Item", result
279 if "fallback_llm" in result:
280 result = result["fallback_llm"]["replies"][0]
281 logger.info(
282 f"llm answered with the following fallback: {result} with type {type(result)}"
283 )
284 return "Fallback", result
285
286

◆ check_ollama_enabled()

ollama_manager.check_ollama_enabled ( func)
Decorator to check if Ollama is enabled before executing the function.
This decorator wraps a function and checks if Ollama is enabled by calling
the `pre_check_ollama_enabled` function. If Ollama is enabled, the wrapped
function is executed. Otherwise, a log message is generated, and the function
execution is skipped.
Args:
    func (callable): The function to be wrapped by the decorator.
Returns:
    callable: The wrapped function that includes the Ollama enabled check.

Definition at line 191 of file ollama_manager.py.

191def check_ollama_enabled(func):
192 """
193 Decorator to check if Ollama is enabled before executing the function.
194 This decorator wraps a function and checks if Ollama is enabled by calling
195 the `pre_check_ollama_enabled` function. If Ollama is enabled, the wrapped
196 function is executed. Otherwise, a log message is generated, and the function
197 execution is skipped.
198 Args:
199 func (callable): The function to be wrapped by the decorator.
200 Returns:
201 callable: The wrapped function that includes the Ollama enabled check.
202 """
203
204 @wraps(func)
205 def wrapper(*args, **kwargs):
206 if pre_check_ollama_enabled():
207 return func(*args, **kwargs)
208
209 logger.info(
210 f"Ollama is not enabled. Execution of function {func.__name__} skipped."
211 )
212 return None
213
214 return wrapper
215
216
217@check_ollama_enabled

◆ get_ollama_models()

ollama_manager.get_ollama_models ( )
Fetches a list of Ollama models from a specified API endpoint.
This function sends a GET request to the API endpoint at "http://10.45.2.60:11434/api/tags",
retrieves the JSON response, and extracts the list of models from the response data.
Returns:
    list: A list of model names (strings) retrieved from the API response.

Definition at line 218 of file ollama_manager.py.

218def get_ollama_models():
219 """
220 Fetches a list of Ollama models from a specified API endpoint.
221 This function sends a GET request to the API endpoint at "http://10.45.2.60:11434/api/tags",
222 retrieves the JSON response, and extracts the list of models from the response data.
223 Returns:
224 list: A list of model names (strings) retrieved from the API response.
225 """
226 url = f"{ollama_host}/api/tags"
227 response = requests.get(url, timeout=10)
228 data = response.json()
229 models = data.get("models", [])
230 model_list = []
231 for model in models:
232 model_list.append(model["model"])
233 return model_list
234
235

◆ pre_check_ollama_enabled()

ollama_manager.pre_check_ollama_enabled ( )
Checks if the Ollama feature is enabled.
Returns:
    bool: True if the Ollama feature is enabled, False otherwise.

Definition at line 180 of file ollama_manager.py.

180def pre_check_ollama_enabled():
181 """
182 Checks if the Ollama feature is enabled.
183 Returns:
184 bool: True if the Ollama feature is enabled, False otherwise.
185 """
186 if is_ollama_enabled:
187 return True
188 return False
189
190

◆ setup_ollama()

ollama_manager.setup_ollama ( )
Sets up the Ollama pipeline with the necessary components and connections.

This function initializes the SQLQuery component, defines routing conditions,
and sets up the ConditionalRouter, OllamaGenerator, and fallback components.
It then creates a Pipeline, adds the components to it, and connects them
according to the defined routes.

Returns:
    Pipeline: The configured Ollama pipeline.

Definition at line 129 of file ollama_manager.py.

129def setup_ollama():
130 """
131 Sets up the Ollama pipeline with the necessary components and connections.
132
133 This function initializes the SQLQuery component, defines routing conditions,
134 and sets up the ConditionalRouter, OllamaGenerator, and fallback components.
135 It then creates a Pipeline, adds the components to it, and connects them
136 according to the defined routes.
137
138 Returns:
139 Pipeline: The configured Ollama pipeline.
140 """
141 sql_query = SQLQuery(DATABASE_PATH)
142
143 routes = [
144 {
145 "condition": "{{'no_answer' not in replies[0]}}",
146 "output": "{{replies}}",
147 "output_name": "sql",
148 "output_type": List[str],
149 },
150 {
151 "condition": "{{'no_answer'|lower in replies[0]|lower}}",
152 "output": "{{question}}",
153 "output_name": "go_to_fallback",
154 "output_type": str,
155 },
156 ]
157 router = ConditionalRouter(routes)
158 llm = OllamaGenerator(model=default_model, url=ollama_host)
159 fallback_llm = OllamaGenerator(model=default_model, url=ollama_host)
160
161 conditional_sql_pipeline = Pipeline()
162 conditional_sql_pipeline.add_component("prompt", prompt_instance)
163 conditional_sql_pipeline.add_component("llm", llm)
164 conditional_sql_pipeline.add_component("router", router)
165 conditional_sql_pipeline.add_component("fallback_prompt", fallback_prompt_instance)
166 conditional_sql_pipeline.add_component("fallback_llm", fallback_llm)
167 conditional_sql_pipeline.add_component("sql_querier", sql_query)
168
169 conditional_sql_pipeline.connect("prompt", "llm")
170 conditional_sql_pipeline.connect("llm.replies", "router.replies")
171 conditional_sql_pipeline.connect("router.sql", "sql_querier.queries")
172 conditional_sql_pipeline.connect(
173 "router.go_to_fallback", "fallback_prompt.question"
174 )
175 conditional_sql_pipeline.connect("fallback_prompt", "fallback_llm")
176
177 return conditional_sql_pipeline
178
179

◆ storage_table_to_csv()

pd.DataFrame ollama_manager.storage_table_to_csv ( str path)
Converts the 'storage' table from the SQLite database to a CSV file.

Args:
    path (str): The file path to the SQLite database.

Returns:
    pd.DataFrame: A DataFrame containing the data from the 'storage' table.

Definition at line 236 of file ollama_manager.py.

236def storage_table_to_csv(path: str) -> pd.DataFrame:
237 """
238 Converts the 'storage' table from the SQLite database to a CSV file.
239
240 Args:
241 path (str): The file path to the SQLite database.
242
243 Returns:
244 pd.DataFrame: A DataFrame containing the data from the 'storage' table.
245 """
246 conn = sqlite3.connect(path)
247 table = pd.read_sql_query("SELECT * FROM storage", conn)
248 conn.close()
249 return table
250
251
252@check_ollama_enabled

Variable Documentation

◆ DATABASE_PATH

Annotated ollama_manager.DATABASE_PATH
Initial value:
1= os.path.join(
2 os.path.dirname(__file__), "data/storage.db"
3)

Definition at line 47 of file ollama_manager.py.

◆ default_model

Annotated ollama_manager.default_model
Initial value:
1= os.getenv(
2 "DEFAULT_MODEL"
3)

Definition at line 43 of file ollama_manager.py.

◆ dotenv_path

ollama_manager.dotenv_path

Definition at line 35 of file ollama_manager.py.

◆ ENV_PATH

Annotated ollama_manager.ENV_PATH
Initial value:
1= os.path.join(
2 os.path.dirname(__file__), "data/.env"
3)

Definition at line 32 of file ollama_manager.py.

◆ fallback_prompt_instance

ollama_manager.fallback_prompt_instance
Initial value:
1= PromptBuilder(
2 template=
3)

Definition at line 80 of file ollama_manager.py.

◆ global_Pipeline

ollama_manager.global_Pipeline = setup_ollama()

Definition at line 287 of file ollama_manager.py.

◆ is_ollama_enabled

tuple ollama_manager.is_ollama_enabled
Initial value:
1= (
2 os.getenv("IS_OLLAMA_ENABLED", "false").lower() == "true"
3)

Definition at line 36 of file ollama_manager.py.

◆ ollama_host

Annotated ollama_manager.ollama_host
Initial value:
1= os.getenv(
2 "OLLAMA_HOST"
3)

Definition at line 40 of file ollama_manager.py.

◆ prompt_instance

ollama_manager.prompt_instance
Initial value:
1= PromptBuilder(
2 template=
3)

Definition at line 51 of file ollama_manager.py.