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54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# COSMOS Cloud Integration Guide

Enable optional cloud services (Azure, IBM) while maintaining local-first operation.

---

## Quick Start

### 1. Install Cloud Support

```bash

pip install flask openai ibm-cloud-sdk-core ibm-cloud-sdk-watsonx requests

```

### 2. Start Cloud Endpoint

```bash

python cloud_endpoint.py

```

The dashboard opens at: `http://localhost:5000`

### 3. Configure Your Cloud Services

#### Azure OpenAI

1. Go to dashboard β†’ **Azure** tab
2. Enable Azure OpenAI
3. Enter:
   - **API Key**: Your Azure OpenAI key (from portal)
   - **API Endpoint**: `https://{resource-name}.openai.azure.com/`
   - **Deployment Name**: Name of your deployed model (e.g., `gpt-4`)
   - **Model Blob**: Reference name (e.g., `gpt-4-vision`)
4. Click **Test Connection**

#### IBM Watsonx

1. Go to dashboard β†’ **IBM** tab
2. Enable IBM Watsonx
3. Enter:
   - **API Key**: Your IBM Cloud API key
   - **API Endpoint**: Your Watsonx endpoint URL
   - **Model Name**: Model ID (e.g., `granite-13b-chat-v2`)
   - **Model Blob**: Reference (e.g., `ibm/granite`)
4. Click **Test Connection**

---

## Architecture

```

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚  Genesis_Engine (Local COSMOS)      β”‚

β”‚  - Ollama (default)                 β”‚

β”‚  - Hebbian learning                 β”‚

β”‚  - Quantum heart                    β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

                   β”‚

    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

    β–Ό              β–Ό              β–Ό

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚ Ollama β”‚   β”‚  Azure   β”‚   β”‚  IBM   β”‚

β”‚ (Local)β”‚   β”‚ OpenAI   β”‚   β”‚ Watsonxβ”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜



Cloud Router (cloud_endpoint.py)

- Config management

- Credential handling

- Request routing

- Vision processing

```

---

## API Endpoints

### Configuration

**GET /api/config**
Get current configuration (sanitized).

```bash

curl http://localhost:5000/api/config

```

**POST /api/config/default**
Set default provider.

```bash

curl -X POST http://localhost:5000/api/config/default \

  -H "Content-Type: application/json" \

  -d '{"provider": "azure"}'

```

**POST /api/config/provider/{provider}**
Update provider settings.

```bash

curl -X POST http://localhost:5000/api/config/provider/azure \

  -H "Content-Type: application/json" \

  -d '{

    "endpoint": "https://myresource.openai.azure.com/",

    "model_name": "gpt-4",

    "model_blob": "gpt-4-vision"

  }'

```

### Credentials

**POST /api/credentials/{provider}**
Set API credentials (from environment variable or request body).

```bash

curl -X POST http://localhost:5000/api/credentials/azure \

  -H "Content-Type: application/json" \

  -d '{"api_key": "YOUR_AZURE_KEY"}'

```

**POST /api/credentials/test/{provider}**
Test provider connectivity.

```bash

curl -X POST http://localhost:5000/api/credentials/test/azure

```

### Generation

**POST /api/generate**
Generate response from selected provider.

```bash

curl -X POST http://localhost:5000/api/generate \

  -H "Content-Type: application/json" \

  -d '{

    "prompt": "Hello, what is your name?",

    "provider": "azure"

  }'

```

**POST /api/vision**
Analyze image with vision model.

```bash

curl -X POST http://localhost:5000/api/vision \

  -F "image=@photo.jpg" \

  -F "prompt=Describe this image" \

  -F "provider=azure"

```

### Status

**GET /api/status**
Get system status and provider info.

```bash

curl http://localhost:5000/api/status

```

**GET /api/health**
Health check.

```bash

curl http://localhost:5000/api/health

```

---

## Environment Variables

For security, use environment variables instead of hardcoding keys:

```bash

# Azure

export COSMOS_AZURE_KEY="your-azure-key-here"



# IBM

export COSMOS_IBM_KEY="your-ibm-key-here"



# Start endpoint

python cloud_endpoint.py

```

The dashboard will automatically load credentials from environment.

---

## Integration with Genesis_Engine



Add cloud routing to your Genesis_Engine:

```python

# In soul/loop.py or serve.py



from cloud_router import CloudConfig, CloudRouter



# Initialize

config = CloudConfig()

router = CloudRouter(config)



# Generate with cloud (or local fallback)

response = router.generate(

    prompt="Your message",

    provider="azure"  # or "ibm", "ollama"

)



# Handle vision

image_analysis = router.vision(

    image_path="/path/to/image.jpg",

    prompt="Describe this",

    provider="azure"  # gpt-4-vision

)

```

---

## Configuration File

Cloud settings are stored in `cloud_config.json` (credentials not persisted):

