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 190 of file ollama_manager.py.

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

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

◆ 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 179 of file ollama_manager.py.

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

◆ 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 128 of file ollama_manager.py.

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

◆ 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 235 of file ollama_manager.py.

235def storage_table_to_csv(path: str) -> pd.DataFrame:
236 """
237 Converts the 'storage' table from the SQLite database to a CSV file.
238
239 Args:
240 path (str): The file path to the SQLite database.
241
242 Returns:
243 pd.DataFrame: A DataFrame containing the data from the 'storage' table.
244 """
245 abs_path = os.path.abspath(path)
246 engine = create_engine(f"sqlite:///{abs_path}")
247 with engine.connect() as conn:
248 table = pd.read_sql_query("SELECT * FROM storage", conn)
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.