rb125 commited on
Commit
3f8f8eb
·
1 Parent(s): 1c858dd

added LLM agents with azure, bedrock, and gemma support

Browse files
cgae_engine/llm_agent.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLM-backed Agent - Calls real Azure AI Foundry model endpoints.
3
+
4
+ Reuses the proven agent infrastructure from the DDFT/EECT frameworks
5
+ (AzureOpenAIAgent, AzureAIAgent) but wrapped for the CGAE economy loop.
6
+
7
+ Each LLMAgent:
8
+ - Has a real model backing it (e.g., gpt-5, deepseek-v3.1, phi-4)
9
+ - Executes tasks by sending prompts to the model and receiving outputs
10
+ - Has its robustness measured by actual CDCT/DDFT/EECT audits (or synthetics until wired)
11
+ - Competes in the CGAE economy alongside other LLM-backed agents
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import os
18
+ import time
19
+ from dataclasses import dataclass
20
+ from threading import Lock
21
+ from typing import Optional
22
+
23
+ from openai import AzureOpenAI, OpenAI
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Retry handler (inline to avoid import path issues with framework code)
30
+ # ---------------------------------------------------------------------------
31
+
32
+ @dataclass
33
+ class RetryConfig:
34
+ max_retries: int = 3
35
+ base_delay: float = 2.0
36
+ max_delay: float = 60.0
37
+
38
+
39
+ def call_with_retry(api_call, config: RetryConfig, log_prefix: str = ""):
40
+ retries = 0
41
+ while True:
42
+ try:
43
+ return api_call()
44
+ except Exception as e:
45
+ retries += 1
46
+ if retries > config.max_retries:
47
+ logger.error(f"{log_prefix} Final attempt failed: {e}")
48
+ raise
49
+ delay = min(config.max_delay, config.base_delay * (2 ** (retries - 1)))
50
+ logger.warning(
51
+ f"{log_prefix} Attempt {retries}/{config.max_retries} failed: {e}. "
52
+ f"Retrying in {delay:.1f}s..."
53
+ )
54
+ time.sleep(delay)
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Client pools (thread-safe singletons)
59
+ # ---------------------------------------------------------------------------
60
+
61
+ _azure_openai_clients: dict[str, AzureOpenAI] = {}
62
+ _azure_openai_lock = Lock()
63
+
64
+ _openai_clients: dict[str, OpenAI] = {}
65
+ _openai_lock = Lock()
66
+
67
+
68
+ def _get_azure_openai_client(api_key: str, endpoint: str, api_version: str) -> AzureOpenAI:
69
+ key = f"{endpoint}:{api_version}"
70
+ if key not in _azure_openai_clients:
71
+ with _azure_openai_lock:
72
+ if key not in _azure_openai_clients:
73
+ _azure_openai_clients[key] = AzureOpenAI(
74
+ api_key=api_key,
75
+ azure_endpoint=endpoint,
76
+ api_version=api_version,
77
+ )
78
+ return _azure_openai_clients[key]
79
+
80
+
81
+ def _get_openai_client(base_url: str, api_key: str) -> OpenAI:
82
+ key = f"{base_url}"
83
+ if key not in _openai_clients:
84
+ with _openai_lock:
85
+ if key not in _openai_clients:
86
+ _openai_clients[key] = OpenAI(base_url=base_url, api_key=api_key)
87
+ return _openai_clients[key]
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # LLM Agent
92
+ # ---------------------------------------------------------------------------
93
+
94
+ class LLMAgent:
95
+ """
96
+ A live LLM agent backed by an Azure AI Foundry model endpoint.
97
+
98
+ Provides:
99
+ - chat(messages) -> str: Send messages, get response
100
+ - execute_task(prompt, system_prompt) -> str: Execute a task
101
+ - Token/call tracking for cost accounting
102
+ """
103
+
104
+ def __init__(self, model_config: dict):
105
+ self.model_name: str = model_config["model_name"]
106
+ self.deployment_name: str = model_config.get("deployment_name", model_config.get("model_id", ""))
107
+ self.provider: str = model_config["provider"]
108
+ self.family: str = model_config.get("family", "Unknown")
109
+ self.retry_config = RetryConfig()
110
+
111
+ # Tracking
112
+ self.total_calls: int = 0
113
+ self.total_input_tokens: int = 0
114
+ self.total_output_tokens: int = 0
115
+ self.total_errors: int = 0
116
+ self.total_latency_ms: float = 0.0
117
+
118
+ if self.provider == "bedrock":
119
+ # Bedrock uses ABSK bearer token + direct HTTP
120
+ self._bedrock_key = os.environ.get("AWS_BEARER_TOKEN_BEDROCK", "")
121
+ model_id = model_config.get("model_id", self.deployment_name)
122
+ region = model_config.get("region", "us-east-1")
123
+ self._bedrock_url = f"https://bedrock-runtime.{region}.amazonaws.com/model/{model_id}/converse"
124
+ self._client = None
125
+ if not self._bedrock_key:
126
+ raise EnvironmentError(f"Missing AWS_BEARER_TOKEN_BEDROCK for {self.model_name}")
127
+ else:
128
+ # Azure OpenAI / Azure AI Foundry / Gemma (OpenAI-compatible)
129
+ api_key_var = model_config["api_key_env_var"]
130
+ endpoint_var = model_config["endpoint_env_var"]
131
+ self._api_key = os.environ.get(api_key_var, "")
132
+ self._endpoint = os.environ.get(endpoint_var, "")
133
+ self._api_version = model_config.get("api_version", "2025-03-01-preview")
134
+
135
+ if not self._api_key:
136
+ raise EnvironmentError(f"Missing env var {api_key_var} for model {self.model_name}")
137
+ if not self._endpoint:
138
+ raise EnvironmentError(f"Missing env var {endpoint_var} for model {self.model_name}")
139
+
140
+ if self.provider == "azure_openai":
141
+ self._client = _get_azure_openai_client(
142
+ self._api_key, self._endpoint, self._api_version
143
+ )
144
+ elif self.provider == "azure_ai":
145
+ self._client = _get_openai_client(self._endpoint, self._api_key)
146
+ else:
147
+ raise ValueError(f"Unsupported provider: {self.provider}")
148
+
149
+ def chat(self, messages: list[dict]) -> str:
150
+ """
151
+ Send messages to the model and return the response text.
152
+ Tracks tokens and latency for cost accounting.
153
+ """
154
+ log_prefix = f"[{self.model_name}]"
155
+
156
+ if self.provider == "bedrock":
157
+ return self._chat_bedrock(messages, log_prefix)
158
+
159
+ def _call():
160
+ kwargs = {
161
+ "model": self.deployment_name,
162
+ "messages": messages,
163
+ "timeout": 180,
164
+ }
165
+ if self.provider == "azure_openai":
166
+ kwargs["max_completion_tokens"] = 8192
167
+ else:
168
+ kwargs["temperature"] = 0.0
169
+ kwargs["max_tokens"] = 4096
170
+
171
+ start = time.time()
172
+ response = self._client.chat.completions.create(**kwargs)
173
+ latency = (time.time() - start) * 1000
174
+
175
+ self.total_calls += 1
176
+ self.total_latency_ms += latency
177
+ if response.usage:
178
+ self.total_input_tokens += response.usage.prompt_tokens or 0
179
+ self.total_output_tokens += response.usage.completion_tokens or 0
180
+
181
+ return response.choices[0].message.content
182
+
183
+ try:
184
+ return call_with_retry(_call, self.retry_config, log_prefix)
185
+ except Exception as e:
186
+ self.total_errors += 1
187
+ raise
188
+
189
+ def _chat_bedrock(self, messages: list[dict], log_prefix: str) -> str:
190
+ """Bedrock Converse API via direct HTTP with ABSK bearer token."""
191
+ import requests
192
+
193
+ def _call():
194
+ # Bedrock expects system messages in a separate 'system' field
195
+ system_parts = []
196
+ user_messages = []
197
+ for m in messages:
198
+ if m["role"] == "system":
199
+ system_parts.append({"text": m["content"]})
200
+ else:
201
+ user_messages.append({"role": m["role"], "content": [{"text": m["content"]}]})
202
+
203
+ body = {
204
+ "messages": user_messages,
205
+ "inferenceConfig": {"temperature": 0.0, "maxTokens": 4096},
206
+ }
207
+ if system_parts:
208
+ body["system"] = system_parts
209
+
210
+ start = time.time()
211
+ resp = requests.post(
212
+ self._bedrock_url,
213
+ headers={
214
+ "Content-Type": "application/json",
215
+ "Authorization": f"Bearer {self._bedrock_key}",
216
+ },
217
+ json=body, timeout=300,
218
+ )
219
+ resp.raise_for_status()
220
+ latency = (time.time() - start) * 1000
221
+
222
+ self.total_calls += 1
223
+ self.total_latency_ms += latency
224
+
225
+ data = resp.json()
226
+ usage = data.get("usage", {})
227
+ self.total_input_tokens += usage.get("inputTokens", 0)
228
+ self.total_output_tokens += usage.get("outputTokens", 0)
229
+
230
+ content = data["output"]["message"]["content"]
231
+ for block in content:
232
+ if "text" in block:
233
+ return block["text"]
234
+ return str(content)
235
+
236
+ try:
237
+ return call_with_retry(_call, self.retry_config, log_prefix)
238
+ except Exception as e:
239
+ self.total_errors += 1
240
+ raise
241
+
242
+ def execute_task(self, prompt: str, system_prompt: Optional[str] = None) -> str:
243
+ """Execute a task with an optional system prompt."""
244
+ messages = []
245
+ if system_prompt:
246
+ messages.append({"role": "system", "content": system_prompt})
247
+ messages.append({"role": "user", "content": prompt})
248
+ return self.chat(messages)
249
+
250
+ def usage_summary(self) -> dict:
251
+ """Return usage stats for cost accounting."""
252
+ return {
253
+ "model": self.model_name,
254
+ "total_calls": self.total_calls,
255
+ "total_input_tokens": self.total_input_tokens,
256
+ "total_output_tokens": self.total_output_tokens,
257
+ "total_errors": self.total_errors,
258
+ "avg_latency_ms": (
259
+ self.total_latency_ms / self.total_calls
260
+ if self.total_calls > 0 else 0
261
+ ),
262
+ }
263
+
264
+ def __repr__(self):
265
+ return f"LLMAgent({self.model_name}, provider={self.provider})"
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Factory
270
+ # ---------------------------------------------------------------------------
271
+
272
+ def create_llm_agent(model_config: dict) -> LLMAgent:
273
+ """Create an LLM agent from a model config dict."""
274
+ return LLMAgent(model_config)
275
+
276
+
277
+ def create_llm_agents(model_configs: list[dict]) -> dict[str, LLMAgent]:
278
+ """Create all LLM agents from a list of configs. Returns {model_name: agent}."""
279
+ agents = {}
280
+ for config in model_configs:
281
+ try:
282
+ agent = create_llm_agent(config)
283
+ agents[agent.model_name] = agent
284
+ logger.info(f"Created LLM agent: {agent.model_name} ({agent.provider})")
285
+ except EnvironmentError as e:
286
+ logger.warning(f"Skipping {config['model_name']}: {e}")
287
+ return agents
cgae_engine/models_config.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CGAE Model Configurations — aligned with CDCT evaluation models.
3
+
4
+ Three providers:
5
+ - Azure OpenAI (GPT) via cognitiveservices endpoint
6
+ - Azure AI Foundry (DeepSeek, Mistral, Grok, Phi, Llama, Kimi) via services.ai endpoint
7
+ - AWS Bedrock (Nova, Claude, MiniMax, jury models) via ABSK bearer token
8
+ - Gemma via Modal (self-hosted, OpenAI-compatible)
9
+
10
+ Environment variables:
11
+ AZURE_API_KEY - Shared Azure key
12
+ AZURE_OPENAI_API_ENDPOINT - Azure OpenAI (GPT models)
13
+ FOUNDRY_MODELS_ENDPOINT - Azure AI Foundry
14
+ AWS_BEARER_TOKEN_BEDROCK - Bedrock ABSK bearer token
15
+ GEMMA_BASE_URL - Modal endpoint for Gemma
16
+ GEMMA_API_KEY - Gemma API key (usually "not-needed")
17
+ """
18
+
19
+ AVAILABLE_MODELS = [
20
+ # --- Azure OpenAI ---
21
+ {
22
+ "model_name": "gpt-5.4",
23
+ "deployment_name": "gpt-5.4",
24
+ "provider": "azure_openai",
25
+ "api_key_env_var": "AZURE_API_KEY",
26
+ "endpoint_env_var": "AZURE_OPENAI_API_ENDPOINT",
27
+ "api_version": "2025-03-01-preview",
28
+ "family": "OpenAI",
29
+ "tier_assignment": "contestant",
30
+ },
31
+ # --- Azure AI Foundry ---
32
+ {
33
+ "model_name": "DeepSeek-V3.2",
34
+ "deployment_name": "DeepSeek-V3.2",
35
+ "provider": "azure_ai",
36
+ "api_key_env_var": "AZURE_API_KEY",
37
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
38
+ "family": "DeepSeek",
39
+ "tier_assignment": "contestant",
40
+ },
41
+ {
42
+ "model_name": "Mistral-Large-3",
43
+ "deployment_name": "Mistral-Large-3",
44
+ "provider": "azure_ai",
45
+ "api_key_env_var": "AZURE_API_KEY",
46
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
47
+ "family": "Mistral",
48
+ "tier_assignment": "contestant",
49
+ },
50
+ {
51
+ "model_name": "grok-4-20-reasoning",
52
+ "deployment_name": "grok-4-20-reasoning",
53
+ "provider": "azure_ai",
54
+ "api_key_env_var": "AZURE_API_KEY",
55
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
56
+ "family": "xAI",
57
+ "tier_assignment": "contestant",
58
+ },
59
+ {
60
+ "model_name": "Phi-4",
61
+ "deployment_name": "Phi-4",
62
+ "provider": "azure_ai",
63
+ "api_key_env_var": "AZURE_API_KEY",
64
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
65
+ "family": "Microsoft",
66
+ "tier_assignment": "contestant",
67
+ },
68
+ {
69
+ "model_name": "Llama-4-Maverick-17B-128E-Instruct-FP8",
70
+ "deployment_name": "Llama-4-Maverick-17B-128E-Instruct-FP8",
71
+ "provider": "azure_ai",
72
+ "api_key_env_var": "AZURE_API_KEY",
73
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
74
+ "family": "Meta",
75
+ "tier_assignment": "contestant",
76
+ },
77
+ {
78
+ "model_name": "Kimi-K2.5",
79
+ "deployment_name": "Kimi-K2.5",
80
+ "provider": "azure_ai",
81
+ "api_key_env_var": "AZURE_API_KEY",
82
+ "endpoint_env_var": "FOUNDRY_MODELS_ENDPOINT",
83
+ "family": "Moonshot",
84
+ "tier_assignment": "contestant",
85
+ },
86
+ # --- Gemma via Modal ---
87
+ {
88
+ "model_name": "gemma-4-27b-it",
89
+ "deployment_name": "google/gemma-4-26B-A4B-it",
90
+ "provider": "azure_ai",
91
+ "api_key_env_var": "GEMMA_API_KEY",
92
+ "endpoint_env_var": "GEMMA_BASE_URL",
93
+ "family": "Google",
94
+ "tier_assignment": "contestant",
95
+ },
96
+ # --- AWS Bedrock (contestant) ---
97
+ {
98
+ "model_name": "nova-pro",
99
+ "model_id": "amazon.nova-pro-v1:0",
100
+ "provider": "bedrock",
101
+ "region": "us-east-1",
102
+ "family": "Amazon",
103
+ "tier_assignment": "contestant",
104
+ },
105
+ {
106
+ "model_name": "claude-sonnet-4.6",
107
+ "model_id": "us.anthropic.claude-sonnet-4-6",
108
+ "provider": "bedrock",
109
+ "region": "us-east-1",
110
+ "family": "Anthropic",
111
+ "tier_assignment": "contestant",
112
+ },
113
+ {
114
+ "model_name": "MiniMax-M2.5",
115
+ "model_id": "minimax.minimax-m2.5",
116
+ "provider": "bedrock",
117
+ "region": "us-east-1",
118
+ "family": "MiniMax",
119
+ "tier_assignment": "contestant",
120
+ },
121
+ # --- AWS Bedrock (jury — zero family overlap with contestants) ---
122
+ {
123
+ "model_name": "Qwen3-32B",
124
+ "model_id": "qwen.qwen3-32b-v1:0",
125
+ "provider": "bedrock",
126
+ "region": "us-east-1",
127
+ "family": "Alibaba",
128
+ "tier_assignment": "jury",
129
+ },
130
+ {
131
+ "model_name": "GLM-5",
132
+ "model_id": "zai.glm-5",
133
+ "provider": "bedrock",
134
+ "region": "us-east-1",
135
+ "family": "Zhipu",
136
+ "tier_assignment": "jury",
137
+ },
138
+ {
139
+ "model_name": "Nemotron-Super-3-120B",
140
+ "model_id": "nvidia.nemotron-super-3-120b",
141
+ "provider": "bedrock",
142
+ "region": "us-east-1",
143
+ "family": "NVIDIA",
144
+ "tier_assignment": "jury",
145
+ },
146
+ ]
147
+
148
+ JURY_MODELS = [m for m in AVAILABLE_MODELS if m["tier_assignment"] == "jury"]
149
+ CONTESTANT_MODELS = [m for m in AVAILABLE_MODELS if m["tier_assignment"] != "jury"]
150
+
151
+
152
+ def get_model_config(model_name: str) -> dict:
153
+ for m in AVAILABLE_MODELS:
154
+ if m["model_name"] == model_name:
155
+ return m
156
+ raise KeyError(f"Model '{model_name}' not found in AVAILABLE_MODELS")