2stacks Claude commited on
Commit
5c62b72
·
verified ·
1 Parent(s): 4efbaed

Add environment variable configuration and enhanced Ollama model verification

Browse files

- Add environment variables (HF_MODEL_ID, OLLAMA_BASE_URL, OLLAMA_MODEL_ID) for flexible model configuration
- Enhance is_ollama_available() to verify both service availability and model existence
- Add detailed logging to diagnose Ollama connection and model availability issues
- Update README.md with configuration documentation and Docker environment variable examples
- Add python-dotenv dependency for environment variable management

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (3) hide show
  1. README.md +26 -2
  2. app.py +63 -13
  3. requirements.txt +5 -3
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: ⚡
4
  colorFrom: pink
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.23.1
8
  app_file: app.py
9
  pinned: false
10
  tags:
@@ -31,6 +31,27 @@ python -m venv env
31
  source env/bin/activate
32
  ```
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  ## Install dependencies and run
35
 
36
  ```shell
@@ -43,6 +64,9 @@ python app.py
43
  ```shell
44
  docker run -it -p 7860:7860 \
45
  --platform=linux/amd64 \
46
- --environment HF_TOKEN="YOUR_VALUE_HERE" \
 
 
 
47
  registry.hf.space/2stacks-first-agent-template:latest python app.py
48
  ```
 
4
  colorFrom: pink
5
  colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
10
  tags:
 
31
  source env/bin/activate
32
  ```
33
 
34
+ ## Configuration (Optional)
35
+
36
+ The application uses environment variables for model configuration. Create a `.env` file in the project root to customize settings:
37
+
38
+ ```shell
39
+ # Ollama configuration (for local models)
40
+ OLLAMA_BASE_URL=http://localhost:11434
41
+ OLLAMA_MODEL_ID=qwen2.5-coder:32b
42
+
43
+ # HuggingFace configuration (fallback when Ollama is unavailable)
44
+ HF_MODEL_ID=Qwen/Qwen2.5-Coder-32B-Instruct
45
+ ```
46
+
47
+ **Environment Variables:**
48
+
49
+ - `OLLAMA_BASE_URL`: URL for your Ollama service (default: `http://localhost:11434`)
50
+ - `OLLAMA_MODEL_ID`: Model name in Ollama (default: `qwen2.5-coder:32b`)
51
+ - `HF_MODEL_ID`: HuggingFace model to use as fallback (default: `Qwen/Qwen2.5-Coder-32B-Instruct`)
52
+
53
+ The app automatically checks if Ollama is available with the specified model. If not, it falls back to HuggingFace.
54
+
55
  ## Install dependencies and run
56
 
57
  ```shell
 
64
  ```shell
65
  docker run -it -p 7860:7860 \
66
  --platform=linux/amd64 \
67
+ -e HF_TOKEN="YOUR_VALUE_HERE" \
68
+ -e OLLAMA_BASE_URL="http://localhost:11434" \
69
+ -e OLLAMA_MODEL_ID="qwen2.5-coder:32b" \
70
+ -e HF_MODEL_ID="Qwen/Qwen2.5-Coder-32B-Instruct" \
71
  registry.hf.space/2stacks-first-agent-template:latest python app.py
