Spaces:
Sleeping
Sleeping
auth
Browse filesFiles changed (6)
- .gitignore+2-1
- config.py+56-6
- evaluation.py+171-43
- hf_agent.py+204-8
- local_config.json+1-1
- test_model_strategies.pyAdded+155
3 unmodified lines45673 unmodified lines.cursorrules/.cursor/models/3 unmodified lines456783 unmodified lines.cursorrules/.cursor/models/example.ipynb
7 unmodified lines8910111213141516 unmodified lines32333435363732 unmodified lines707172737475764 unmodified lines8182838485868758 unmodified lines14614714814915015115215315415515615715815916016119 unmodified lines1811821831841851861871881891907 unmodified lines# --- Smolagents Model Configuration ---MODEL_CONFIG = {# Model selection strategy: "local", "remote", or "auto""model_strategy": "remote", # auto will try local first, then remote# Local model paths (set these to your downloaded model directories)"local_models": {16 unmodified lines"embedding_model": "./models/all-MiniLM-L6-v2", # Smaller embedding model},# Primary LLM for the CodeAgent - use a strong reasoning model"llm_model": "meta-llama/Llama-3.3-70B-Instruct", # Will be overridden by model selection"fallback_model": "HuggingFaceH4/zephyr-7b-beta", # Will be overridden by model selection32 unmodified lines# --- System Prompts for Smolagents ---SYSTEM_PROMPTS = {"code_agent": ("You are a general AI assistant tasked with solving complex questions accurately for GAIA evaluation.\n""Use tools and write Python code to gather information, perform calculations, or process data.\n""Follow a Thought-Action-Observation cycle:\n""- Thought: Plan the steps to solve the task\n"4 unmodified lines),"evaluation": ("You are participating in the GAIA benchmark evaluation. ""Provide accurate, comprehensive, and concise answers. ""Use available tools to gather current information or perform calculations. ""Focus on precision and exactness in your responses."58 unmodified lines# Use local modelsconfig.update(config["local_models"])config["use_local"] = Trueprint("Using local models")elif strategy == "local_light" or (strategy == "auto" and _check_local_light_models_available()):# Use lighter local modelsconfig.update(config["local_light_models"])config["use_local"] = Trueprint("Using local light models")else:# Use remote modelsconfig.update(config["remote_models"])config["use_local"] = Falseprint("Using remote models")return config19 unmodified linesreturn Truedef set_model_strategy(strategy):"""Set the model strategy: 'local', 'local_light', 'remote', or 'auto'"""MODEL_CONFIG["model_strategy"] = strategysave_config()def set_local_model_paths(llm_path=None, fallback_path=None, embedding_path=None):"""Set custom paths for local models"""if llm_path:7 unmodified lines8910111213141516 unmodified lines323334353637383940414243444546474849505152535432 unmodified lines878889909192934 unmodified lines989910010110210310458 unmodified lines16316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372382392407 unmodified lines# --- Smolagents Model Configuration ---MODEL_CONFIG = {# Model selection strategy: "local", "remote", "ollama", "openai", or "auto""model_strategy": "ollama", # auto will try local first, then remote# Local model paths (set these to your downloaded model directories)"local_models": {16 unmodified lines"embedding_model": "./models/all-MiniLM-L6-v2", # Smaller embedding model},# Ollama models (local inference server)"ollama_models": {"llm_model": "phi4:latest", # Main reasoning model"fallback_model": "gemma3:12b", # Same model as fallback"embedding_model": "nomic-embed-text", # Ollama embedding model"base_url": "http://localhost:11434", # Default Ollama server URL},# OpenAI models (for specific use cases)"openai_models": {"llm_model": "gpt-4o-mini", # Main model for text analysis"fallback_model": "gpt-4o-mini", # Same model as fallback"embedding_model": "text-embedding-3-small", # Small embedding model"observation_model": "gpt-4o-mini", # For observation analysis"api_key_env": "OPENAI_API_KEY", # Environment variable for API key},# Primary LLM for the CodeAgent - use a strong reasoning model"llm_model": "meta-llama/Llama-3.3-70B-Instruct", # Will be overridden by model selection"fallback_model": "HuggingFaceH4/zephyr-7b-beta", # Will be overridden by model selection32 unmodified lines# --- System Prompts for Smolagents ---SYSTEM_PROMPTS = {"code_agent": ("You are a general AI assistant tasked with solving complex questions accurately.\n""Use tools and write Python code to gather information, perform calculations, or process data.\n""Follow a Thought-Action-Observation cycle:\n""- Thought: Plan the steps to solve the task\n"4 unmodified lines),"evaluation": ("You are answering tricky and hard questions. ""Provide accurate, comprehensive, and concise answers. ""Use available tools to gather current information or perform calculations. ""Focus on precision and exactness in your responses."58 unmodified lines# Use local modelsconfig.update(config["local_models"])config["use_local"] = Trueconfig["model_type"] = "local"print("Using local models")elif strategy == "local_light" or (strategy == "auto" and _check_local_light_models_available()):# Use lighter local modelsconfig.update(config["local_light_models"])config["use_local"] = Trueconfig["model_type"] = "local_light"print("Using local light models")elif strategy == "ollama":# Use Ollama modelsconfig.update(config["ollama_models"])config["use_local"] = Falseconfig["model_type"] = "ollama"print("Using Ollama models")elif strategy == "openai":# Use OpenAI modelsconfig.update(config["openai_models"])config["use_local"] = Falseconfig["model_type"] = "openai"print("Using OpenAI models")else:# Use remote models (HuggingFace)config.update(config["remote_models"])config["use_local"] = Falseconfig["model_type"] = "remote"print("Using remote models")return config19 unmodified linesreturn Truedef set_model_strategy(strategy):"""Set the model strategy: 'local', 'local_light', 'remote', 'ollama', 'openai', or 'auto'"""valid_strategies = ["local", "local_light", "remote", "ollama", "openai", "auto"]if strategy not in valid_strategies:raise ValueError(f"Invalid strategy. Must be one of: {valid_strategies}")MODEL_CONFIG["model_strategy"] = strategysave_config()def set_ollama_config(base_url="http://localhost:11434", llm_model="llama3.1:8b", embedding_model="nomic-embed-text"):"""Set Ollama configuration"""MODEL_CONFIG["ollama_models"]["base_url"] = base_urlMODEL_CONFIG["ollama_models"]["llm_model"] = llm_modelMODEL_CONFIG["ollama_models"]["embedding_model"] = embedding_modelsave_config()def set_openai_config(api_key_env="OPENAI_API_KEY", llm_model="gpt-4o-mini", embedding_model="text-embedding-3-small"):"""Set OpenAI configuration"""MODEL_CONFIG["openai_models"]["api_key_env"] = api_key_envMODEL_CONFIG["openai_models"]["llm_model"] = llm_modelMODEL_CONFIG["openai_models"]["embedding_model"] = embedding_modelsave_config()def set_local_model_paths(llm_path=None, fallback_path=None, embedding_path=None):"""Set custom paths for local models"""if llm_path:
368 unmodified lines3693703713723733743753 unmodified lines37938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943049 unmodified lines4804814824834844856 unmodified lines49249349449549649717 unmodified lines515516517518519520368 unmodified lines# Create a profile-like object from request dataclass RequestProfile:def __init__(self, username):self.username = username or "authenticated_user"profile = RequestProfile(getattr(request, 'username', None))return run_evaluation(profile)3 unmodified lines# Use dummy profile for local developmenteval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table])with gr.Tab("Local Models"):gr.Markdown("""## Local Model SupportRun the evaluation with models downloaded locally on your machine for:- **Privacy**: No data sent to external APIs- **Speed**: Faster inference (with proper hardware)- **Offline**: Works without internet connection- **Control**: Full control over model versions""")with gr.Row():with gr.Column():gr.Markdown("### Quick Setup")model_size = gr.Radio(choices=["light", "medium", "full"],value="light",label="Model Size",info="Light: ~20GB, Medium: ~18GB, Full: ~155GB")hf_token = gr.Textbox(label="HuggingFace Token (optional)",placeholder="hf_...",type="password",info="Required for some gated models")download_btn = gr.Button("Download Models", variant="primary")with gr.Column():gr.Markdown("### Manual Setup")llm_path = gr.Textbox(label="LLM Model Path",placeholder="./models/Llama-3.2-3B-Instruct",info="Path to your local LLM")fallback_path = gr.Textbox(label="Fallback Model Path",placeholder="./models/Qwen2.5-7B-Instruct",info="Path to your fallback model")embedding_path = gr.Textbox(label="Embedding Model Path",placeholder="./models/all-MiniLM-L6-v2",info="Path to your embedding model")set_paths_btn = gr.Button("Set Model Paths", variant="secondary")download_status = gr.Textbox(label="Status",49 unmodified linesexcept Exception as e:return f"β Error setting model paths: {str(e)}"download_btn.click(download_models_interface,inputs=[model_size, hf_token],6 unmodified linesoutputs=download_status)gr.Markdown("""### Command Line Usage17 unmodified lines- **Memory**: 8GB+ RAM for light models, 16GB+ for medium, 64GB+ for full- **Storage**: 20GB+ free space for light models- **GPU**: Optional but recommended for faster inference""")with gr.Tab("About Smolagents"):368 unmodified lines3693703713723733743753 unmodified lines37938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845856 unmodified lines59259359459559659759859960060160260360460560660760860961061161261361461517 unmodified lines633634635636637638639640641642643644645646647648368 unmodified lines# Create a profile-like object from request dataclass RequestProfile:def __init__(self, username):self.username = username or "tjrtm"profile = RequestProfile(getattr(request, 'username', None))return run_evaluation(profile)3 unmodified lines# Use dummy profile for local developmenteval_btn.click(lambda: run_evaluation(DummyProfile()), outputs=[status_output, results_table])with gr.Tab("Model Configuration"):gr.Markdown("""## Model Strategy SelectionChoose your preferred model strategy for the GAIA evaluation:""")strategy_selector = gr.Radio(choices=[("Local Models", "local"),("Remote (HuggingFace)", "remote"),("Ollama Server", "ollama"),("OpenAI API", "openai"),("Auto Select", "auto")],value="local",label="Model Strategy",info="Select which type of models to use for inference")with gr.Tab("Local Models"):gr.Markdown("""### Local Model SupportRun with models downloaded locally for privacy and offline usage:""")with gr.Row():with gr.Column():gr.Markdown("### Quick Setup")model_size = gr.Radio(choices=["light", "medium", "full"],value="light",label="Model Size",info="Light: ~20GB, Medium: ~18GB, Full: ~155GB")hf_token = gr.Textbox(label="HuggingFace Token (optional)",placeholder="hf_...",type="password",info="Required for some gated models")download_btn = gr.Button("Download Models", variant="primary")with gr.Column():gr.Markdown("### Manual Setup")llm_path = gr.Textbox(label="LLM Model Path",placeholder="./models/Llama-3.2-3B-Instruct",info="Path to your local LLM")fallback_path = gr.Textbox(label="Fallback Model Path",placeholder="./models/Qwen2.5-7B-Instruct",info="Path to your fallback model")embedding_path = gr.Textbox(label="Embedding Model Path",placeholder="./models/all-MiniLM-L6-v2",info="Path to your embedding model")set_paths_btn = gr.Button("Set Model Paths", variant="secondary")with gr.Tab("Ollama"):gr.Markdown("""### Ollama ConfigurationUse local Ollama server for privacy and control:""")ollama_url = gr.Textbox(label="Ollama Server URL",value="http://localhost:11434",info="URL of your Ollama server")ollama_model = gr.Textbox(label="Ollama Model",value="llama3.1:8b",info="Model name in Ollama (e.g., llama3.1:8b, mistral:7b)")ollama_embedding = gr.Textbox(label="Embedding Model",value="nomic-embed-text",info="Embedding model for RAG")set_ollama_btn = gr.Button("Configure Ollama", variant="primary")with gr.Tab("OpenAI"):gr.Markdown("""### OpenAI ConfigurationUse OpenAI API for high-quality responses (requires API key):""")openai_key = gr.Textbox(label="OpenAI API Key",type="password",placeholder="sk-...",info="Your OpenAI API key")openai_model = gr.Textbox(label="OpenAI Model",value="gpt-4o-mini",info="OpenAI model to use (gpt-4o-mini recommended)")openai_embedding = gr.Textbox(label="Embedding Model",value="text-embedding-3-small",info="OpenAI embedding model")set_openai_btn = gr.Button("Configure OpenAI", variant="primary")download_status = gr.Textbox(label="Status",49 unmodified linesexcept Exception as e:return f"β Error setting model paths: {str(e)}"def set_strategy_interface(strategy):try:from config import set_model_strategyset_model_strategy(strategy)return f"β Model strategy set to: {strategy}\n\nRestart the application to apply changes."except Exception as e:return f"β Error setting strategy: {str(e)}"def set_ollama_interface(url, model, embedding):try:from config import set_ollama_config, set_model_strategyimport osset_ollama_config(base_url=url, llm_model=model, embedding_model=embedding)set_model_strategy("ollama")return f"β Ollama configuration updated:\nServer: {url}\nModel: {model}\nEmbedding: {embedding}\n\nRestart the application to use Ollama."except Exception as e:return f"β Error configuring Ollama: {str(e)}"def set_openai_interface(api_key, model, embedding):try:from config import set_openai_config, set_model_strategyimport osif api_key:os.environ["OPENAI_API_KEY"] = api_keyset_openai_config(llm_model=model, embedding_model=embedding)set_model_strategy("openai")return f"β OpenAI configuration updated:\nModel: {model}\nEmbedding: {embedding}\n\nAPI key {'set' if api_key else 'not provided'}\n\nRestart the application to use OpenAI."except Exception as e:return f"β Error configuring OpenAI: {str(e)}"download_btn.click(download_models_interface,inputs=[model_size, hf_token],6 unmodified linesoutputs=download_status)strategy_selector.change(set_strategy_interface,inputs=[strategy_selector],outputs=download_status)set_ollama_btn.click(set_ollama_interface,inputs=[ollama_url, ollama_model, ollama_embedding],outputs=download_status)set_openai_btn.click(set_openai_interface,inputs=[openai_key, openai_model, openai_embedding],outputs=download_status)gr.Markdown("""### Command Line Usage17 unmodified lines- **Memory**: 8GB+ RAM for light models, 16GB+ for medium, 64GB+ for full- **Storage**: 20GB+ free space for light models- **GPU**: Optional but recommended for faster inference### Requirements for Ollama- **Ollama installed**: Download from [ollama.ai](https://ollama.ai)- **Models pulled**: Run `ollama pull llama3.1:8b` or your preferred model- **Server running**: Ollama runs on `http://localhost:11434` by default### Requirements for OpenAI- **API Key**: Get from [platform.openai.com](https://platform.openai.com)- **Credits**: Ensure you have sufficient API credits- **Model access**: gpt-4o-mini recommended for cost-effectiveness""")with gr.Tab("About Smolagents"):
19 unmodified lines202122232425184 unmodified lines210211212213214215190 unmodified lines4064074084094104114124134144 unmodified lines4194204214224234244254264 unmodified lines4314324334344354364376 unmodified lines44444544644744844962 unmodified lines5125135145155165175185195205215225235245255266 unmodified lines53353453553653753819 unmodified linesfrom smolagents import CodeAgent, ToolCallingAgent, tool, InferenceClientModel, LocalPythonExecutorfrom smolagents.default_tools import FinalAnswerToolfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.docstore.document import Document as LangchainDocumentfrom langchain_community.vectorstores import FAISS184 unmodified lines# This would need to be implemented based on the model's output formatreturn []class SimpleConversationAgent:"""Simple agent that uses conversation for tool calling when CodeAgent isn't suitable"""190 unmodified linesself._create_agent()def _initialize_model(self):"""Initialize either local or remote model based on configuration"""try:if self.model_config.get("use_local", False):# Use local modeldevice_config = get_device_config()model_path = self.model_config["llm_model"]4 unmodified linesraise FileNotFoundError(f"Local model not found: {model_path}")return LocalModel(model_path, device_config)else:# Use remote model with InferenceClientModelreturn InferenceClientModel(model_id=self.model_config["llm_model"],token=get_hf_token()4 unmodified lines# Try fallback modeltry:if self.model_config.get("use_local", False):device_config = get_device_config()fallback_path = self.model_config["fallback_model"]6 unmodified linesmodel_id=self.model_config["fallback_model"],token=get_hf_token())else:return InferenceClientModel(model_id=self.model_config["fallback_model"],62 unmodified linesif self.vectordb:tools.append(rag_search_tool)# Create a simple agent based on model capabilitiesif self.model_config.get("use_local", False):# For local models like DialoGPT, create a simple conversation-based agentself.agent = SimpleConversationAgent(tools=tools,model=self.llm_engine)else:# For remote models, use CodeAgent for better reasoningtry:self.agent = CodeAgent(tools=tools,6 unmodified linestools=tools,model=self.llm_engine)def __call__(self, question, files=None):"""Main interface for the agent"""19 unmodified lines20212223242526184 unmodified lines211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367190 unmodified lines5585595605615625635645655665675684 unmodified lines5735745755765775785795805815825835845855865875885895905915925935945955964 unmodified lines6016026036046056066076086096 unmodified lines61661761861962062162262362462562662762862963063163263363463563663762 unmodified lines7007017027037047057067077087097107117127137147157166 unmodified lines72372472572672772872973073173273373419 unmodified linesfrom smolagents import CodeAgent, ToolCallingAgent, tool, InferenceClientModel, LocalPythonExecutorfrom smolagents.default_tools import FinalAnswerToolimport openaifrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.docstore.document import Document as LangchainDocumentfrom langchain_community.vectorstores import FAISS184 unmodified lines# This would need to be implemented based on the model's output formatreturn []class OllamaModel:"""Wrapper for Ollama models to be compatible with smolagents Model interface"""def __init__(self, model_id, base_url="http://localhost:11434"):self.model_id = model_idself.base_url = base_urlself.last_input_token_count = 0self.last_output_token_count = 0print(f"Initialized Ollama model: {model_id} at {base_url}")# Test connectiontry:import requestsresponse = requests.get(f"{base_url}/api/tags", timeout=5)if response.status_code == 200:print("β Ollama server connection successful")else:print("β Ollama server connection failed")except Exception as e:print(f"β Could not connect to Ollama server: {e}")def __call__(self, messages, **kwargs):"""Main interface method expected by smolagents"""return self.generate_response(messages, **kwargs)def generate_response(self, messages, max_new_tokens=512, temperature=0.7, **kwargs):"""Generate response using Ollama API"""try:import requests# Convert messages to Ollama formatif isinstance(messages, list) and messages and isinstance(messages[0], dict):# Use the last user message as promptprompt = ""for msg in messages:role = msg.get("role", "user")content = msg.get("content", "")if role == "user":prompt = content # Use the last user messageelse:prompt = str(messages)# Prepare Ollama API requestpayload = {"model": self.model_id,"prompt": prompt,"stream": False,"options": {"temperature": temperature,"num_predict": max_new_tokens}}# Make request to Ollamaresponse = requests.post(f"{self.base_url}/api/generate",json=payload,timeout=60)if response.status_code == 200:result = response.json()generated_text = result.get("response", "")# Estimate token counts (rough approximation)self.last_input_token_count = len(prompt.split())self.last_output_token_count = len(generated_text.split())return ChatMessage(generated_text, self.last_input_token_count, self.last_output_token_count)else:error_msg = f"Ollama API error: {response.status_code}"return ChatMessage(error_msg, 0, 0)except Exception as e:print(f"Error in Ollama generation: {e}")return ChatMessage(f"Ollama error: {str(e)}", 0, 0)def generate(self, messages, **kwargs):"""Generate method expected by smolagents"""return self.generate_response(messages, **kwargs)class OpenAIModel:"""Wrapper for OpenAI models to be compatible with smolagents Model interface"""def __init__(self, model_id, api_key=None):self.model_id = model_idself.last_input_token_count = 0self.last_output_token_count = 0# Set up OpenAI clientif api_key:openai.api_key = api_keyelse:# Try to get from environmentapi_key = os.getenv("OPENAI_API_KEY")if not api_key:raise ValueError("OpenAI API key not found. Set OPENAI_API_KEY environment variable.")openai.api_key = api_keyself.client = openai.OpenAI(api_key=api_key)print(f"Initialized OpenAI model: {model_id}")def __call__(self, messages, **kwargs):"""Main interface method expected by smolagents"""return self.generate_response(messages, **kwargs)def generate_response(self, messages, max_new_tokens=512, temperature=0.7, **kwargs):"""Generate response using OpenAI API"""try:# Convert messages to OpenAI formatif isinstance(messages, list) and messages and isinstance(messages[0], dict):# Already in correct formatopenai_messages = messageselif isinstance(messages, str):# Convert string to message formatopenai_messages = [{"role": "user", "content": messages}]else:# Convert other formatsopenai_messages = [{"role": "user", "content": str(messages)}]# Make request to OpenAIresponse = self.client.chat.completions.create(model=self.model_id,messages=openai_messages,max_tokens=max_new_tokens,temperature=temperature)generated_text = response.choices[0].message.content# Get token usage if availableif hasattr(response, 'usage') and response.usage:usage = response.usageself.last_input_token_count = usage.prompt_tokensself.last_output_token_count = usage.completion_tokenselse:# Estimate token counts if usage not availableself.last_input_token_count = len(str(openai_messages).split())self.last_output_token_count = len(generated_text.split())return ChatMessage(generated_text, self.last_input_token_count, self.last_output_token_count)except Exception as e:print(f"Error in OpenAI generation: {e}")return ChatMessage(f"OpenAI error: {str(e)}", 0, 0)def generate(self, messages, **kwargs):"""Generate method expected by smolagents"""return self.generate_response(messages, **kwargs)class SimpleConversationAgent:"""Simple agent that uses conversation for tool calling when CodeAgent isn't suitable"""190 unmodified linesself._create_agent()def _initialize_model(self):"""Initialize model based on configuration (local, remote, ollama, or openai)"""try:model_type = self.model_config.get("model_type", "remote")if model_type in ["local", "local_light"]:# Use local modeldevice_config = get_device_config()model_path = self.model_config["llm_model"]4 unmodified linesraise FileNotFoundError(f"Local model not found: {model_path}")return LocalModel(model_path, device_config)elif model_type == "ollama":# Use Ollama modelreturn OllamaModel(model_id=self.model_config["llm_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"))elif model_type == "openai":# Use OpenAI modelapi_key = os.getenv(self.model_config.get("api_key_env", "OPENAI_API_KEY"))return OpenAIModel(model_id=self.model_config["llm_model"],api_key=api_key)else:# Use remote model with InferenceClientModel (HuggingFace)return InferenceClientModel(model_id=self.model_config["llm_model"],token=get_hf_token()4 unmodified lines# Try fallback modeltry:model_type = self.model_config.get("model_type", "remote")if model_type in ["local", "local_light"]:device_config = get_device_config()fallback_path = self.model_config["fallback_model"]6 unmodified linesmodel_id=self.model_config["fallback_model"],token=get_hf_token())elif model_type == "ollama":print(f"Using Ollama fallback model: {self.model_config['fallback_model']}")return OllamaModel(model_id=self.model_config["fallback_model"],base_url=self.model_config.get("base_url", "http://localhost:11434"))elif model_type == "openai":print(f"Using OpenAI fallback model: {self.model_config['fallback_model']}")api_key = os.getenv(self.model_config.get("api_key_env", "OPENAI_API_KEY"))return OpenAIModel(model_id=self.model_config["fallback_model"],api_key=api_key)else:return InferenceClientModel(model_id=self.model_config["fallback_model"],62 unmodified linesif self.vectordb:tools.append(rag_search_tool)# Create agent based on model capabilitiesmodel_type = self.model_config.get("model_type", "remote")if model_type in ["local", "local_light"]:# For local models like DialoGPT, create a simple conversation-based agentself.agent = SimpleConversationAgent(tools=tools,model=self.llm_engine)elif model_type in ["ollama", "openai", "remote"]:# For Ollama, OpenAI, and remote models, use CodeAgent for better reasoningtry:self.agent = CodeAgent(tools=tools,6 unmodified linestools=tools,model=self.llm_engine)else:# Fallback to simple agentself.agent = SimpleConversationAgent(tools=tools,model=self.llm_engine)def __call__(self, question, files=None):"""Main interface for the agent"""
12345{"model_strategy": "local","local_models": {"llm_model": "models/DialoGPT-medium","fallback_model": "models/Qwen2.5-7B-Instruct",12345{"model_strategy": "openai","local_models": {"llm_model": "models/DialoGPT-medium","fallback_model": "models/Qwen2.5-7B-Instruct",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155#!/usr/bin/env python3"""Test script for new model strategies: Ollama and OpenAI"""
from config import set_model_strategy, get_model_config, set_ollama_config, set_openai_configimport os
def test_strategies(): """Test all available model strategies""" print("Testing Model Strategies") print("=" * 40) strategies = ["local", "remote", "ollama", "openai"] for strategy in strategies: print(f"\nπ§ͺ Testing {strategy.upper()} strategy...") try: # Set the strategy set_model_strategy(strategy) # Get the config config = get_model_config() print(f"β Strategy: {config.get('model_type', 'unknown')}") print(f"β LLM Model: {config.get('llm_model', 'unknown')}") print(f"β Embedding Model: {config.get('embedding_model', 'unknown')}") if strategy == "ollama": print(f"β Base URL: {config.get('base_url', 'unknown')}") elif strategy == "openai": print(f"β API Key Env: {config.get('api_key_env', 'unknown')}") except Exception as e: print(f"β Error with {strategy}: {e}")
def test_agent_initialization(): """Test agent initialization with different strategies""" print("\n" + "=" * 40) print("Testing Agent Initialization") print("=" * 40) # Test strategies that don't require external dependencies test_strategies = ["remote", "local"] # Add ollama if it might be available try: import requests response = requests.get("http://localhost:11434/api/tags", timeout=2) if response.status_code == 200: test_strategies.append("ollama") print("β Ollama server detected") except: print("β Ollama server not available") # Add openai if API key is available if os.getenv("OPENAI_API_KEY"): test_strategies.append("openai") print("β OpenAI API key detected") else: print("β OpenAI API key not found") for strategy in test_strategies: print(f"\nπ€ Testing {strategy.upper()} agent initialization...") try: set_model_strategy(strategy) # Import and test basic initialization from hf_agent import SmolagentsGAIAAgent agent = SmolagentsGAIAAgent() # Test a simple question result = agent("What is 2+2?") print(f"β Agent response: {result}") except Exception as e: print(f"β Error with {strategy} agent: {e}")
def show_configuration_examples(): """Show how to configure different strategies""" print("\n" + "=" * 40) print("Configuration Examples") print("=" * 40) print("""π How to use the new strategies:
1. **Ollama Strategy:** ```python from config import set_model_strategy, set_ollama_config # Configure Ollama set_ollama_config( base_url="http://localhost:11434", llm_model="llama3.1:8b", embedding_model="nomic-embed-text" ) # Set strategy set_model_strategy("ollama") ```
2. **OpenAI Strategy:** ```python from config import set_model_strategy, set_openai_config import os # Set your API key os.environ["OPENAI_API_KEY"] = "your-api-key-here" # Configure OpenAI set_openai_config( llm_model="gpt-4o-mini", embedding_model="text-embedding-3-small" ) # Set strategy set_model_strategy("openai") ```
3. **Environment Variables:** ```bash # For OpenAI export OPENAI_API_KEY="your-openai-api-key" # Then run your agent python evaluation.py ```
4. **Command Line Testing:** ```bash # Test with different strategies python -c "from config import set_model_strategy; set_model_strategy('ollama')" python -c "from hf_agent import SmolagentsGAIAAgent; agent = SmolagentsGAIAAgent(); print(agent('Hello'))" ``` """)
if __name__ == "__main__": test_strategies() test_agent_initialization() show_configuration_examples() print("\n" + "=" * 40) print("β
Model strategy testing completed!") print("\nUse set_model_strategy('strategy_name') to switch between:") print("- 'local': Local models with transformers") print("- 'remote': HuggingFace Inference API") print("- 'ollama': Local Ollama server") print("- 'openai': OpenAI API") print("- 'auto': Automatic selection") .gitignore+2-1
config.py+56-6
evaluation.py+171-43
hf_agent.py+204-8
local_config.json+1-1
test_model_strategies.pyAdded+155