import json import os import re from ontology_architect.agents.base_agent import BaseAgent from ontology_architect.models import OntologyArchitectAction, OntologyArchitectObservation class LLMAgent(BaseAgent): """An agent that uses an LLM to generate the theory DSL.""" def __init__(self, name: str = "llm_agent"): super().__init__(name) # Template for OpenAI-compatible APIs (OpenAI, Groq, local vLLM, etc.) self.api_key = os.environ.get("LLM_API_KEY", "") self.api_base = os.environ.get("LLM_API_BASE", "https://api.openai.com/v1") self.model = os.environ.get("LLM_MODEL", "gpt-4o") def _query_llm(self, prompt: str) -> str: """Query the LLM endpoint. Needs the requests library.""" try: import requests except ImportError: return "Error: requests library not installed. Cannot query LLM." if not self.api_key: # Return a fallback theory if no key is provided to avoid crashing the grader return json.dumps({ "dsl_version": 1, "state": ["A"], "dynamics": {"A": {"const": 0.0}}, "observations": {"pressure": {"var": "A"}}, "noise": 0.1 }) headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } payload = { "model": self.model, "messages": [ {"role": "system", "content": "You are a scientific discovery agent. Output ONLY valid JSON containing the Theory DSL."}, {"role": "user", "content": prompt} ], "temperature": 0.2 } try: response = requests.post(f"{self.api_base}/chat/completions", headers=headers, json=payload, timeout=30) response.raise_for_status() content = response.json()["choices"][0]["message"]["content"] return content except Exception as e: print(f"[LLMAgent Error] {e}") return "{}" def act(self, observation: OntologyArchitectObservation) -> OntologyArchitectAction: prompt = f""" OBSERVATION: {observation.text} SENSOR LOG: {observation.sensor_log} PEER REVIEW (Past feedback): {observation.peer_review} Please provide a JSON DSL theory that explains this data. """ response_text = self._query_llm(prompt) # Try to extract JSON from markdown if necessary match = re.search(r'```json\n(.*?)\n```', response_text, re.DOTALL) if match: response_text = match.group(1) paradigm_shift_claim = "paradigm" in response_text.lower() or "crisis" in response_text.lower() return OntologyArchitectAction( theory_module=response_text.strip(), revision_note="Generated by LLM.", paradigm_shift_claim=paradigm_shift_claim )