```json

{

  "enabled": true,

  "default_provider": "ollama",

  "providers": {

    "azure": {

      "enabled": false,

      "api_key": "[SET_VIA_ENV]",

      "api_endpoint": "https://myresource.openai.azure.com/",

      "deployment_name": "gpt-4",

      "model_blob": "gpt-4-vision",

      "temperature": 0.7,

      "timeout": 30

    },

    "ibm": {

      "enabled": false,

      "api_key": "[SET_VIA_ENV]",

      "api_endpoint": "https://api.us-south.watson-platform.net/instances/...",

      "model_name": "granite-13b-chat-v2",

      "model_blob": "ibm/granite",

      "temperature": 0.7,

      "timeout": 30

    },

    "ollama": {

      "enabled": true,

      "api_endpoint": "http://localhost:11434",

      "model_name": "cosmos-q4:latest",

      "timeout": 60

    }

  }

}

```

---

## Example: Full Cloud Setup

### Setup Script

```bash

#!/bin/bash



# Install dependencies

pip install flask openai ibm-cloud-sdk-core ibm-cloud-sdk-watsonx requests



# Set credentials

export COSMOS_AZURE_KEY="your-azure-key"

export COSMOS_IBM_KEY="your-ibm-key"



# Start endpoint

python cloud_endpoint.py

```

### Client Code

```python

import requests

import json



# Configure Azure as default

requests.post('http://localhost:5000/api/config/default',

              json={'provider': 'azure'})



# Generate response

response = requests.post('http://localhost:5000/api/generate',

                        json={'prompt': 'Hello!'})



print(response.json()['response'])

```

---

## Fallback Behavior

If cloud service fails, routes to:
1. Default provider (if enabled)
2. Ollama (if available)
3. Error

```python

# Graceful fallback

try:

    response = router.generate(prompt, provider='azure')

except Exception as e:

    print(f"Azure failed, falling back to Ollama: {e}")

    response = router.generate(prompt, provider='ollama')

```

---

## Vision Support

Currently supported:
- βœ… Azure OpenAI (gpt-4-vision)
- ⏳ IBM Watsonx (coming soon)
- βœ… Ollama (with multimodal models)

```python

# Azure vision

analysis = router.vision(

    image_path="photo.jpg",

    prompt="What's in this image?",

    provider="azure"

)

```

---

## Troubleshooting

### "Azure not enabled or API key not set"

- Ensure `COSMOS_AZURE_KEY` environment variable is set
- Or use dashboard to set credentials

### "Connection timeout"

- Check endpoint URL is correct
- Verify network access to cloud service
- Increase timeout in `cloud_config.json`

### "Invalid deployment name"

- Check deployment exists in Azure portal
- Name is case-sensitive
- Use "gpt-4" not "GPT-4"

### "Model not found"

- For IBM: check model ID in Watsonx console
- For Azure: verify deployment is created

---

## Security Best Practices

1. **Never commit API keys** to version control
2. **Use environment variables** for credentials
3. **Rotate keys regularly** in cloud portals
4. **Use API key with minimal permissions** if possible
5. **Monitor usage** in cloud provider dashboards
6. **Set rate limits** on endpoint if exposed

---

## Performance

Typical latencies:
- **Ollama (local)**: 50-500ms
- **Azure OpenAI**: 500-2000ms (network + model)
- **IBM Watsonx**: 500-2000ms (network + model)

For best performance:
- Use Ollama for interactive chat
- Use Azure/IBM for heavy lifting (vision, reasoning)
- Implement caching for repeated prompts

---

## Advanced: Custom Providers

Extend `CloudRouter` to add custom providers:

```python

class CustomRouter(CloudRouter):

    def _generate_custom(self, prompt: str, **kwargs) -> str:

        """Add your custom provider here."""

        # Implementation

        pass

    

    def generate(self, prompt, provider=None, **kwargs):

        if provider == "custom":

            return self._generate_custom(prompt, **kwargs)

        return super().generate(prompt, provider, **kwargs)

```

---

## Deployment

### Docker

```dockerfile

FROM python:3.9

WORKDIR /cosmos

COPY cloud_*.py .

COPY templates/ templates/

RUN pip install flask openai requests



EXPOSE 5000

CMD ["python", "cloud_endpoint.py"]

```

### Systemd Service

```ini

[Unit]

Description=COSMOS Cloud Router

After=network.target



[Service]

Type=simple

User=cosmos

WorkingDirectory=/opt/cosmos

EnvironmentFile=/etc/cosmos/cloud.env

ExecStart=/usr/bin/python3 cloud_endpoint.py

Restart=always



[Install]

WantedBy=multi-user.target

```

---

## License & Citation

COSMOS Cloud Integration is part of the COSMOS project.

```bibtex

@misc{phera2026cosmos,

  title={COSMOS: A 54D Quantum-Inspired Transformer with Cloud Integration},

  author={Phera},

  year={2026},

  url={https://zenodo.org/records/17574447}

}

```

---

**Questions?** Check `/docs` endpoint or review `cloud_router.py` source code.