arimatch1 commited on
Commit
f0df9cb
·
0 Parent(s):

Squashed: deploy code_assistant

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN pip install --no-cache-dir \
6
+ fastapi uvicorn httpx litellm google-generativeai
7
+
8
+ COPY demo_agents/__init__.py demo_agents/__init__.py
9
+ COPY demo_agents/base.py demo_agents/base.py
10
+ COPY demo_agents/code_assistant/__init__.py demo_agents/code_assistant/__init__.py
11
+ COPY demo_agents/code_assistant/agent.py demo_agents/code_assistant/agent.py
12
+
13
+ USER 1000
14
+
15
+ ENV PORT=7860
16
+ EXPOSE 7860
17
+
18
+ CMD ["uvicorn", "demo_agents.code_assistant.agent:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: CrewHub Agent - Code Assistant
3
+ emoji: 💻
4
+ colorFrom: purple
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ A2A-compatible Code Assistant agent for the CrewHub marketplace.
12
+ Returns syntax-highlighted code blocks and side-by-side diffs via A2UI protocol.
demo_agents/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Copyright (c) 2026 CrewHub. All rights reserved.
2
+ # Proprietary and confidential. See LICENSE for details.
demo_agents/base.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CrewHub. All rights reserved.
2
+ # Proprietary and confidential. See LICENSE for details.
3
+ """Shared A2A protocol handler for demo agents.
4
+
5
+ Provides a factory function that creates a FastAPI app implementing the
6
+ Google A2A (Agent-to-Agent) protocol with:
7
+ - GET /.well-known/agent-card.json -- agent card discovery
8
+ - POST / -- JSON-RPC 2.0 dispatch
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ import uuid
16
+ from dataclasses import dataclass, field
17
+
18
+ # Ensure Ollama uses 127.0.0.1 to avoid DNS/async resolution issues with litellm
19
+ if not os.environ.get("OLLAMA_API_BASE"):
20
+ os.environ["OLLAMA_API_BASE"] = "http://127.0.0.1:11434"
21
+ from datetime import datetime, timezone
22
+ from typing import Any, AsyncGenerator, Callable, Awaitable
23
+
24
+ from fastapi import FastAPI, Request
25
+ from fastapi.responses import JSONResponse, StreamingResponse
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Types used by handler functions
30
+ # ---------------------------------------------------------------------------
31
+
32
+ class MessagePart:
33
+ """Lightweight mirror of the marketplace MessagePart schema."""
34
+
35
+ def __init__(self, type: str, content: str | None = None, data: dict | None = None, mime_type: str | None = None, text: str | None = None):
36
+ self.type = type
37
+ # A2A spec uses "text"; our internal convention uses "content". Accept both.
38
+ self.content = content or text
39
+ self.data = data
40
+ self.mime_type = mime_type
41
+
42
+ def to_dict(self) -> dict:
43
+ d: dict[str, Any] = {"type": self.type}
44
+ if self.content is not None:
45
+ d["content"] = self.content
46
+ if self.data is not None:
47
+ d["data"] = self.data
48
+ if self.mime_type is not None:
49
+ d["mime_type"] = self.mime_type
50
+ return d
51
+
52
+
53
+ class TaskMessage:
54
+ def __init__(self, role: str, parts: list[MessagePart]):
55
+ self.role = role
56
+ self.parts = parts
57
+
58
+ @classmethod
59
+ def from_dict(cls, d: dict) -> "TaskMessage":
60
+ parts = [MessagePart(**p) for p in d.get("parts", [])]
61
+ return cls(role=d["role"], parts=parts)
62
+
63
+ def to_dict(self) -> dict:
64
+ return {"role": self.role, "parts": [p.to_dict() for p in self.parts]}
65
+
66
+
67
+ class Artifact:
68
+ def __init__(
69
+ self,
70
+ name: str | None = None,
71
+ parts: list[MessagePart] | None = None,
72
+ metadata: dict | None = None,
73
+ ui_components: list[dict] | None = None,
74
+ ):
75
+ self.name = name
76
+ self.parts = parts or []
77
+ self.metadata = metadata or {}
78
+ self.ui_components = ui_components or []
79
+
80
+ def to_dict(self) -> dict:
81
+ d = {
82
+ "name": self.name,
83
+ "parts": [p.to_dict() for p in self.parts],
84
+ "metadata": self.metadata,
85
+ }
86
+ if self.ui_components:
87
+ d["ui_components"] = self.ui_components
88
+ return d
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # A2UI helpers — create structured UI components for rich rendering
93
+ # ---------------------------------------------------------------------------
94
+
95
+ def emit_table(title: str, headers: list[str], rows: list[list], caption: str | None = None) -> dict:
96
+ """Create a table UI component."""
97
+ return {"type": "table", "title": title, "data": {"headers": headers, "rows": rows, "caption": caption}, "metadata": {}}
98
+
99
+ def emit_chart(title: str, chart_type: str, labels: list[str], datasets: list[dict]) -> dict:
100
+ """Create a chart UI component (bar, line, pie, area)."""
101
+ return {"type": "chart", "title": title, "data": {"chart_type": chart_type, "labels": labels, "datasets": datasets}, "metadata": {}}
102
+
103
+ def emit_code(code: str, language: str, filename: str | None = None, title: str | None = None) -> dict:
104
+ """Create a syntax-highlighted code block UI component."""
105
+ return {"type": "code_block", "title": title or filename, "data": {"code": code, "language": language, "filename": filename}, "metadata": {}}
106
+
107
+ def emit_diff(before: str, after: str, language: str | None = None, title: str | None = None) -> dict:
108
+ """Create a side-by-side diff UI component."""
109
+ return {"type": "diff", "title": title, "data": {"before": before, "after": after, "language": language}, "metadata": {}}
110
+
111
+ def emit_image(url: str, alt: str | None = None, title: str | None = None) -> dict:
112
+ """Create an image UI component."""
113
+ return {"type": "image", "title": title, "data": {"url": url, "alt": alt}, "metadata": {}}
114
+
115
+
116
+ # Handler signature:
117
+ # async def handler(skill_id: str, messages: list[TaskMessage]) -> list[Artifact]
118
+ HandlerFunc = Callable[[str, list[TaskMessage]], Awaitable[list[Artifact]]]
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # AG-UI Streaming types
123
+ # ---------------------------------------------------------------------------
124
+
125
+ @dataclass
126
+ class StreamChunk:
127
+ """A single chunk emitted by a streaming agent handler.
128
+
129
+ Types:
130
+ - "thinking" — agent reasoning (shown collapsed in UI)
131
+ - "text" — partial text output (appended progressively)
132
+ - "artifact" — complete artifact (rendered when received)
133
+ - "status" — status change (e.g. "working")
134
+ - "error" — error message
135
+ - "done" — final signal with optional artifact list
136
+ """
137
+ type: str # thinking | text | artifact | status | error | done
138
+ content: str = ""
139
+ artifact: Artifact | None = None
140
+ artifacts: list[Artifact] | None = None # used with "done" to send all final artifacts
141
+ metadata: dict = field(default_factory=dict)
142
+
143
+ def to_sse(self) -> str:
144
+ """Serialize to SSE event format."""
145
+ import json
146
+ data: dict[str, Any] = {"type": self.type}
147
+ if self.content:
148
+ data["content"] = self.content
149
+ if self.artifact:
150
+ data["artifact"] = self.artifact.to_dict()
151
+ if self.artifacts:
152
+ data["artifacts"] = [a.to_dict() for a in self.artifacts]
153
+ if self.metadata:
154
+ data["metadata"] = self.metadata
155
+ return f"event: {self.type}\ndata: {json.dumps(data)}\n\n"
156
+
157
+
158
+ # Streaming handler signature — yields StreamChunks instead of returning artifacts
159
+ StreamingHandlerFunc = Callable[
160
+ [str, list[TaskMessage]],
161
+ AsyncGenerator[StreamChunk, None],
162
+ ]
163
+
164
+ logger = logging.getLogger(__name__)
165
+
166
+
167
+ async def _ollama_call(
168
+ model_name: str,
169
+ system_prompt: str,
170
+ user_message: str,
171
+ ) -> str:
172
+ """Call Ollama directly via httpx (bypasses LiteLLM async issues)."""
173
+ import httpx
174
+
175
+ base = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434")
176
+ messages = [
177
+ {"role": "system", "content": system_prompt},
178
+ {"role": "user", "content": user_message},
179
+ ]
180
+ # connect quickly, but allow up to 5min for generation on slow hardware
181
+ timeout = httpx.Timeout(connect=10.0, read=300.0, write=10.0, pool=10.0)
182
+ async with httpx.AsyncClient(timeout=timeout) as client:
183
+ resp = await client.post(
184
+ f"{base}/api/chat",
185
+ json={"model": model_name, "messages": messages, "stream": False},
186
+ )
187
+ resp.raise_for_status()
188
+ return resp.json()["message"]["content"]
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Multi-provider LLM Router (built once at import time)
193
+ # ---------------------------------------------------------------------------
194
+
195
+ # Provider definitions: (env_var, model_string, rpm_limit)
196
+ _PROVIDER_DEFS = [
197
+ ("GROQ_API_KEY", "groq/llama-3.3-70b-versatile", 30),
198
+ ("CEREBRAS_API_KEY", "cerebras/llama-3.3-70b", 30),
199
+ ("SAMBANOVA_API_KEY", "sambanova/Meta-Llama-3.3-70B-Instruct", 20),
200
+ ("GEMINI_API_KEY", "gemini/gemini-2.0-flash", 15),
201
+ ]
202
+
203
+ _router = None # Lazy-initialized on first call
204
+
205
+
206
+ def _build_router():
207
+ """Build a LiteLLM Router from available API keys. Returns None if no keys."""
208
+ try:
209
+ from litellm import Router
210
+ except ImportError:
211
+ return None
212
+
213
+ model_list = []
214
+ for env_var, model_str, rpm in _PROVIDER_DEFS:
215
+ key = os.environ.get(env_var)
216
+ if key:
217
+ model_list.append({
218
+ "model_name": "agent-llm",
219
+ "litellm_params": {
220
+ "model": model_str,
221
+ "api_key": key,
222
+ "rpm": rpm,
223
+ },
224
+ })
225
+
226
+ if not model_list:
227
+ return None
228
+
229
+ providers = [m["litellm_params"]["model"] for m in model_list]
230
+ logger.info("LLM Router initialized with %d providers: %s", len(model_list), providers)
231
+
232
+ return Router(
233
+ model_list=model_list,
234
+ num_retries=2,
235
+ timeout=30,
236
+ allowed_fails=3,
237
+ cooldown_time=60,
238
+ retry_after=1,
239
+ )
240
+
241
+
242
+ async def llm_call(
243
+ system_prompt: str,
244
+ user_message: str,
245
+ model: str | None = None,
246
+ ) -> str:
247
+ """Call an LLM with automatic multi-provider fallback.
248
+
249
+ Uses LiteLLM Router to load-balance across available providers and
250
+ automatically retry on 429/500 errors. Falls back to single-model
251
+ call if MODEL env var is set explicitly, or echo if nothing works.
252
+ """
253
+ global _router
254
+ explicit_model = model or os.environ.get("MODEL")
255
+
256
+ # Ollama: bypass router entirely
257
+ if explicit_model and explicit_model.lower().startswith("ollama/"):
258
+ try:
259
+ return await _ollama_call(explicit_model.split("/", 1)[1], system_prompt, user_message)
260
+ except Exception as exc:
261
+ logger.warning("Ollama call failed: %s: %s", type(exc).__name__, exc)
262
+ return f"[LLM unavailable — echoing input]\n\n{user_message}"
263
+
264
+ messages = [
265
+ {"role": "system", "content": system_prompt},
266
+ {"role": "user", "content": user_message},
267
+ ]
268
+
269
+ # Try Router first (multi-provider with automatic failover)
270
+ if _router is None:
271
+ _router = _build_router() or False # False = no keys available
272
+ if _router:
273
+ try:
274
+ response = await _router.acompletion(model="agent-llm", messages=messages)
275
+ return response.choices[0].message.content
276
+ except Exception as exc:
277
+ logger.warning("Router call failed: %s: %s", type(exc).__name__, exc)
278
+
279
+ # Fallback: direct single-model call (if MODEL env var set)
280
+ if explicit_model:
281
+ try:
282
+ import litellm
283
+ response = await litellm.acompletion(
284
+ model=explicit_model, messages=messages, timeout=60,
285
+ )
286
+ return response.choices[0].message.content
287
+ except Exception as exc:
288
+ logger.warning("Direct LLM call failed (%s): %s: %s", explicit_model, type(exc).__name__, exc)
289
+
290
+ return f"[LLM unavailable — echoing input]\n\n{user_message}"
291
+
292
+
293
+ async def llm_call_streaming(
294
+ system_prompt: str,
295
+ user_message: str,
296
+ model: str | None = None,
297
+ ) -> AsyncGenerator[str, None]:
298
+ """Streaming version of llm_call — yields text chunks as they arrive.
299
+
300
+ Falls back to non-streaming llm_call if streaming is unavailable.
301
+ """
302
+ global _router
303
+ explicit_model = model or os.environ.get("MODEL")
304
+
305
+ # Ollama: stream via httpx
306
+ if explicit_model and explicit_model.lower().startswith("ollama/"):
307
+ import httpx
308
+ base = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434")
309
+ messages = [
310
+ {"role": "system", "content": system_prompt},
311
+ {"role": "user", "content": user_message},
312
+ ]
313
+ timeout = httpx.Timeout(connect=10.0, read=300.0, write=10.0, pool=10.0)
314
+ async with httpx.AsyncClient(timeout=timeout) as client:
315
+ async with client.stream(
316
+ "POST",
317
+ f"{base}/api/chat",
318
+ json={"model": explicit_model.split("/", 1)[1], "messages": messages, "stream": True},
319
+ ) as resp:
320
+ resp.raise_for_status()
321
+ import json
322
+ async for line in resp.aiter_lines():
323
+ if line.strip():
324
+ try:
325
+ chunk = json.loads(line)
326
+ content = chunk.get("message", {}).get("content", "")
327
+ if content:
328
+ yield content
329
+ except (ValueError, KeyError):
330
+ pass
331
+ return
332
+
333
+ messages = [
334
+ {"role": "system", "content": system_prompt},
335
+ {"role": "user", "content": user_message},
336
+ ]
337
+
338
+ # Try Router streaming first
339
+ if _router is None:
340
+ _router = _build_router() or False
341
+ if _router:
342
+ try:
343
+ response = await _router.acompletion(
344
+ model="agent-llm", messages=messages, stream=True,
345
+ )
346
+ async for chunk in response:
347
+ delta = chunk.choices[0].delta
348
+ if delta and delta.content:
349
+ yield delta.content
350
+ return
351
+ except Exception as exc:
352
+ logger.warning("Router streaming failed: %s: %s", type(exc).__name__, exc)
353
+
354
+ # Fallback: direct single-model streaming
355
+ if explicit_model:
356
+ try:
357
+ import litellm
358
+ response = await litellm.acompletion(
359
+ model=explicit_model, messages=messages, timeout=60, stream=True,
360
+ )
361
+ async for chunk in response:
362
+ delta = chunk.choices[0].delta
363
+ if delta and delta.content:
364
+ yield delta.content
365
+ return
366
+ except Exception as exc:
367
+ logger.warning("Direct LLM streaming failed (%s): %s: %s", explicit_model, type(exc).__name__, exc)
368
+
369
+ # Last resort: yield the full non-streaming response as one chunk
370
+ result = await llm_call(system_prompt, user_message, model)
371
+ yield result
372
+
373
+
374
+ # In-memory task store shared within one process
375
+ _task_store: dict[str, dict] = {}
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # Factory
380
+ # ---------------------------------------------------------------------------
381
+
382
+ def create_a2a_app(
383
+ name: str,
384
+ description: str,
385
+ version: str,
386
+ skills: list[dict],
387
+ handler_func: HandlerFunc,
388
+ port: int,
389
+ credits_per_task: float = 1,
390
+ streaming_handler_func: StreamingHandlerFunc | None = None,
391
+ ) -> FastAPI:
392
+ """Create a FastAPI app that speaks the A2A protocol.
393
+
394
+ Parameters
395
+ ----------
396
+ name:
397
+ Human-readable agent name.
398
+ description:
399
+ Short description shown in the agent card.
400
+ version:
401
+ Semantic version string.
402
+ skills:
403
+ List of skill dicts following the A2A agent-card skill schema.
404
+ handler_func:
405
+ Async callable ``(skill_id, messages) -> list[Artifact]``.
406
+ port:
407
+ Port number the agent listens on (used for the agent card URL).
408
+ credits_per_task:
409
+ Credit cost advertised for every task handled by this agent.
410
+ streaming_handler_func:
411
+ Optional async generator ``(skill_id, messages) -> StreamChunk``.
412
+ When provided, the agent advertises ``streaming: true`` in its card
413
+ and supports the ``tasks/sendSubscribe`` SSE method.
414
+ """
415
+
416
+ supports_streaming = streaming_handler_func is not None
417
+ app = FastAPI(title=name, version=version)
418
+
419
+ # -- Agent card -----------------------------------------------------------
420
+
421
+ # Use AGENT_URL env var when deployed (e.g. HF Spaces), else localhost
422
+ base_url = os.environ.get("AGENT_URL", f"http://localhost:{port}")
423
+
424
+ agent_card = {
425
+ "name": name,
426
+ "description": description,
427
+ "url": base_url,
428
+ "version": version,
429
+ "capabilities": {
430
+ "streaming": supports_streaming,
431
+ "pushNotifications": False,
432
+ "stateTransitionHistory": False,
433
+ },
434
+ "skills": skills,
435
+ "securitySchemes": [],
436
+ "defaultInputModes": ["text"],
437
+ "defaultOutputModes": ["text"],
438
+ "pricing": {
439
+ "model": "per_task",
440
+ "credits": credits_per_task,
441
+ },
442
+ }
443
+
444
+ @app.get("/.well-known/agent-card.json")
445
+ async def get_agent_card():
446
+ return agent_card
447
+
448
+ # -- JSON-RPC 2.0 dispatch -----------------------------------------------
449
+
450
+ @app.post("/")
451
+ async def jsonrpc_dispatch(request: Request):
452
+ body = await request.json()
453
+
454
+ jsonrpc = body.get("jsonrpc", "2.0")
455
+ method = body.get("method")
456
+ params = body.get("params", {})
457
+ req_id = body.get("id")
458
+
459
+ if method == "tasks/send":
460
+ return await _handle_send(params, req_id, jsonrpc)
461
+ elif method == "tasks/get":
462
+ return await _handle_get(params, req_id, jsonrpc)
463
+ elif method == "tasks/cancel":
464
+ return await _handle_cancel(params, req_id, jsonrpc)
465
+ elif method == "tasks/sendSubscribe":
466
+ return await _handle_send_subscribe(params, req_id, jsonrpc)
467
+ else:
468
+ return _error_response(req_id, -32601, f"Method not found: {method}", jsonrpc)
469
+
470
+ # -- tasks/send -----------------------------------------------------------
471
+
472
+ async def _handle_send(params: dict, req_id: Any, jsonrpc: str):
473
+ try:
474
+ task_id = params.get("id") or str(uuid.uuid4())
475
+ metadata = params.get("metadata", {})
476
+ skill_id = params.get("skill_id") or metadata.get("skill_id") or _default_skill_id()
477
+ raw_messages = params.get("message", params.get("messages", []))
478
+
479
+ # Accept a single message dict or a list of messages
480
+ if isinstance(raw_messages, dict):
481
+ raw_messages = [raw_messages]
482
+ messages = [TaskMessage.from_dict(m) for m in raw_messages]
483
+
484
+ # Resolve skill_id from first message if caller put it there
485
+ if not skill_id:
486
+ skill_id = _default_skill_id()
487
+
488
+ # Execute
489
+ artifacts = await handler_func(skill_id, messages)
490
+
491
+ task = {
492
+ "id": task_id,
493
+ "status": {"state": "completed"},
494
+ "messages": [m.to_dict() for m in messages],
495
+ "artifacts": [a.to_dict() for a in artifacts],
496
+ "metadata": {
497
+ "credits_charged": credits_per_task,
498
+ "completed_at": datetime.now(timezone.utc).isoformat(),
499
+ },
500
+ }
501
+ _task_store[task_id] = task
502
+
503
+ return JSONResponse(content={
504
+ "jsonrpc": jsonrpc,
505
+ "id": req_id,
506
+ "result": task,
507
+ })
508
+ except Exception as exc:
509
+ return _error_response(req_id, -32000, str(exc), jsonrpc)
510
+
511
+ # -- tasks/sendSubscribe (AG-UI streaming) --------------------------------
512
+
513
+ async def _handle_send_subscribe(params: dict, req_id: Any, jsonrpc: str):
514
+ """Stream task execution via Server-Sent Events.
515
+
516
+ If a streaming_handler_func was provided, yields chunks in real-time.
517
+ Otherwise falls back to running handler_func and emitting the result
518
+ as a single artifact event.
519
+ """
520
+ import json as _json
521
+
522
+ task_id = params.get("id") or str(uuid.uuid4())
523
+ metadata = params.get("metadata", {})
524
+ skill_id = params.get("skill_id") or metadata.get("skill_id") or _default_skill_id()
525
+ raw_messages = params.get("message", params.get("messages", []))
526
+ if isinstance(raw_messages, dict):
527
+ raw_messages = [raw_messages]
528
+ messages = [TaskMessage.from_dict(m) for m in raw_messages]
529
+
530
+ async def _stream_generator():
531
+ # Emit initial status
532
+ yield StreamChunk(type="status", content="working").to_sse()
533
+
534
+ try:
535
+ if streaming_handler_func is not None:
536
+ # True streaming — yield each chunk from the handler
537
+ final_artifacts: list[Artifact] = []
538
+ accumulated_text = ""
539
+
540
+ async for chunk in streaming_handler_func(skill_id, messages):
541
+ yield chunk.to_sse()
542
+
543
+ # Track artifacts for final task store
544
+ if chunk.type == "artifact" and chunk.artifact:
545
+ final_artifacts.append(chunk.artifact)
546
+ elif chunk.type == "text":
547
+ accumulated_text += chunk.content
548
+ elif chunk.type == "done" and chunk.artifacts:
549
+ final_artifacts = chunk.artifacts
550
+
551
+ # If no explicit artifacts were emitted, create one from accumulated text
552
+ if not final_artifacts and accumulated_text:
553
+ final_artifacts = [Artifact(
554
+ name="response",
555
+ parts=[MessagePart(type="text", content=accumulated_text)],
556
+ metadata={"skill": skill_id, "streamed": True},
557
+ )]
558
+
559
+ # Emit done with final artifacts
560
+ done_chunk = StreamChunk(
561
+ type="done",
562
+ artifacts=final_artifacts,
563
+ metadata={"credits_charged": credits_per_task},
564
+ )
565
+ yield done_chunk.to_sse()
566
+
567
+ else:
568
+ # Non-streaming fallback — run handler, emit result as single event
569
+ artifacts = await handler_func(skill_id, messages)
570
+ for artifact in artifacts:
571
+ yield StreamChunk(type="artifact", artifact=artifact).to_sse()
572
+ yield StreamChunk(
573
+ type="done",
574
+ artifacts=artifacts,
575
+ metadata={"credits_charged": credits_per_task},
576
+ ).to_sse()
577
+
578
+ except Exception as exc:
579
+ logger.exception("Streaming handler error")
580
+ yield StreamChunk(type="error", content=str(exc)).to_sse()
581
+
582
+ # Store final task
583
+ task = {
584
+ "id": task_id,
585
+ "status": {"state": "completed"},
586
+ "messages": [m.to_dict() for m in messages],
587
+ "artifacts": [a.to_dict() for a in (final_artifacts if streaming_handler_func else artifacts)],
588
+ "metadata": {
589
+ "credits_charged": credits_per_task,
590
+ "completed_at": datetime.now(timezone.utc).isoformat(),
591
+ },
592
+ }
593
+ _task_store[task_id] = task
594
+
595
+ return StreamingResponse(
596
+ _stream_generator(),
597
+ media_type="text/event-stream",
598
+ headers={
599
+ "Cache-Control": "no-cache",
600
+ "Connection": "keep-alive",
601
+ "X-Accel-Buffering": "no",
602
+ },
603
+ )
604
+
605
+ # -- tasks/get ------------------------------------------------------------
606
+
607
+ async def _handle_get(params: dict, req_id: Any, jsonrpc: str):
608
+ task_id = params.get("id")
609
+ task = _task_store.get(task_id)
610
+ if task is None:
611
+ return _error_response(req_id, -32001, f"Task not found: {task_id}", jsonrpc)
612
+ return JSONResponse(content={
613
+ "jsonrpc": jsonrpc,
614
+ "id": req_id,
615
+ "result": task,
616
+ })
617
+
618
+ # -- tasks/cancel ---------------------------------------------------------
619
+
620
+ async def _handle_cancel(params: dict, req_id: Any, jsonrpc: str):
621
+ task_id = params.get("id")
622
+ task = _task_store.get(task_id)
623
+ if task is None:
624
+ return _error_response(req_id, -32001, f"Task not found: {task_id}", jsonrpc)
625
+ task["status"] = {"state": "canceled"}
626
+ return JSONResponse(content={
627
+ "jsonrpc": jsonrpc,
628
+ "id": req_id,
629
+ "result": task,
630
+ })
631
+
632
+ # -- helpers --------------------------------------------------------------
633
+
634
+ def _default_skill_id() -> str:
635
+ if skills:
636
+ return skills[0]["id"]
637
+ return "default"
638
+
639
+ def _error_response(req_id: Any, code: int, message: str, jsonrpc: str = "2.0"):
640
+ return JSONResponse(content={
641
+ "jsonrpc": jsonrpc,
642
+ "id": req_id,
643
+ "error": {"code": code, "message": message},
644
+ })
645
+
646
+ return app
demo_agents/code_assistant/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Copyright (c) 2026 CrewHub. All rights reserved.
demo_agents/code_assistant/agent.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026 CrewHub. All rights reserved.
2
+ # Proprietary and confidential. See LICENSE for details.
3
+ """Code Assistant Agent — A2UI showcase for code blocks and diffs.
4
+
5
+ Skills:
6
+ - generate-code Generate code with syntax-highlighted output
7
+ - review-code Review code and suggest improvements as diffs
8
+
9
+ Port: 8006
10
+ Credits: 5 per task
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+
18
+ from demo_agents.base import (
19
+ Artifact,
20
+ MessagePart,
21
+ StreamChunk,
22
+ TaskMessage,
23
+ create_a2a_app,
24
+ emit_code,
25
+ emit_diff,
26
+ llm_call,
27
+ llm_call_streaming,
28
+ )
29
+
30
+ PORT = 8006
31
+ CREDITS = 5
32
+
33
+ SKILLS = [
34
+ {
35
+ "id": "generate-code",
36
+ "name": "Generate Code",
37
+ "description": (
38
+ "Generate code snippets with syntax highlighting. "
39
+ "Specify the language and what you need — functions, classes, scripts, configs."
40
+ ),
41
+ "inputModes": ["text"],
42
+ "outputModes": ["text"],
43
+ "examples": [
44
+ {
45
+ "input": "Write a Python function to calculate fibonacci numbers with memoization",
46
+ "output": "A syntax-highlighted Python function with explanation.",
47
+ "description": "Python fibonacci generator",
48
+ },
49
+ ],
50
+ },
51
+ {
52
+ "id": "review-code",
53
+ "name": "Review & Improve Code",
54
+ "description": (
55
+ "Review code and suggest improvements. Returns a side-by-side diff "
56
+ "showing the original and improved version with explanation."
57
+ ),
58
+ "inputModes": ["text"],
59
+ "outputModes": ["text"],
60
+ "examples": [
61
+ {
62
+ "input": "Review this Python code: def add(a,b): return a+b",
63
+ "output": "A diff showing the original vs improved code with type hints and docstring.",
64
+ "description": "Simple function improvement",
65
+ },
66
+ ],
67
+ },
68
+ ]
69
+
70
+ GENERATE_SYSTEM_PROMPT = """You are an expert programmer. Generate clean, well-documented code.
71
+
72
+ You MUST return your response in this exact JSON format (no other text before or after):
73
+ {
74
+ "explanation": "Brief explanation of what the code does and design choices",
75
+ "language": "python",
76
+ "filename": "example.py",
77
+ "code": "def fibonacci(n):\\n pass"
78
+ }
79
+
80
+ Use proper indentation (\\n for newlines, spaces for indentation in the code string).
81
+ The code should be complete, runnable, and follow best practices.
82
+ IMPORTANT: Return ONLY valid JSON, no markdown, no code fences, no text before or after."""
83
+
84
+ REVIEW_SYSTEM_PROMPT = """You are a senior code reviewer. Review the user's code and suggest improvements.
85
+
86
+ You MUST return your response in this exact JSON format (no other text before or after):
87
+ {
88
+ "explanation": "What was improved and why",
89
+ "language": "python",
90
+ "before": "original code here",
91
+ "after": "improved code here"
92
+ }
93
+
94
+ Keep the improved version functionally equivalent but better: add type hints, docstrings,
95
+ error handling, better naming, or performance improvements as appropriate.
96
+ Use \\n for newlines in the code strings.
97
+ IMPORTANT: Return ONLY valid JSON, no markdown, no code fences, no text before or after."""
98
+
99
+
100
+ def _extract_json(text: str) -> dict | None:
101
+ """Best-effort JSON extraction from LLM output."""
102
+ try:
103
+ return json.loads(text.strip())
104
+ except json.JSONDecodeError:
105
+ pass
106
+ m = re.search(r"```(?:json)?\s*\n?(.*?)```", text, re.DOTALL)
107
+ if m:
108
+ try:
109
+ return json.loads(m.group(1).strip())
110
+ except json.JSONDecodeError:
111
+ pass
112
+ m = re.search(r"\{.*\}", text, re.DOTALL)
113
+ if m:
114
+ try:
115
+ return json.loads(m.group(0))
116
+ except json.JSONDecodeError:
117
+ pass
118
+ return None
119
+
120
+
121
+ async def handle(skill_id: str, messages: list[TaskMessage]) -> list[Artifact]:
122
+ text = ""
123
+ for msg in messages:
124
+ for part in msg.parts:
125
+ if part.type == "text" and part.content:
126
+ text += part.content + "\n"
127
+ text = text.strip()
128
+
129
+ if not text:
130
+ return [Artifact(
131
+ name="error",
132
+ parts=[MessagePart(type="text", content="No input provided.")],
133
+ )]
134
+
135
+ if skill_id == "generate-code":
136
+ prompt = GENERATE_SYSTEM_PROMPT
137
+ else:
138
+ prompt = REVIEW_SYSTEM_PROMPT
139
+
140
+ raw = await llm_call(prompt, text)
141
+ data = _extract_json(raw)
142
+
143
+ if not data:
144
+ return [Artifact(
145
+ name="code-output",
146
+ parts=[MessagePart(type="text", content=raw)],
147
+ metadata={"skill": skill_id, "parse_error": True},
148
+ )]
149
+
150
+ explanation = data.get("explanation", "")
151
+ language = data.get("language", "python")
152
+
153
+ if skill_id == "generate-code":
154
+ components = [
155
+ emit_code(
156
+ data.get("code", ""),
157
+ language,
158
+ filename=data.get("filename"),
159
+ title="Generated Code",
160
+ ),
161
+ ]
162
+ else:
163
+ components = [
164
+ emit_diff(
165
+ data.get("before", ""),
166
+ data.get("after", ""),
167
+ language=language,
168
+ title="Code Improvements",
169
+ ),
170
+ ]
171
+
172
+ return [Artifact(
173
+ name="generated-code" if skill_id == "generate-code" else "code-review",
174
+ parts=[MessagePart(type="text", content=explanation)],
175
+ metadata={"skill": skill_id, "language": language},
176
+ ui_components=components,
177
+ )]
178
+
179
+
180
+ async def handle_streaming(skill_id: str, messages: list[TaskMessage]):
181
+ """Streaming version — shows thinking then emits rich components."""
182
+ text = ""
183
+ for msg in messages:
184
+ for part in msg.parts:
185
+ if part.type == "text" and part.content:
186
+ text += part.content + "\n"
187
+ text = text.strip()
188
+
189
+ if not text:
190
+ yield StreamChunk(type="error", content="No input provided.")
191
+ return
192
+
193
+ if skill_id == "generate-code":
194
+ yield StreamChunk(type="thinking", content="Generating code...")
195
+ prompt = GENERATE_SYSTEM_PROMPT
196
+ else:
197
+ yield StreamChunk(type="thinking", content="Reviewing code and preparing improvements...")
198
+ prompt = REVIEW_SYSTEM_PROMPT
199
+
200
+ accumulated = ""
201
+ async for chunk in llm_call_streaming(prompt, text):
202
+ accumulated += chunk
203
+ yield StreamChunk(type="text", content=chunk)
204
+
205
+ data = _extract_json(accumulated)
206
+
207
+ if not data:
208
+ yield StreamChunk(
209
+ type="done",
210
+ artifacts=[Artifact(
211
+ name="code-output",
212
+ parts=[MessagePart(type="text", content=accumulated)],
213
+ metadata={"skill": skill_id, "parse_error": True},
214
+ )],
215
+ )
216
+ return
217
+
218
+ explanation = data.get("explanation", "")
219
+ language = data.get("language", "python")
220
+
221
+ if skill_id == "generate-code":
222
+ components = [
223
+ emit_code(
224
+ data.get("code", ""),
225
+ language,
226
+ filename=data.get("filename"),
227
+ title="Generated Code",
228
+ ),
229
+ ]
230
+ else:
231
+ components = [
232
+ emit_diff(
233
+ data.get("before", ""),
234
+ data.get("after", ""),
235
+ language=language,
236
+ title="Code Improvements",
237
+ ),
238
+ ]
239
+
240
+ yield StreamChunk(
241
+ type="done",
242
+ artifacts=[Artifact(
243
+ name="generated-code" if skill_id == "generate-code" else "code-review",
244
+ parts=[MessagePart(type="text", content=explanation)],
245
+ metadata={"skill": skill_id, "language": language},
246
+ ui_components=components,
247
+ )],
248
+ )
249
+
250
+
251
+ app = create_a2a_app(
252
+ name="Code Assistant",
253
+ description="Generate code and review improvements with syntax highlighting and diffs.",
254
+ version="1.0.0",
255
+ skills=SKILLS,
256
+ handler_func=handle,
257
+ port=PORT,
258
+ credits_per_task=CREDITS,
259
+ streaming_handler_func=handle_streaming,
260
+ )