File size: 4,619 Bytes
bcc0784
 
 
 
3f392e0
 
bcc0784
 
 
 
 
 
 
 
 
b891612
bcc0784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f392e0
bcc0784
 
3f392e0
bcc0784
 
 
3f392e0
 
 
 
bcc0784
 
3f392e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcc0784
 
3f392e0
 
 
 
 
 
 
bcc0784
 
 
 
 
 
 
3f392e0
bcc0784
3f392e0
bcc0784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f392e0
bcc0784
 
 
3f392e0
bcc0784
 
 
3f392e0
bcc0784
 
 
 
 
3f392e0
bcc0784
3f392e0
b891612
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
"""
Jarvis AI Automation Planner — Hugging Face Space Application

Exposes two interfaces:
  1. Gradio chat UI at /  (browser testing)
  2. OpenAI-compatible  POST /v1/chat/completions  (mobile clients)
"""

import json
import logging
import os
import time
import uuid

import gradio as gr
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from jarvis.agent import JarvisAgent
from jarvis.tools import ToolRegistry

# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(name)-20s  %(levelname)-7s  %(message)s",
)
logger = logging.getLogger("jarvis.app")

# ---------------------------------------------------------------------------
# Initialise agent (loaded once at startup)
# ---------------------------------------------------------------------------
registry = ToolRegistry()
agent = JarvisAgent(registry=registry)
logger.info("Jarvis agent ready  •  model=%s  •  tools=%s", agent.model, registry.tool_names())

# ---------------------------------------------------------------------------
# Gradio chat interface
# ---------------------------------------------------------------------------


def chat_fn(message: str, _history: list) -> str:
    """Gradio handler — takes a user message and returns the JSON plan."""
    plan = agent.plan(message)
    return json.dumps(plan, indent=2)


demo = gr.ChatInterface(
    fn=chat_fn,
    title="🤖 Jarvis — AI Automation Planner",
    description=(
        "Type a command (e.g. *\"download a galaxy image\"*) and Jarvis will "
        "return a structured JSON automation plan for your mobile device."
    ),
    examples=[
        "Download a galaxy image",
        "Open YouTube",
        "Search water bottle for boys",
        "Download a galaxy image and send it to Arun",
        "Set an alarm for 7 AM",
        "Search Google for latest AI news",
    ],
    type="messages",
)

# ---------------------------------------------------------------------------
# Custom FastAPI routes (mounted alongside Gradio)
# ---------------------------------------------------------------------------

app = FastAPI(title="Jarvis – AI Automation Planner", version="1.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.post("/v1/chat/completions")
async def chat_completions(request: Request):
    """OpenAI-compatible chat completions endpoint for mobile clients."""
    try:
        body = await request.json()
    except Exception:
        return JSONResponse({"error": "Invalid JSON body."}, status_code=400)

    messages = body.get("messages", [])
    if not messages:
        return JSONResponse({"error": "No messages provided."}, status_code=400)

    user_msg = ""
    for m in reversed(messages):
        if m.get("role") == "user":
            user_msg = m.get("content", "")
            break

    if not user_msg:
        return JSONResponse({"error": "No user message found."}, status_code=400)

    plan = agent.plan(user_msg)

    return JSONResponse({
        "id": f"chatcmpl-{uuid.uuid4().hex[:12]}",
        "object": "chat.completion",
        "created": int(time.time()),
        "model": agent.model,
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": json.dumps(plan),
                },
                "finish_reason": "stop",
            }
        ],
        "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
    })


@app.get("/v1/models")
async def list_models():
    return {
        "object": "list",
        "data": [{"id": agent.model, "object": "model", "owned_by": "jarvis"}],
    }


@app.get("/health")
async def health():
    return {"status": "ok", "model": agent.model, "tools": registry.tool_names()}


# ---------------------------------------------------------------------------
# Mount Gradio onto the FastAPI app at root
# ---------------------------------------------------------------------------
app = gr.mount_gradio_app(app, demo, path="/")

# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=7860, log_level="info")