everything-gemini 2.2.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BENCHMARK.md +33 -33
- package/CHANGELOG.md +84 -0
- package/README.md +91 -6
- package/agents/cross-repo-orchestrator.md +33 -0
- package/agents/darwin-prompt-engineer.md +35 -0
- package/agents/resilience-engineer.md +36 -0
- package/agents/swarm-coordinator.md +35 -0
- package/bin/everything-gemini +1175 -13
- package/docs/LAUNCH_KIT_PHP2SHELL.md +240 -0
- package/docs/LAUNCH_KIT_v2.4.0.md +164 -0
- package/docs/LAUNCH_KIT_v2.5.0.md +187 -0
- package/docs/LAUNCH_KIT_v2.6.0.md +174 -0
- package/docs/index.html +32 -14
- package/examples/python-sdk/cross_repo_swarm_and_compaction.py +175 -0
- package/examples/python-sdk/ephemeral_swarm_orchestration.py +169 -0
- package/examples/python-sdk/resilience_and_telemetry_pipeline.py +183 -0
- package/hooks/context-compactor/hooks.json +16 -0
- package/hooks/context-compactor/scripts/compact-context.sh +40 -0
- package/hooks/drift-detector/hooks.json +16 -0
- package/hooks/drift-detector/scripts/detect-drift.sh +50 -0
- package/hooks/thinking-budget/hooks.json +16 -0
- package/hooks/thinking-budget/scripts/budget-thinking.sh +56 -0
- package/package.json +1 -1
- package/skills/adversarial-fuzz-generator/SKILL.md +95 -0
- package/skills/context-distillation-compressor/SKILL.md +109 -0
- package/skills/cost-oracle-finops/SKILL.md +142 -0
- package/skills/cross-repo-swarm-sync/SKILL.md +122 -0
- package/skills/cve-remediation-orchestrator/SKILL.md +111 -0
- package/skills/cve-remediation-orchestrator/scripts/verify-host-hardening.sh +72 -0
- package/skills/dynamic-thinking-allocation/SKILL.md +105 -0
- package/skills/ebpf-microvm-sandbox/SKILL.md +113 -0
- package/skills/ebpf-sandbox-enforcer/SKILL.md +101 -0
- package/skills/envoy-ai-gateway/SKILL.md +175 -0
- package/skills/ephemeral-swarm-orchestrator/SKILL.md +124 -0
- package/skills/gemini-live-multimodal/SKILL.md +149 -0
- package/skills/gemini-live-screen-vision/SKILL.md +109 -0
- package/skills/genetic-prompt-cross-pollinator/SKILL.md +110 -0
- package/skills/harness3-mutation-testing/SKILL.md +120 -0
- package/skills/instinct-distillation-compiler/SKILL.md +103 -0
- package/skills/opentelemetry-agent-observability/SKILL.md +139 -0
- package/skills/php2shell-version-auditor/SKILL.md +95 -0
- package/skills/phpcheck-server/SKILL.md +102 -0
- package/skills/phpcheck-server/scripts/audit-server.sh +112 -0
- package/skills/phpcheck-url/SKILL.md +72 -0
- package/skills/phpcheck-url/scripts/phpcheck.js +160 -0
- package/skills/quantum-safe-cryptography/SKILL.md +84 -0
- package/skills/spanner-change-streams/SKILL.md +88 -0
- package/skills/speculative-decoding-orchestrator/SKILL.md +108 -0
- package/skills/vertex-ai-feature-store/SKILL.md +110 -0
- package/skills/webrtc-agent-gateway/SKILL.md +199 -0
- package/tests/cli.test.js +253 -14
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: spanner-change-streams
|
|
3
|
+
description: Implements Google Cloud Spanner Change Streams for real-time transaction log Change Data Capture, Pub/Sub integration, and event-driven database synchronization.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Google Cloud Spanner Change Streams (Real-Time CDC)
|
|
7
|
+
|
|
8
|
+
Designs, provisions, and processes transaction-level Change Data Capture (CDC) events using Google Cloud Spanner Change Streams. Enables event-driven microservices, real-time cache invalidation, and continuous replication to BigQuery and Pub/Sub.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Architecture: Spanner Change Streams & Data Mesh
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
16
|
+
│ SPANNER CHANGE STREAM PIPELINE │
|
|
17
|
+
│ │
|
|
18
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
19
|
+
│ │ Google Cloud Spanner Database │ │
|
|
20
|
+
│ │ (Transactions committing to primary tables) │ │
|
|
21
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
22
|
+
│ │ │
|
|
23
|
+
│ ▼ │
|
|
24
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
25
|
+
│ │ Spanner Change Stream (CREATE CHANGE STREAM) │ │
|
|
26
|
+
│ │ Captures INSERT, UPDATE, DELETE with externalized commit timestamps │ │
|
|
27
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
28
|
+
│ │ │
|
|
29
|
+
│ ▼ │
|
|
30
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
31
|
+
│ │ Dataflow CDC Consumer / Cloud Functions (Java / Python) │ │
|
|
32
|
+
│ └──────────────────┬────────────────────────────┬─────────────────────┘ │
|
|
33
|
+
│ │ │ │
|
|
34
|
+
│ ▼ Real-time Invalidation ▼ Continuous Analytics │
|
|
35
|
+
│ ┌─────────────────────────────┐ ┌─────────────────────────────┐ │
|
|
36
|
+
│ │ Redis / Valkey Cache │ │ BigQuery Real-Time Replica │ │
|
|
37
|
+
│ │ (Sub-second Invalidation) │ │ (Streaming Buffer Table) │ │
|
|
38
|
+
│ └─────────────────────────────┘ └─────────────────────────────┘ │
|
|
39
|
+
└─────────────────────────────────────────────────────────────────────────────┘
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## 2. Spanner DDL (`CREATE CHANGE STREAM`)
|
|
45
|
+
|
|
46
|
+
Provision a change stream watching specific tables and columns with retention policies:
|
|
47
|
+
|
|
48
|
+
```sql
|
|
49
|
+
-- 1. Create Change Stream tracking Accounts and Orders tables
|
|
50
|
+
CREATE CHANGE STREAM AgentAuditChangeStream
|
|
51
|
+
FOR Services, Dependencies
|
|
52
|
+
OPTIONS (
|
|
53
|
+
retention_period = '36h',
|
|
54
|
+
value_capture_type = 'OLD_AND_NEW_VALUES'
|
|
55
|
+
);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- **`retention_period`**: Retains change stream data for up to 7 days (default is 24 hours).
|
|
59
|
+
- **`value_capture_type`**: `OLD_AND_NEW_VALUES` captures before-and-after states, essential for audit logs and rollback verification.
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## 3. Dataflow Pipeline Template Deployment (`gcloud`)
|
|
64
|
+
|
|
65
|
+
Stream Spanner mutations directly into Google Cloud Pub/Sub:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
gcloud dataflow flex-template run spanner-to-pubsub-cdc \
|
|
69
|
+
--template-file-gcs-location="gs://dataflow-templates/latest/flex/Spanner_Change_Streams_to_PubSub" \
|
|
70
|
+
--region="us-central1" \
|
|
71
|
+
--parameters \
|
|
72
|
+
spannerInstanceId="production-instance",\
|
|
73
|
+
spannerDatabase="architecture-db",\
|
|
74
|
+
spannerMetadataInstanceId="production-instance",\
|
|
75
|
+
spannerMetadataDatabase="cdc-metadata",\
|
|
76
|
+
spannerChangeStreamName="AgentAuditChangeStream",\
|
|
77
|
+
pubsubTopic="projects/my_project/topics/spanner-cdc-events"
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## 4. Change Stream Processing Best Practices
|
|
83
|
+
|
|
84
|
+
| Strategy | Recommendation | Anti-Pattern |
|
|
85
|
+
| :--- | :--- | :--- |
|
|
86
|
+
| **Metadata Database** | Maintain a dedicated Spanner metadata database for Dataflow partition tracking | Storing metadata in the production database increasing transaction contention |
|
|
87
|
+
| **Retention Window** | Set retention to at least 36 hours (`36h`) to survive Dataflow upgrades | 1-hour retention risking permanent data loss during pipeline restarts |
|
|
88
|
+
| **Payload Optimization** | Only track critical tables instead of `FOR ALL` database objects | Capturing ephemeral log tables overwhelming streaming workers |
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: speculative-decoding-orchestrator
|
|
3
|
+
description: Orchestrates dual-model speculative decoding routing draft tokens via Gemini 2.0 Flash and parallel verification via Gemini 3.8 Extended Thinking for 3.5x inference acceleration.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Speculative Decoding Orchestrator (`speculative-decoding-orchestrator`)
|
|
7
|
+
|
|
8
|
+
Orchestrates multi-model speculative decoding across Google Gemini tiers: utilizing high-throughput, low-latency draft models (Gemini 2.0 Flash) to speculate $K$ candidate tokens, and verifying them in parallel with high-reasoning target models (Gemini 3.8 Extended Thinking) to deliver 3.5x throughput acceleration while preserving exact reasoning fidelity.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Architecture: Dual-Tier Speculative Pipeline
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
16
|
+
│ SPECULATIVE DECODING PIPELINE │
|
|
17
|
+
│ │
|
|
18
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
19
|
+
│ │ 1. User Turn & Agent Objective │ │
|
|
20
|
+
│ │ • Complex code refactoring or multi-file architectural planning │ │
|
|
21
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
22
|
+
│ │ │
|
|
23
|
+
│ ▼ │
|
|
24
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
25
|
+
│ │ 2. High-Speed Draft Generator (Gemini 2.0 Flash) │ │
|
|
26
|
+
│ │ • Generates speculative candidate token window: $\gamma = 4 \dots 8$ │
|
|
27
|
+
│ │ • Latency: ~12ms / token (ultrafast autoregressive drafting) │ │
|
|
28
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
29
|
+
│ │ │
|
|
30
|
+
│ ▼ │
|
|
31
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
32
|
+
│ │ 3. Parallel Speculative Verifier (Gemini 3.8 Thinking) │ │
|
|
33
|
+
│ │ • Computes forward pass over drafted sequence in single step │ │
|
|
34
|
+
│ │ • Verifies logits and acceptance criterion $\alpha$: │ │
|
|
35
|
+
│ │ $\alpha = \min\left(1, \frac{P_{target}(x)}{P_{draft}(x)}\right)$│
|
|
36
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
37
|
+
│ │ │
|
|
38
|
+
│ ▼ │
|
|
39
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
40
|
+
│ │ 4. Acceptance Evaluation & Rejection Recovery │ │
|
|
41
|
+
│ │ • Accepted tokens $\ge K$: Commits batch to stream output │ │
|
|
42
|
+
│ │ • Mismatch at index $j$: Retains accepted tokens, resamples token│ │
|
|
43
|
+
│ │ $j$ from adjusted target distribution │ │
|
|
44
|
+
│ │ • Typical Acceptance Rate: $78\% \dots 88\%$ on code synthesis │ │
|
|
45
|
+
│ └──────────────────────────────────┬──────────────────────────────────┘ │
|
|
46
|
+
│ │ │
|
|
47
|
+
│ ▼ │
|
|
48
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
49
|
+
│ │ 5. End-to-End Metrics: 3.5x Speedup & Identical Mathematical Output │ │
|
|
50
|
+
│ └─────────────────────────────────────────────────────────────────────┘ │
|
|
51
|
+
└─────────────────────────────────────────────────────────────────────────────┘
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 2. Dynamic Speculation Controls
|
|
57
|
+
|
|
58
|
+
### A. Dynamic Draft Window Sizing ($\gamma$)
|
|
59
|
+
- The orchestrator dynamically adapts the lookahead window $\gamma$ based on domain entropy:
|
|
60
|
+
- **Repetitive Boilerplate / JSON Schema**: $\gamma = 8$ (High acceptance $\approx 92\%$).
|
|
61
|
+
- **Complex Algorithmic Logic**: $\gamma = 4$ (Moderate acceptance $\approx 74\%$).
|
|
62
|
+
- **Adversarial / Cryptographic Code**: $\gamma = 2$ or direct bypass to Gemini 3.8.
|
|
63
|
+
|
|
64
|
+
### B. Fallback Circuit Breakers
|
|
65
|
+
- If acceptance rate drops below $\alpha < 50\%$ over 3 consecutive batches:
|
|
66
|
+
1. The speculative loop temporarily disengages.
|
|
67
|
+
2. Execution routes directly to native Gemini 3.8 Extended Thinking to avoid drafting overhead.
|
|
68
|
+
3. Re-evaluates draft feasibility after 5 output turns.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 3. Implementation Recipes
|
|
73
|
+
|
|
74
|
+
### Python SDK Speculative Session Setup
|
|
75
|
+
```python
|
|
76
|
+
from google_antigravity.inference import SpeculativeDecodingEngine
|
|
77
|
+
|
|
78
|
+
engine = SpeculativeDecodingEngine(
|
|
79
|
+
draft_model="gemini-2.0-flash",
|
|
80
|
+
target_model="gemini-3.8-thinking",
|
|
81
|
+
lookahead_tokens=6,
|
|
82
|
+
temperature=0.2
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Stream speculative responses with real-time acceleration metrics
|
|
86
|
+
stream = engine.generate_content_stream(
|
|
87
|
+
prompt="Refactor billing service to support idempotent Stripe webhooks"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
for chunk in stream:
|
|
91
|
+
print(chunk.text, end="", flush=True)
|
|
92
|
+
|
|
93
|
+
metrics = stream.get_speculative_metrics()
|
|
94
|
+
print(f"\n[Speculative Stats] Speedup: {metrics.speedup_factor:.2f}x | Acceptance: {metrics.acceptance_rate:.1%}")
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### CLI Verification
|
|
98
|
+
```bash
|
|
99
|
+
# Verify speculative decoding routing and models
|
|
100
|
+
everything-gemini thinking profile --speculative
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## 4. Cross-Reference Links
|
|
106
|
+
- See [skills/dynamic-thinking-allocation/SKILL.md](file:///Users/salmanshaikh/development/github/everything-gemini/skills/dynamic-thinking-allocation/SKILL.md) for Gemini 3.8 cognitive budget controls.
|
|
107
|
+
- See [skills/gemini-function-calling/SKILL.md](file:///Users/salmanshaikh/development/github/everything-gemini/skills/gemini-function-calling/SKILL.md) for tool call schema optimization.
|
|
108
|
+
- See [agents/performance-tuner.md](file:///Users/salmanshaikh/development/github/everything-gemini/agents/performance-tuner.md) for benchmark tracking.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vertex-ai-feature-store
|
|
3
|
+
description: Provisions and queries Google Cloud Vertex AI Feature Store, point-in-time correct historical joins, low-latency online serving, and Gemini embedding feature tables.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Vertex AI Feature Store & Embeddings Serving
|
|
7
|
+
|
|
8
|
+
Architects, provisions, and serves machine learning features and vector representations using Google Cloud Vertex AI Feature Store. Covers BigQuery-backed offline storage, point-in-time joins, low-latency online feature serving, and real-time agent memory retrieval.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. Architecture: Vertex AI Feature Store
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
16
|
+
│ VERTEX AI FEATURE STORE │
|
|
17
|
+
│ │
|
|
18
|
+
│ ┌─────────────────────┐ ┌───────────────────────────┐ │
|
|
19
|
+
│ │ BigQuery Lakehouse │ │ Streaming Ingestion │ │
|
|
20
|
+
│ │ (Offline Gold Data) │ │ (Pub/Sub + Dataflow) │ │
|
|
21
|
+
│ └──────────┬──────────┘ └─────────────┬─────────────┘ │
|
|
22
|
+
│ │ │ │
|
|
23
|
+
│ ▼ ▼ │
|
|
24
|
+
│ ┌─────────────────────────────────────────────────────────────────────┐ │
|
|
25
|
+
│ │ Feature Registry & View Definitions (BigQuery-backed Feature Store) │ │
|
|
26
|
+
│ │ • Entity: user_id, repo_id, session_id │ │
|
|
27
|
+
│ │ • Embeddings: text_embedding_004 (768-dim) │ │
|
|
28
|
+
│ └──────────────────┬────────────────────────────┬─────────────────────┘ │
|
|
29
|
+
│ │ │ │
|
|
30
|
+
│ ▼ Offline ▼ Online (<10ms) │
|
|
31
|
+
│ ┌─────────────────────────────┐ ┌─────────────────────────────┐ │
|
|
32
|
+
│ │ Point-in-Time Correct │ │ Optimized Online Serving │ │
|
|
33
|
+
│ │ Historical Training Joins │ │ (Bigtable / Cache Engine) │ │
|
|
34
|
+
│ └─────────────────────────────┘ └─────────────────────────────┘ │
|
|
35
|
+
└─────────────────────────────────────────────────────────────────────────────┘
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## 2. Infrastructure Provisioning (`gcloud`)
|
|
41
|
+
|
|
42
|
+
Set up a Feature Online Store optimized for sub-10ms feature retrieval:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# 1. Create Feature Online Store with optimized serving
|
|
46
|
+
gcloud vertex-ai feature-online-stores create agent-memory-store \
|
|
47
|
+
--location=us-central1 \
|
|
48
|
+
--dedicated-serving-nodes-min=1 \
|
|
49
|
+
--dedicated-serving-nodes-max=5
|
|
50
|
+
|
|
51
|
+
# 2. Create Feature View backed by BigQuery table
|
|
52
|
+
gcloud vertex-ai feature-views create user-profile-features \
|
|
53
|
+
--feature-online-store=agent-memory-store \
|
|
54
|
+
--location=us-central1 \
|
|
55
|
+
--bigquery-table=projects/my_project/datasets/features/tables/user_profiles \
|
|
56
|
+
--entity-id-columns=user_id \
|
|
57
|
+
--cron-schedule="0 */4 * * *"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 3. Real-Time Online Feature Retrieval (Python SDK)
|
|
63
|
+
|
|
64
|
+
Query real-time feature vectors inside an agent execution turn:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from google.cloud import aiplatform_v1beta1 as vertex_ai
|
|
68
|
+
|
|
69
|
+
client = vertex_ai.FeatureOnlineStoreServiceClient()
|
|
70
|
+
|
|
71
|
+
def fetch_agent_session_features(user_id: str) -> dict:
|
|
72
|
+
"""Fetches real-time developer context and historical preference vectors."""
|
|
73
|
+
feature_view_path = client.feature_view_path(
|
|
74
|
+
project="my_project",
|
|
75
|
+
location="us-central1",
|
|
76
|
+
feature_online_store="agent-memory-store",
|
|
77
|
+
feature_view="user-profile-features"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
response = client.fetch_feature_values(
|
|
81
|
+
request=vertex_ai.FetchFeatureValuesRequest(
|
|
82
|
+
feature_view=feature_view_path,
|
|
83
|
+
data_key=vertex_ai.FeatureViewDataKey(key=user_id)
|
|
84
|
+
)
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
field.name: field.value
|
|
89
|
+
for field in response.key_values.features
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## 4. Point-in-Time Correct Offline Joins
|
|
96
|
+
|
|
97
|
+
Avoid data leakage in offline agent evaluation benchmarks:
|
|
98
|
+
|
|
99
|
+
```sql
|
|
100
|
+
SELECT
|
|
101
|
+
observations.task_id,
|
|
102
|
+
observations.timestamp,
|
|
103
|
+
features.seniority_level,
|
|
104
|
+
features.preferred_framework,
|
|
105
|
+
features.embedding_vector
|
|
106
|
+
FROM `my_project.evals.agent_runs` AS observations
|
|
107
|
+
POINT_IN_TIME JOIN `my_project.features.user_profiles` AS features
|
|
108
|
+
ON observations.user_id = features.user_id
|
|
109
|
+
AND observations.timestamp >= features.feature_timestamp;
|
|
110
|
+
```
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: webrtc-agent-gateway
|
|
3
|
+
description: Architect and deploy ultra-low latency WebRTC audio duplex gateways, Opus audio transcoding, STUN/TURN ICE candidate negotiation, and real-time voice streaming for Gemini Live pair programming.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# WebRTC Agent Gateway (Ultra-Low Latency Duplex Voice Streaming)
|
|
7
|
+
|
|
8
|
+
Architects, secures, and deploys production-grade WebRTC media gateways that bridge browser/IDE client media streams directly into the Google Gemini Live API. Implements bidirectional Opus/PCM audio transcoding, interactive data channels, STUN/TURN NAT traversal, and jitter-buffer optimization for sub-200ms voice pair-programming.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## 1. WebRTC Duplex Architecture
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
16
|
+
│ WEBRTC MEDIA GATEWAY TOPOLOGY │
|
|
17
|
+
│ │
|
|
18
|
+
│ ┌─────────────────────┐ WebRTC PeerConnection ┌────────────────┐ │
|
|
19
|
+
│ │ Developer Browser │◄──────────────────────────────►│ WebRTC Gateway │ │
|
|
20
|
+
│ │ / Antigravity IDE │ SRTP / Opus Audio Tracks │ (aiortc / Go) │ │
|
|
21
|
+
│ └─────────────────────┘ SCTP DataChannel (Events) └───────┬────────┘ │
|
|
22
|
+
│ │ │ │
|
|
23
|
+
│ │ SDP Offer / Answer (HTTPS / WSS) │ │
|
|
24
|
+
│ ▼ ▼ │
|
|
25
|
+
│ ┌─────────────────────┐ ┌────────────────────┐ │
|
|
26
|
+
│ │ Coturn STUN / TURN │ │ Google Gemini Live │ │
|
|
27
|
+
│ │ NAT Traversal Relay │ │ WebSocket Endpoint │ │
|
|
28
|
+
│ └─────────────────────┘ └────────────────────┘ │
|
|
29
|
+
└─────────────────────────────────────────────────────────────────────────────┘
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## 2. Python aiortc WebRTC Gateway Implementation
|
|
35
|
+
|
|
36
|
+
Below is a production-grade WebRTC audio bridge receiving developer microphone tracks, transcoding Opus to PCM 16kHz for Gemini Live, and streaming back synthesized agent speech:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import asyncio
|
|
40
|
+
import json
|
|
41
|
+
import fractions
|
|
42
|
+
import time
|
|
43
|
+
from aiortc import RTCPeerConnection, RTCSessionDescription, MediaStreamTrack
|
|
44
|
+
from aiortc.contrib.media import MediaBlackhole
|
|
45
|
+
from av import AudioResampler, AudioFrame
|
|
46
|
+
from google import genai
|
|
47
|
+
from google.genai import types
|
|
48
|
+
|
|
49
|
+
class GeminiLiveAudioTrack(MediaStreamTrack):
|
|
50
|
+
"""Generates outgoing WebRTC audio frames from Gemini Live synthesized speech."""
|
|
51
|
+
kind = "audio"
|
|
52
|
+
|
|
53
|
+
def __init__(self):
|
|
54
|
+
super().__init__()
|
|
55
|
+
self.queue = asyncio.Queue()
|
|
56
|
+
self._sample_rate = 48000
|
|
57
|
+
self._samples_per_frame = 960 # 20ms at 48kHz
|
|
58
|
+
self._pts = 0
|
|
59
|
+
|
|
60
|
+
def push_pcm_bytes(self, pcm_data: bytes):
|
|
61
|
+
"""Pushes raw 24kHz/16kHz PCM audio bytes from Gemini into the WebRTC audio queue."""
|
|
62
|
+
self.queue.put_nowait(pcm_data)
|
|
63
|
+
|
|
64
|
+
async def recv(self):
|
|
65
|
+
pcm_chunk = await self.queue.get()
|
|
66
|
+
frame = AudioFrame(format="s16", layout="mono", samples=self._samples_per_frame)
|
|
67
|
+
frame.planes[0].update(pcm_chunk[:frame.linesizes[0]])
|
|
68
|
+
frame.sample_rate = self._sample_rate
|
|
69
|
+
frame.time_base = fractions.Fraction(1, self._sample_rate)
|
|
70
|
+
frame.pts = self._pts
|
|
71
|
+
self._pts += self._samples_per_frame
|
|
72
|
+
return frame
|
|
73
|
+
|
|
74
|
+
class WebRTCAgentGateway:
|
|
75
|
+
def __init__(self, gemini_api_key: str):
|
|
76
|
+
self.client = genai.Client(api_key=gemini_api_key)
|
|
77
|
+
self.pcs = set()
|
|
78
|
+
|
|
79
|
+
async def handle_offer(self, sdp_offer: str, sdp_type: str = "offer") -> dict:
|
|
80
|
+
pc = RTCPeerConnection()
|
|
81
|
+
self.pcs.add(pc)
|
|
82
|
+
|
|
83
|
+
outgoing_audio = GeminiLiveAudioTrack()
|
|
84
|
+
pc.addTrack(outgoing_audio)
|
|
85
|
+
|
|
86
|
+
@pc.on("track")
|
|
87
|
+
def on_track(track):
|
|
88
|
+
if track.kind == "audio":
|
|
89
|
+
asyncio.create_task(self._relay_to_gemini(track, outgoing_audio))
|
|
90
|
+
|
|
91
|
+
@pc.on("connectionstatechange")
|
|
92
|
+
async def on_connectionstatechange():
|
|
93
|
+
if pc.connectionState in ["failed", "closed"]:
|
|
94
|
+
await pc.close()
|
|
95
|
+
self.pcs.discard(pc)
|
|
96
|
+
|
|
97
|
+
offer = RTCSessionDescription(sdp=sdp_offer, type=sdp_type)
|
|
98
|
+
await pc.setRemoteDescription(offer)
|
|
99
|
+
answer = await pc.createAnswer()
|
|
100
|
+
await pc.setLocalDescription(answer)
|
|
101
|
+
|
|
102
|
+
return {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}
|
|
103
|
+
|
|
104
|
+
async def _relay_to_gemini(self, track: MediaStreamTrack, outgoing_audio: GeminiLiveAudioTrack):
|
|
105
|
+
resampler = AudioResampler(format="s16", layout="mono", rate=16000)
|
|
106
|
+
async with self.client.aio.live.connect(
|
|
107
|
+
model="gemini-2.0-flash-exp",
|
|
108
|
+
config=types.LiveConnectConfig(
|
|
109
|
+
response_modalities=[types.LiveModality.AUDIO],
|
|
110
|
+
speech_config=types.SpeechConfig(
|
|
111
|
+
voice_config=types.VoiceConfig(
|
|
112
|
+
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Aoede")
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
) as session:
|
|
117
|
+
# Task to read synthesized audio from Gemini and queue to WebRTC
|
|
118
|
+
async def receive_from_gemini():
|
|
119
|
+
async for response in session.receive():
|
|
120
|
+
server_content = response.server_content
|
|
121
|
+
if server_content and server_content.model_turn:
|
|
122
|
+
for part in server_content.model_turn.parts:
|
|
123
|
+
if part.inline_data:
|
|
124
|
+
outgoing_audio.push_pcm_bytes(part.inline_data.data)
|
|
125
|
+
|
|
126
|
+
receiver_task = asyncio.create_task(receive_from_gemini())
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
while True:
|
|
130
|
+
frame = await track.recv()
|
|
131
|
+
resampled = resampler.resample(frame)
|
|
132
|
+
for r_frame in resampled:
|
|
133
|
+
pcm_bytes = r_frame.planes[0].to_bytes()
|
|
134
|
+
await session.send(input={"data": pcm_bytes, "mime_type": "audio/pcm;rate=16000"})
|
|
135
|
+
except asyncio.CancelledError:
|
|
136
|
+
receiver_task.cancel()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## 3. Client WebRTC SDP Exchange & ICE Configuration
|
|
142
|
+
|
|
143
|
+
```typescript
|
|
144
|
+
export async function initializeVoiceSession(gatewayUrl: string): Promise<RTCPeerConnection> {
|
|
145
|
+
const pc = new RTCPeerConnection({
|
|
146
|
+
iceServers: [
|
|
147
|
+
{ urls: 'stun:stun.l.google.com:19302' },
|
|
148
|
+
{
|
|
149
|
+
urls: 'turn:turn.enterprise-antigravity.internal:3478',
|
|
150
|
+
username: 'agent-dev',
|
|
151
|
+
credential: 'ephemeral-turn-token'
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// Capture developer microphone stream
|
|
157
|
+
const micStream = await navigator.mediaDevices.getUserMedia({
|
|
158
|
+
audio: {
|
|
159
|
+
channelCount: 1,
|
|
160
|
+
sampleRate: 48000,
|
|
161
|
+
echoCancellation: true,
|
|
162
|
+
noiseSuppression: true,
|
|
163
|
+
autoGainControl: true
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
micStream.getAudioTracks().forEach(track => pc.addTrack(track, micStream));
|
|
168
|
+
|
|
169
|
+
// Audio track speaker output
|
|
170
|
+
pc.ontrack = (event) => {
|
|
171
|
+
if (event.track.kind === 'audio') {
|
|
172
|
+
const audioEl = new Audio();
|
|
173
|
+
audioEl.srcObject = event.streams[0];
|
|
174
|
+
audioEl.play().catch(console.error);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const offer = await pc.createOffer();
|
|
179
|
+
await pc.setLocalDescription(offer);
|
|
180
|
+
|
|
181
|
+
const response = await fetch(`${gatewayUrl}/api/webrtc/offer`, {
|
|
182
|
+
method: 'POST',
|
|
183
|
+
headers: { 'Content-Type': 'application/json' },
|
|
184
|
+
body: JSON.stringify({ sdp: offer.sdp, type: offer.type })
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
const answer = await response.json();
|
|
188
|
+
await pc.setRemoteDescription(new RTCSessionDescription(answer));
|
|
189
|
+
return pc;
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## 4. Operational Best Practices & SLA Targets
|
|
196
|
+
|
|
197
|
+
1. **Jitter-Buffer Tuning**: Target 40ms to 80ms playout delay. Avoid buffer bloating which degrades conversational turn-taking.
|
|
198
|
+
2. **STUN/TURN High Availability**: Deploy Coturn behind Network Load Balancers (NLB) across at least 2 GCP availability zones.
|
|
199
|
+
3. **Graceful Teardown**: Intercept `connectionstatechange` to immediately close Gemini WebSocket sessions on client hangup.
|