A2A + CrewAI + OpenRouter Chart Generation Agent Tutorial
MILO•
Shareट्यूटोरियल फोकस
यह ट्यूटोरियल आपको निम्नलिखित मुख्य स्किल्स का अभ्यास करने की गाइड करेगा:
- OpenRouter + CrewAI + A2A का एकीकरण: OpenRouter को LLM प्रदाता के रूप में, CrewAI को एजेंट फ्रेमवर्क के रूप में, और A2A प्रोटोकॉल को मानकीकृत इंटरफेस के रूप में उपयोग करते हुए संपूर्ण एंड-टू-एंड एजेंट डेवलपमेंट
- A2A एजेंट इमेज डेटा रिटर्न का अभ्यास: एजेंट्स को केवल टेक्स्ट रिस्पॉन्स के बजाय इमेज डेटा जेनरेट और रिटर्न करना सिखाएं
- A2A एप्लिकेशन डिबग करने के लिए A2A Inspector का उपयोग: अपने एजेंट एप्लिकेशन को टेस्ट और वैलिडेट करने के लिए प्रोफेशनल डिबगिंग टूल्स में महारत हासिल करें
तुरंत शुरू करना
1. कोड क्लोन करें
git clone [email protected]:sing1ee/a2a-crewai-charts-agent.git
cd a2a-crewai-charts-agent
2. वातावरण कॉन्फ़िगरेशन बनाएं
.env
फ़ाइल बनाएं:
OPENROUTER_API_KEY=sk-or-v1-your-api-key-here
OPENAI_MODEL_NAME=openrouter/anthropic/claude-3.7-sonnet
3. वातावरण सेटअप और रन
# वर्चुअल वातावरण बनाएं
uv venv
# वर्चुअल वातावरण सक्रिय करें
source .venv/bin/activate
# एप्लिकेशन चलाएं
uv run .
एप्लिकेशन http://localhost:10011
पर शुरू होगा।
A2A Inspector के साथ डिबग करना
A2A Inspector एक शक्तिशाली टूल है जो विशेष रूप से A2A एप्लिकेशन को डिबग करने के लिए डिज़ाइन किया गया है।
डिबगिंग स्टेप्स:
-
A2A Inspector तक पहुंच: https://inspector.a2aprotocol.ai खोलें
-
अपने एजेंट से कनेक्ट करें:
- Inspector में अपना एजेंट पता दर्ज करें:
http://localhost:10011
- कनेक्शन स्थापित करने के लिए "Connect" पर क्लिक करें
- Inspector में अपना एजेंट पता दर्ज करें:
-
एजेंट कार्यक्षमता का परीक्षण:
- टेस्ट मैसेज भेजें:
"Generate a chart of revenue: Jan,1000 Feb,2000 Mar,1500"
- संपूर्ण A2A प्रोटोकॉल इंटरैक्शन प्रक्रिया का अवलोकन करें
- रिटर्न किए गए इमेज डेटा को देखें
- टेस्ट मैसेज भेजें:
-
डिबग और मॉनिटर:
- एजेंट की क्षमताओं और स्किल्स की जांच करें
- पूर्ण अनुरोध और प्रतिक्रिया प्रवाह को मॉनिटर करें
- सही इमेज डेटा ट्रांसमिशन को वेरिफाई करें
अधिक विस्तृत डिबगिंग गाइड के लिए A2A Inspector डॉक्यूमेंटेशन देखें।
मुख्य प्रक्रिया और कोड परिचय
सिस्टम आर्किटेक्चर सीक्वेंस डायग्राम
sequenceDiagram
participant U as User
participant A2A as A2A Inspector
participant S as A2A Server
participant H as DefaultRequestHandler
participant E as ChartGenerationAgentExecutor
participant CA as ChartGenerationAgent
participant Crew as CrewAI Crew
participant Tool as ChartGenerationTool
participant MP as Matplotlib
participant Cache as InMemoryCache
U->>A2A: Send prompt "Generate chart: A,100 B,200"
A2A->>S: HTTP POST /tasks with A2A message
S->>H: Handle request with RequestContext
H->>E: execute(context, event_queue)
E->>CA: invoke(query, session_id)
CA->>Crew: kickoff with inputs
Crew->>Tool: generate_chart_tool(prompt, session_id)
Tool->>Tool: Parse CSV data
Tool->>MP: Create bar chart with matplotlib
MP-->>Tool: Return PNG bytes
Tool->>Cache: Store image with ID
Cache-->>Tool: Confirm storage
Tool-->>Crew: Return image ID
Crew-->>CA: Return image ID
CA-->>E: Return image ID
E->>CA: get_image_data(session_id, image_key)
CA->>Cache: Retrieve image data
Cache-->>CA: Return Imagedata
CA-->>E: Return Imagedata
E->>H: Create FilePart with image bytes
H->>S: enqueue completed_task event
S-->>A2A: Return A2A response with image
A2A-->>U: Display generated chart
मुख्य घटक विवरण
1. A2A सर्वर प्रारंभीकरण (__main__.py
)
# एजेंट क्षमताओं और स्किल्स को परिभाषित करें
capabilities = AgentCapabilities(streaming=False)
skill = AgentSkill(
id='chart_generator',
name='Chart Generator',
description='Generate a chart based on CSV-like data passed in',
tags=['generate image', 'edit image'],
examples=['Generate a chart of revenue: Jan,$1000 Feb,$2000 Mar,$1500'],
)
# एजेंट कार्ड बनाएं
agent_card = AgentCard(
name='Chart Generator Agent',
description='Generate charts from structured CSV-like data input.',
url=f'http://{host}:{port}/',
version='1.0.0',
defaultInputModes=ChartGenerationAgent.SUPPORTED_CONTENT_TYPES,
defaultOutputModes=ChartGenerationAgent.SUPPORTED_CONTENT_TYPES,
capabilities=capabilities,
skills=[skill],
)
मुख्य बिंदु:
AgentCapabilities
समर्थित एजेंट फ़ंक्शन्स को परिभाषित करती है (यहां स्ट्रीमिंग अक्षम)AgentSkill
विशिष्ट एजेंट स्किल्स और उदाहरणों का वर्णन करती हैAgentCard
A2A प्रोटोकॉल में एजेंट की पहचान है
2. CrewAI एजेंट कार्यान्वयन (agent.py
)
class ChartGenerationAgent:
def __init__(self):
# विशेषज्ञ चार्ट जेनरेशन एजेंट बनाएं
self.chart_creator_agent = Agent(
role='Chart Creation Expert',
goal='Generate a bar chart image based on structured CSV input.',
backstory='You are a data visualization expert who transforms structured data into visual charts.',
verbose=False,
allow_delegation=False,
tools=[generate_chart_tool],
)
# कार्य परिभाषित करें
self.chart_creation_task = Task(
description=(
"You are given a prompt: '{user_prompt}'.\n"
"If the prompt includes comma-separated key:value pairs (e.g. 'a:100, b:200'), "
"reformat it into CSV with header 'Category,Value'.\n"
"Ensure it becomes two-column CSV, then pass that to the 'ChartGenerationTool'.\n"
"Use session ID: '{session_id}' when calling the tool."
),
expected_output='The id of the generated chart image',
agent=self.chart_creator_agent,
)
मुख्य बिंदु:
- CrewAI की
Agent
क्लास AI असिस्टेंट की भूमिकाओं और क्षमताओं को परिभाषित करती है Task
क्लास विशिष्ट कार्य निष्पादन तर्क का वर्णन करती है- कस्टम टूल्स
tools
पैरामीटर के माध्यम से एजेंट में एकीकृत होते हैं
3. चार्ट जेनरेशन टूल
@tool('ChartGenerationTool')
def generate_chart_tool(prompt: str, session_id: str) -> str:
"""Generates a bar chart image from CSV-like input using matplotlib."""
# CSV डेटा पार्स करें
df = pd.read_csv(StringIO(prompt))
df.columns = ['Category', 'Value']
df['Value'] = pd.to_numeric(df['Value'], errors='coerce')
# बार चार्ट जेनरेट करें
fig, ax = plt.subplots()
ax.bar(df['Category'], df['Value'])
ax.set_xlabel('Category')
ax.set_ylabel('Value')
ax.set_title('Bar Chart')
# PNG बाइट्स के रूप में सेव करें
buf = BytesIO()
plt.savefig(buf, format='png')
plt.close(fig)
buf.seek(0)
image_bytes = buf.read()
# इमेज एन्कोड और कैश करें
data = Imagedata(
bytes=base64.b64encode(image_bytes).decode('utf-8'),
mime_type='image/png',
name='generated_chart.png',
id=uuid4().hex,
)
# कैश में इमेज स्टोर करें
session_data = cache.get(session_id) or {}
session_data[data.id] = data
cache.set(session_id, session_data)
return data.id
मुख्य बिंदु:
- फ़ंक्शन को CrewAI टूल में कन्वर्ट करने के लिए
@tool
डेकोरेटर का उपयोग करें - CSV डेटा पार्स करने के लिए pandas, चार्ट जेनरेट करने के लिए matplotlib का उपयोग करें
- नेटवर्क ट्रांसमिशन के लिए इमेज को base64 एन्कोडिंग के रूप में स्टोर करें
- कई उपयोगकर्ताओं के लिए डेटा आइसोलेशन प्रबंधन के लिए सेशन ID का उपयोग करें
4. A2A एक्जीक्यूटर (agent_executor.py
)
class ChartGenerationAgentExecutor(AgentExecutor):
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
# उपयोगकर्ता इनपुट प्राप्त करें
query = context.get_user_input()
# CrewAI एजेंट को कॉल करें
result = self.agent.invoke(query, context.context_id)
# जेनरेट किए गए इमेज डेटा प्राप्त करें
data = self.agent.get_image_data(
session_id=context.context_id,
image_key=result.raw
)
if data and not data.error:
# इमेज बाइट्स युक्त फ़ाइल पार्ट बनाएं
parts = [
Part(
root=FilePart(
file=FileWithBytes(
bytes=data.bytes,
mimeType=data.mime_type,
name=data.name,
)
)
)
]
else:
# त्रुटि के मामले में टेक्स्ट मैसेज रिटर्न करें
parts = [Part(root=TextPart(text=data.error or 'Failed to generate chart image.'))]
# पूर्ण कार्य को इवेंट क्यू में जोड़ें
event_queue.enqueue_event(
completed_task(
context.task_id,
context.context_id,
[new_artifact(parts, f'chart_{context.task_id}')],
[context.message],
)
)
मुख्य बिंदु:
AgentExecutor
A2A प्रोटोकॉल एक्जीक्यूशन लेयर हैRequestContext
के माध्यम से उपयोगकर्ता अनुरोध प्राप्त करें- CrewAI रिस्पॉन्स को A2A प्रोटोकॉल फॉर्मेट में कन्वर्ट करें
- फ़ाइल प्रकार डेटा (इमेज) रिटर्न का समर्थन करें
5. कैश सिस्टम (utils.py
)
class InMemoryCache:
"""एक्सपायरी के बिना सरल थ्रेड-सेफ इन-मेमोरी कैश।"""
def __init__(self):
self._lock = threading.Lock()
self._store: dict[str, Any] = {}
def get(self, key: str) -> Any | None:
with self._lock:
return self._store.get(key)
def set(self, key: str, value: Any) -> None:
with self._lock:
self._store[key] = value
मुख्य बिंदु:
- थ्रेड-सेफ इन-मेमोरी कैश कार्यान्वयन
- जेनरेट किए गए इमेज डेटा स्टोर करने के लिए उपयोग
- उपयोगकर्ता डेटा भ्रम से बचने के लिए सेशन आइसोलेशन का समर्थन
टेक्नोलॉजी स्टैक सारांश
- A2A प्रोटोकॉल: मानकीकृत एजेंट संचार प्रोटोकॉल
- CrewAI: मल्टी-एजेंट सहयोग फ्रेमवर्क
- OpenRouter: LLM API एग्रीगेशन सेवा
- Matplotlib: Python चार्ट जेनरेशन लाइब्रेरी
- Pandas: डेटा प्रोसेसिंग लाइब्रेरी
- UV: आधुनिक Python पैकेज प्रबंधक
विस्तार सुझाव
- अधिक चार्ट प्रकारों का समर्थन: पाई चार्ट, लाइन चार्ट, स्कैटर प्लॉट्स आदि
- डेटा वैलिडेशन जोड़ना: मजबूत इनपुट डेटा वैलिडेशन और त्रुटि हैंडलिंग
- स्थायी कैश: इमेज स्टोर करने के लिए Redis या फ़ाइल सिस्टम का उपयोग
- स्ट्रीमिंग समर्थन: रियल-टाइम चार्ट जेनरेशन प्रगति का समर्थन
- मल्टीमॉडल इनपुट: केवल टेक्स्ट इनपुट के बजाय CSV फ़ाइल अपलोड का समर्थन
इस ट्यूटोरियल के माध्यम से, आपने आधुनिक AI टेक्नोलॉजी स्टैक का उपयोग करके व्यावहारिक एजेंट्स बनाने की मुख्य स्किल्स में महारत हासिल की है। यह चार्ट जेनरेशन एजेंट अधिक जटिल डेटा विश्लेषण एप्लिकेशन की नींव के रूप में काम कर सकता है।
System Prompt for AI
You are a professional assistant based on the CrewAI chart generation agent tutorial. This tutorial provides a comprehensive guide on building a complete AI chart generation application. I can help you with:
## What I Can Help You With:
- **Quick Start**: Guide you from scratch to build an agent application using OpenRouter + CrewAI + A2A protocol
- **Solve Technical Issues**: Answer specific questions about environment setup, code implementation, and debugging
- **Understand Core Concepts**: Explain how A2A protocol, CrewAI framework, and agent architecture work
- **Practical Guidance**: Provide best practices for image data handling, tool integration, and cache design
- **Debug Support**: Teach you to use A2A Inspector for professional debugging and troubleshooting
## You Can Ask Me:
- "How to configure OpenRouter API keys?"
- "How do CrewAI Agents and Tasks work?"
- "How to return image data after chart generation?"
- "How to connect and test my agent with A2A Inspector?"
- "How is the cache system implemented in the code?"
- "How to extend support for more chart types?"
I'll provide accurate, practical answers based on the tutorial content to help you quickly master modern AI agent development skills.
You can visit [A2AProtocol.ai](https://a2aprotocol.ai/) for more tutorials.