ApolloAIs commited on
Commit
9be6b43
·
verified ·
1 Parent(s): bbd070b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +83 -27
main.py CHANGED
@@ -1,19 +1,18 @@
1
  import os
2
- import asyncio
3
  from fastapi import FastAPI, Request
4
  from fastapi.staticfiles import StaticFiles
5
  import uvicorn
6
  from playwright.async_api import async_playwright
7
- from openclaw import Agent, Tool
8
 
9
  # --- CONFIG ---
10
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
11
- SPACE_HOST = os.getenv("MY_SPACE_HOST")
12
  STATIC_DIR = "static"
13
 
14
  app = FastAPI()
15
 
16
- # Create static directory if it doesn't exist
17
  if not os.path.exists(STATIC_DIR):
18
  os.makedirs(STATIC_DIR)
19
 
@@ -32,20 +31,86 @@ async def take_screenshot(url: str) -> str:
32
 
33
  return f"Screenshot successful. View it here: https://{SPACE_HOST}/static/screenshot.png"
34
 
35
- tools = [Tool(name="take_screenshot", func=take_screenshot, description="Takes a screenshot of a URL.")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- # --- AGENT ---
38
- agent = Agent(
39
- model="gemini/gemini-2.5-pro",
40
- tools=tools,
41
- system_prompt=(
42
- "You are an expert coding/devops agent. Users interact via a WhatsApp bridge. "
43
- "Keep replies concise and under 1000 chars. Explain before acting. "
44
- "If you take a screenshot, provide the URL clearly."
45
- ),
46
- model_kwargs={"temperature": 0.2, "max_tokens": 8192, "top_p": 0.95}
47
  )
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  # --- ENDPOINTS ---
50
  @app.get("/health")
51
  async def health_check():
@@ -53,13 +118,8 @@ async def health_check():
53
 
54
  @app.api_route("/webhook", methods=["GET", "POST"])
55
  async def wa_webhook(request: Request):
56
- """Universal webhook that handles both GET and POST requests."""
57
- user_msg = ""
58
-
59
- # Try to get message from URL (GET)
60
  user_msg = request.query_params.get("message", "")
61
 
62
- # Try to get message from JSON Body (POST)
63
  if request.method == "POST":
64
  try:
65
  data = await request.json()
@@ -67,14 +127,10 @@ async def wa_webhook(request: Request):
67
  except:
68
  pass
69
 
70
- # Process prompt if it starts with "claw "
71
  if user_msg.lower().startswith("claw "):
72
  prompt = user_msg[5:].strip()
73
- try:
74
- response_text = await agent.arun(prompt)
75
- return {"replies": [{"message": response_text}]}
76
- except Exception as e:
77
- return {"replies": [{"message": f"Agent Error: {str(e)}"}]}
78
 
79
  return {"replies": []}
80
 
 
1
  import os
2
+ import json
3
  from fastapi import FastAPI, Request
4
  from fastapi.staticfiles import StaticFiles
5
  import uvicorn
6
  from playwright.async_api import async_playwright
7
+ from litellm import acompletion
8
 
9
  # --- CONFIG ---
10
+ os.environ["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY", "")
11
+ SPACE_HOST = os.getenv("MY_SPACE_HOST", "")
12
  STATIC_DIR = "static"
13
 
14
  app = FastAPI()
15
 
 
16
  if not os.path.exists(STATIC_DIR):
17
  os.makedirs(STATIC_DIR)
18
 
 
31
 
32
  return f"Screenshot successful. View it here: https://{SPACE_HOST}/static/screenshot.png"
33
 
34
+ tools = [
35
+ {
36
+ "type": "function",
37
+ "function": {
38
+ "name": "take_screenshot",
39
+ "description": "Takes a screenshot of a URL.",
40
+ "parameters": {
41
+ "type": "object",
42
+ "properties": {
43
+ "url": {"type": "string", "description": "The URL to screenshot"}
44
+ },
45
+ "required": ["url"]
46
+ }
47
+ }
48
+ }
49
+ ]
50
 
51
+ system_prompt = (
52
+ "You are an expert coding/devops agent. Users interact via a WhatsApp bridge. "
53
+ "Keep replies concise and under 1000 chars. Explain before acting. "
54
+ "If you take a screenshot, provide the URL clearly."
 
 
 
 
 
 
55
  )
56
 
57
+ # --- NATIVE AGENT ENGINE ---
58
+ async def run_agent(prompt: str) -> str:
59
+ messages = [
60
+ {"role": "system", "content": system_prompt},
61
+ {"role": "user", "content": prompt}
62
+ ]
63
+
64
+ try:
65
+ response = await acompletion(
66
+ model="gemini/gemini-2.5-pro",
67
+ messages=messages,
68
+ tools=tools,
69
+ temperature=0.2
70
+ )
71
+
72
+ msg = response.choices[0].message
73
+
74
+ # Check if the LLM wants to use the screenshot tool
75
+ if hasattr(msg, 'tool_calls') and msg.tool_calls:
76
+ assistant_msg = {"role": "assistant", "content": msg.content or ""}
77
+ assistant_msg["tool_calls"] = [
78
+ {
79
+ "id": tc.id,
80
+ "type": "function",
81
+ "function": {
82
+ "name": tc.function.name,
83
+ "arguments": tc.function.arguments
84
+ }
85
+ } for tc in msg.tool_calls
86
+ ]
87
+ messages.append(assistant_msg)
88
+
89
+ # Execute the tool
90
+ for tool_call in msg.tool_calls:
91
+ if tool_call.function.name == "take_screenshot":
92
+ args = json.loads(tool_call.function.arguments)
93
+ result = await take_screenshot(args["url"])
94
+
95
+ messages.append({
96
+ "role": "tool",
97
+ "tool_call_id": tool_call.id,
98
+ "name": "take_screenshot",
99
+ "content": result
100
+ })
101
+
102
+ # Get the final answer after the screenshot
103
+ final_response = await acompletion(
104
+ model="gemini/gemini-2.5-pro",
105
+ messages=messages,
106
+ temperature=0.2
107
+ )
108
+ return final_response.choices[0].message.content
109
+
110
+ return msg.content or "No response generated."
111
+ except Exception as e:
112
+ return f"Agent Error: {str(e)}"
113
+
114
  # --- ENDPOINTS ---
115
  @app.get("/health")
116
  async def health_check():
 
118
 
119
  @app.api_route("/webhook", methods=["GET", "POST"])
120
  async def wa_webhook(request: Request):
 
 
 
 
121
  user_msg = request.query_params.get("message", "")
122
 
 
123
  if request.method == "POST":
124
  try:
125
  data = await request.json()
 
127
  except:
128
  pass
129
 
 
130
  if user_msg.lower().startswith("claw "):
131
  prompt = user_msg[5:].strip()
132
+ response_text = await run_agent(prompt)
133
+ return {"replies": [{"message": response_text}]}
 
 
 
134
 
135
  return {"replies": []}
136