72
  ```
app.py CHANGED
@@ -1,10 +1,49 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, tool
2
- #import requests
 
3
  import pytz
4
  import yaml
5
- from datetime import datetime
6
 
 
7
  from Gradio_UI import GradioUI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  @tool
10
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -49,16 +88,27 @@ search_tool = DuckDuckGoSearchTool(max_results=5, rate_limit=2.0)
49
  # Instantiate the FinalAnswerTool
50
  final_answer = FinalAnswerTool()
51
 
52
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
53
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
54
-
55
- model = InferenceClientModel(
56
- max_tokens=2096,
57
- temperature=0.5,
58
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # it is possible that this model may be overloaded
59
- #model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
60
- custom_role_conversions=None,
61
- )
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  with open("prompts.yaml", 'r') as stream:
64
  prompt_templates = yaml.safe_load(stream)
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, LiteLLMModel, tool
2
+ import os
3
+ import requests
4
  import pytz
5
  import yaml
 
6
 
7
+ from datetime import datetime
8
  from Gradio_UI import GradioUI
9
+ from dotenv import load_dotenv
10
+
11
+ # Load environment variables from .env file
12
+ load_dotenv()
13
+
14
+ # Configuration
15
+ HF_MODEL_ID = os.getenv("HF_MODEL_ID", "Qwen/Qwen2.5-Coder-32B-Instruct")
16
+ OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
17
+ OLLAMA_MODEL_ID = os.getenv("OLLAMA_MODEL_ID", "qwen2.5-coder:32b")
18
+
19
+ def is_ollama_available(base_url=None, timeout=2):
20
+ """Check if Ollama service is running and the specified model exists."""
21
+ if base_url is None:
22
+ base_url = OLLAMA_BASE_URL
23
+ try:
24
+ response = requests.get(f"{base_url}/api/tags", timeout=timeout)
25
+ if response.status_code != 200:
26
+ print(f"Ollama service check failed: HTTP {response.status_code} from {base_url}/api/tags")
27
+ return False
28
+
29
+ # Parse the response to get available models
30
+ data = response.json()
31
+ available_models = [model.get('name', '') for model in data.get('models', [])]
32
+
33
+ # Check if the model exists in available models
34
+ if OLLAMA_MODEL_ID not in available_models:
35
+ print(f"Model '{OLLAMA_MODEL_ID}' not found in Ollama.")
36
+ print(f"Available models: {', '.join(available_models) if available_models else 'None'}")
37
+ return False
38
+
39
+ print(f"Ollama service is available and model '{OLLAMA_MODEL_ID}' found.")
40
+ return True
41
+ except (requests.RequestException, ConnectionError) as e:
42
+ print(f"Failed to connect to Ollama service at {base_url}: {type(e).__name__}: {e}")
43
+ return False
44
+ except (ValueError, KeyError) as e:
45
+ print(f"Failed to parse Ollama API response: {type(e).__name__}: {e}")
46
+ return False
47
 
48
  @tool
49
  def get_current_time_in_timezone(timezone: str) -> str:
 
88
  # Instantiate the FinalAnswerTool
89
  final_answer = FinalAnswerTool()
90
 
91
+ # Check if Ollama is available and configure the model accordingly
92
+ if is_ollama_available():
93
+ print("Ollama detected - using LiteLLMModel with local Ollama instance")
94
+ model = LiteLLMModel(
95
+ model_id=f"ollama_chat/{OLLAMA_MODEL_ID}", # Adjust model name based on what you have in Ollama
96
+ api_base=OLLAMA_BASE_URL,
97
+ api_key="ollama",
98
+ num_ctx=8192, # Important: Ollama's default 2048 may cause failures
99
+ max_tokens=2096,
100
+ temperature=0.5,
101
+ )
102
+ else:
103
+ print("Ollama not available - falling back to InferenceClientModel")
104
+ # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
105
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
106
+ model = InferenceClientModel(
107
+ max_tokens=2096,
108
+ temperature=0.5,
109
+ model_id=HF_MODEL_ID, # it is possible that this model may be overloaded
110
+ custom_role_conversions=None,
111
+ )
112
 
113
  with open("prompts.yaml", 'r') as stream:
114
  prompt_templates = yaml.safe_load(stream)
requirements.txt CHANGED
@@ -1,6 +1,8 @@
 
 
1
  markdownify
 
 
2
  smolagents
3
- #requests
4
- duckduckgo_search
5
- ddgs
6
  smolagents[gradio]
 
 
1
+ ddgs
2
+ duckduckgo_search
3
  markdownify
4
+ python-dotenv
5
+ requests
6
  smolagents
 
 
 
7
  smolagents[gradio]
8
+ smolagents[litellm]