viraja1 commited on
Commit
5ace4e6
·
verified ·
1 Parent(s): c3144ae

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from dotenv import load_dotenv
5
+ from strands import Agent
6
+ from strands.models.litellm import LiteLLMModel
7
+ from mcp.client.streamable_http import streamablehttp_client
8
+ from strands.tools.mcp.mcp_client import MCPClient
9
+
10
+
11
+ load_dotenv()
12
+ os.environ["STRANDS_TOOL_CONSOLE_MODE"] = "enabled"
13
+
14
+
15
+ def create_streamable_http_transport():
16
+ return streamablehttp_client(os.environ["MCP_SERVER"])
17
+
18
+ streamable_http_mcp_client = MCPClient(create_streamable_http_transport)
19
+
20
+ model = LiteLLMModel(
21
+ client_args={
22
+ "api_key": os.environ["OPENROUTER_API_KEY"],
23
+ "api_base": "https://openrouter.ai/api/v1",
24
+ },
25
+ model_id="openrouter/google/gemini-2.5-flash"
26
+ )
27
+
28
+
29
+
30
+ SYSTEM_PROMPT = """
31
+ You are an Image Agent that allows users to generate an image using prompt or edit images
32
+ using prompt. Always render the images as markdown
33
+ """
34
+
35
+ def convert_history(history):
36
+ """
37
+ Convert Gradio 6 history format:
38
+ [{"role": "...", "content": [{"text": "..."}]}]
39
+
40
+ Into Required format:
41
+ [{"role": "...", "content": "..."}]
42
+ """
43
+ messages = []
44
+ for msg in history:
45
+ # Gradio packs content into list of content blocks
46
+ if isinstance(msg["content"], list):
47
+ # extract just the text pieces
48
+ text = "".join(block.get("text", "") for block in msg["content"])
49
+ else:
50
+ text = msg["content"]
51
+
52
+ messages.append({"role": msg["role"], "content": text})
53
+ return messages
54
+
55
+
56
+ def response_generator(message, history):
57
+ """
58
+ Response Generator
59
+ """
60
+ messages = convert_history(history) if history else []
61
+ agent_messages = []
62
+ for msg in messages:
63
+ agent_messages.append({
64
+ "role": msg["role"],
65
+ "content": [{"text": msg["content"]}]
66
+ })
67
+ with streamable_http_mcp_client:
68
+ # Get the tools from the MCP server
69
+ tools = streamable_http_mcp_client.list_tools_sync()
70
+ image_agent = Agent(
71
+ model=model,
72
+ system_prompt=SYSTEM_PROMPT,
73
+ tools=tools,
74
+ messages=agent_messages
75
+ )
76
+ print(agent_messages)
77
+ messages.append({"role": "user", "content": message})
78
+ response = image_agent(message)
79
+ response = response.message["content"][0]["text"]
80
+ response = response.replace("sandbox:/", "")
81
+ yield response
82
+
83
+ demo = gr.ChatInterface(
84
+ fn=response_generator,
85
+ examples=[["A scenic landscape with mountains, a river, and a clear blue sky", None]],
86
+ title="Image Agent"
87
+ )
88
+ demo.launch()