Quickstart Guide
Get started with Nexus in just a few steps! π
Follow this guide to install the Nexus SDK, authenticate, and start using agents right away.
Before you beginβ
You need a Nexus API key. If you don't already have one, you can get it for free in Nexus.
Install the Nexus SDKβ
Install the Python SDK via pip:
pip install ainexus-sdk
Approach 1: Using Docker Image from Nexus site β pull & run locallyβ
In this approach, you fetch the Docker image from Nexus and run the agent on your machine.
- Discover agent cards via SDK or Nexus API
- Pull the agent Docker image
- Run the container locally
- Interact with the agent through REST API
Fetch and Use Agents with the SDKβ
Hereβs how you can discover, fetch, and run agents in your code:
You must have Docker Desktop (or Docker Engine) running on your system before starting.
Without Docker running, the container will not start and the SDK will fail to connect.
import logging
import time
from typing import Any
from uuid import uuid4
import docker
import httpx
from a2a.client import A2AClient
from a2a.types import (
AgentCard,
MessageSendParams,
SendMessageRequest,
SendStreamingMessageRequest,
)
# AI Nexus SDK
from ainexus_sdk.client import AgentSDK
async def main() -> None:
# Configure logging to show INFO level messages
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) # Get a logger instance
PUBLIC_AGENT_CARD_PATH = '/.well-known/agent.json'
EXTENDED_AGENT_CARD_PATH = '/agent/authenticatedExtendedCard'
nexus_sdk = AgentSDK(api_key="YOUR_API_KEY") # Get you API Key
agent = nexus_sdk.discover("e9ce7d35-cc81-4268-9808-04471947edaa") # Simple hello-world agent id
agent_metadata = agent[0].model_dump()
card = agent_metadata["agent_card"]
agent_card = AgentCard.model_validate(card)
# Docker run
client = docker.from_env()
image = agent_metadata["docker_image"]
logger.info(f'Docker image pulled : {image}')
# Pull the image
client.images.pull(image)
container = client.containers.run(
image,
detach = True,
ports={'9999/tcp':9999} #local path and port
)
# Wait for the container to initialize (e.g., 10 seconds)
time.sleep(10)
logger.info(f'Agent running at {container.name}')
for container in client.containers.list():
logger.info(f'Agent running at {container.name}')
async with httpx.AsyncClient() as httpx_client:
try:
logger.info(
f'Attempting to fetch public agent card from: {base_url}{PUBLIC_AGENT_CARD_PATH}'
)
logger.info('Successfully fetched public agent card:')
logger.info(
'Using PUBLIC agent card for client initialization (default).'
)
except Exception as e:
logger.error(
f'Critical error fetching public agent card: {e}', exc_info=True
)
raise RuntimeError(
'Failed to fetch the public agent card. Cannot continue.'
) from e
# --8<-- [start:send_message]
client = A2AClient(
httpx_client=httpx_client, agent_card=agent_card
)
logger.info('A2AClient initialized.')
send_message_payload: dict[str, Any] = {
'message': {
'role': 'user',
'parts': [
{'kind': 'text', 'text': 'how much is 10 USD in INR?'}
],
'messageId': uuid4().hex,
},
}
request = SendMessageRequest(
id=str(uuid4()), params=MessageSendParams(**send_message_payload)
)
response = await client.send_message(request)
print(response.model_dump(mode='json', exclude_none=True))
# --8<-- [end:send_message]
# --8<-- [start:send_message_streaming]
streaming_request = SendStreamingMessageRequest(
id=str(uuid4()), params=MessageSendParams(**send_message_payload)
)
stream_response = client.send_message_streaming(streaming_request)
async for chunk in stream_response:
print(chunk.model_dump(mode='json', exclude_none=True))
# --8<-- [end:send_message_streaming]
container.stop()
if __name__ == '__main__':
import asyncio
asyncio.run(main())
Example Runβ
uv run .
Approach 2: Using Agent URL (server endpoint) from Nexus site β call it directly via REST APIβ
In this approach, you donβt need to run a Docker container locally. Instead, you directly integrate with the hosted agent endpoint (Agent URL) published on Nexus.
Stepsβ
- Discover the Agent - Use the Nexus SDK to discover agents by ID or query:
- Fetch the Agent Card - The Agent Card contains metadata like capabilities, endpoints, and skills.
- Initialize A2A Client - Once you have the agent card, initialize the client:
- Send a Message - Agents may support streaming or non-streaming responses.
import logging
from typing import Any
from uuid import uuid4
import httpx
from a2a.client import A2ACardResolver, A2AClient
from a2a.types import (
AgentCard,
JSONRPCErrorResponse,
Message,
MessageSendParams,
SendMessageRequest,
SendStreamingMessageRequest,
Task,
TaskArtifactUpdateEvent,
TaskStatusUpdateEvent,
)
from ainexus_sdk.client import AgentSDK
async def main() -> None:
# Configure logging to show INFO level messages
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) # Get a logger instance
# Discover agent using Agent SDK
nexus_sdk = AgentSDK(api_key="YOUR_API_KEY") # Get you API Key
agent = nexus_sdk.discover("14b56552-1675-41b3-b4cf-a9b04635a002") # Content Planner agent id``
agent_metadata = agent[0].model_dump()
base_url = agent_metadata['agent_url']
# --8<-- [start:A2ACardResolver]
async with httpx.AsyncClient() as httpx_client:
# Initialize A2ACardResolver
resolver = A2ACardResolver(
httpx_client=httpx_client,
base_url=base_url,
)
# --8<-- [end:A2ACardResolver]
# Fetch Public Agent Card and Initialize Client
agent_card: AgentCard | None = None
try:
_public_card = (
await resolver.get_agent_card()
)
agent_card = _public_card
logger.info(
'Using PUBLIC agent card for client initialization (default).'
)
except Exception as e:
logger.error(
f'Critical error fetching public agent card: {e}', exc_info=True
)
raise RuntimeError(
'Failed to fetch the public agent card. Cannot continue.'
) from e
logger.info('A2AClient initialized.')
client = A2AClient(
httpx_client=httpx_client, agent_card=agent_card
)
# Streaming or non-streaming based on agent capabilities
streaming = agent_card.capabilities.streaming
# Send a message to the agent
send_message_payload: dict[str, Any] = {
'message': {
'role': 'user',
'parts': [
{'kind': 'text', 'text': 'Plan a detailed outline for a 10-minute presentation on artificial intelligence in healthcare'}
],
'messageId': uuid4().hex,
},
}
payload = MessageSendParams(**send_message_payload)
# If streaming is true
if streaming:
response_stream = client.send_message_streaming(
SendStreamingMessageRequest(
id=str(uuid4()),
params=payload,
)
)
async for result in response_stream:
if isinstance(result.root, JSONRPCErrorResponse):
print(
f'Error: {result.root.error}, context_id: {context_id}, task_id: {task_id}'
)
return False, context_id, task_id
event = result.root.result
context_id = event.context_id
if isinstance(event, Task):
task_id = event.id
elif isinstance(event, TaskStatusUpdateEvent) or isinstance(
event, TaskArtifactUpdateEvent
):
task_id = event.task_id
if (
isinstance(event, TaskStatusUpdateEvent)
and event.status.state == 'completed'
):
task_completed = True
elif isinstance(event, Message):
message = event
print(f'stream event => {event.model_dump_json(exclude_none=True)}')
else:
request = SendMessageRequest(id=str(uuid4()), params=payload)
response = await client.send_message(request)
print(response.model_dump(mode='json', exclude_none=True))
if __name__ == '__main__':
import asyncio
asyncio.run(main())
Example Runβ
uv run .
Expected Outputβ
INFO:a2a.client.card_resolver:Successfully fetched agent card data from https://first-agent-388722952841.asia-south1.run.app/.well-known/agent-card.json:
{
'capabilities': {'streaming': True},
'defaultInputModes': ['text', 'text/plain'],
'defaultOutputModes': ['text', 'text/plain'],
'description': 'Planning agent that creates a detailed and logical outline for a piece of content,given a high-level description.',
'name': 'Content Planner Agent',
'preferredTransport': 'JSONRPC', 'protocolVersion': '0.3.0',
'skills': [{'description': 'Creates outlines for content given a high-level description of the content', 'examples': ['Create an outline for a short, upbeat, and encouraging X post about learning Java'], 'id': 'content_planner', 'name': 'Creates outlines for content', 'tags': ['plan', 'outline']}],
'url': 'https://first-agent-388722952841.asia-south1.run.app',
'version': '1.0.0'
}
INFO:__main__:
Using PUBLIC agent card for client initialization (default).
INFO:__main__:A2AClient initialized.
INFO:httpx:HTTP Request: POST https://example-agent.run.app "HTTP/1.1 200 OK"
stream event => {
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"history": [
{
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"kind": "message",
"messageId": "ce38c820112f45cf92af464a7f08eb6f",
"parts": [
{
"kind": "text",
"text": "Plan a detailed outline for a 10-minute presentation on artificial intelligence in healthcare"
}
],
"role": "user",
"taskId": "0577d46d-a350-4534-88d1-489bcffb2969"
}
],
"id": "0577d46d-a350-4534-88d1-489bcffb2969",
"kind": "task",
"status": {
"state": "submitted"
}
}
stream event => {
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"history": [
{
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"kind": "message",
"messageId": "ce38c820112f45cf92af464a7f08eb6f",
"parts": [
{
"kind": "text",
"text": "Plan a detailed outline for a 10-minute presentation on artificial intelligence in healthcare"
}
],
"role": "user",
"taskId": "0577d46d-a350-4534-88d1-489bcffb2969"
}
],
"id": "0577d46d-a350-4534-88d1-489bcffb2969",
"kind": "task",
"status": {
"state": "submitted"
}
}
stream event => {
"events": [
{
"artifact": {
"artifactId": "aa3caacf-0b96-4c1f-8d24-471cd6c349a0",
"name": "response",
"parts": [
{
"kind":"text",
"text":"Here's a detailed outline for a 10-minute presentation on Artificial Intelligence in Healthcare:
---
## **Presentation Title:** Revolutionizing Medicine: The Impact of Artificial Intelligence in Healthcare
**Target Audience:** General audience with an interest in technology and healthcare (or similar, adapt as needed)
**Time Allotment:** 10 minutes (approximate timings per section provided)
---
### **I. Introduction (Approx. 1 minute)**
* **A. Hook (15 seconds)**
* Start with a thought-provoking question or a compelling statistic about healthcare challenges (e. g., \"Imagine a world where diseases are diagnosed earlier, treatments are
personalized, and drug discovery takes a fraction of the time. This is the promise of AI
in healthcare.\")
* **B. Define AI (briefly) (15 seconds)**
* What is Artificial Intelligence? (Simply: computers performing tasks that typically require human intelligence, like learning, problem-solving, decision-making).
* Focus on its relevance to data analysis and pattern recognition.
* **C. Presentation Roadmap (30 seconds)**
* \"Today, we'll explore how AI is transforming various facets of healthcare, from diagnosis to drug discovery, discuss its benefits, address the challenges, and peek into its future potential.\"
### **II. What is AI in Healthcare? (Key Technologies) (Approx. 1.5 minutes)**
* **A. Machine Learning (ML) (45 seconds)**
* **Concept:** Algorithms that learn from data without explicit programming.
* **Healthcare Relevance:** Pattern recognition, predictive analytics.
* **Examples:** Identifying disease markers, predicting patient risk.
* **B. Deep Learning (DL) (30 seconds)**
* **Concept:** A subset of ML using neural networks with many layers.
* **Healthcare Relevance:** Image and complex data analysis.
* **Examples:** Medical imaging (radiology, pathology).
* **C. Natural Language Processing (NLP) (15 seconds)**
* **Concept:** Enabling computers to understand and process human language.
* **Healthcare Relevance:** Analyzing unstructured text data.
* **Examples:** Electronic Health Records (EHRs), research papers.
### **III. Key Applications of AI in Healthcare (Approx. 4 minutes)**
* **A. Enhanced Diagnostics & Imaging (1.5 minutes)**
* **Early Disease Detection:** AI algorithms can analyze medical images (X-rays, MRIs, CT scans) more quickly and accurately than the human eye, identifying subtle indicators of disease (e.g., detecting early signs of cancer, diabetic retinopathy).
* **Pathology:** Assisting pathologists in analyzing tissue samples for disease.
* **Personalized Risk Assessment:** Using patient data to predict susceptibility to certain conditions.
* **B. Drug Discovery & Development (1 minute)**
* **Accelerated Research:** AI can analyze vast datasets of genetic, molecular, and clinical data to identify potential drug targets and predict drug efficacy.
* **Reduced Time & Cost:** Speeding up the identification of promising compounds, potentially reducing the multi-year timeline and billions of dollars typically involved in drug development. * **Repurposing Existing Drugs:** Identifying new uses for existing medications.
* **C. Personalized Treatment & Precision Medicine (1 minute)**
* **Tailored Therapies:** Analyzing a patient's genetic makeup, lifestyle, and medical history to recommend the most effective treatment plan, minimizing adverse effects.
* **Dosage Optimization:** Using AI to determine optimal drug dosages based on individual patient characteristics.
* **Predicting Treatment Response:** Identifying which patients are most likely to respond to a
particular therapy.
* **D. Administrative Efficiency & Patient Management (0.5 minutes)**
* **Streamlined Operations:** Automating tasks like scheduling, billing, and record-keeping.
* **Predictive Analytics for Hospital Management:** Predicting patient flow, optimizing resource allocation.
* **Virtual Assistants/Chatbots:** Providing patient support, answering FAQs, medication reminders.
### **IV. Benefits of AI in Healthcare (Approx. 1.5 minutes)**
* **A. Improved Patient Outcomes (30 seconds)**
* Faster, more accurate diagnoses.
* More effective and personalized treatments.
* **B. Increased Efficiency & Cost Reduction (30 seconds)**
* Streamlined workflows, reduced administrative burden.
* Accelerated research and development.
* **C. Enhanced Accessibility (30 seconds)**
* Potential to extend expert-level care to remote or underserved areas.
* Empowering patients with more information and self-management tools.
* **D. Support for Healthcare Professionals (30 seconds)**
* AI as a powerful assistant, not a replacement.
* Reducing burnout by automating routine tasks.
### **V. Challenges and Ethical Considerations (Approx. 1 minute)**
* **A. Data Privacy & Security (30 seconds)**
* Protecting sensitive patient information.
* Ensuring ethical data collection and usage.
* **B. Bias in Algorithms (15 seconds)**
* Risk of perpetuating or amplifying existing health disparities if training data is biased.
* Need for diverse and representative datasets.
* **C. Regulatory Hurdles & Integration (15 seconds)**
* Developing clear guidelines for AI medical devices.
* Integrating new AI systems into existing healthcare infrastructures.
* Physician acceptance and training.
### **VI. Future Outlook (Approx. 0.5 minutes)**
* **A. Expanding Role:** AI will become increasingly integrated into all aspects of healthcare.
* **B. Collaborative Future:** Continued collaboration between AI developers, clinicians, and policymakers will be crucial.
* **C. Focus on Explainable AI:** Greater transparency in how AI makes decisions to build trust.### **VII. Conclusion & Q&A (Approx. 0.5 minutes)**
* **A. Recap (15 seconds)**
* Briefly summarize the transformative potential of AI in improving diagnostics, treatments, and overall healthcare delivery.
* **B. Final Thought/Call to Action (15 seconds)**
* \"AI is not just a tool; it's a paradigm shift, promising a healthier, more efficient, and more equitable future for medicine.\"* **C. Questions & Discussion (Remaining time)**
---
**Visual Aids Suggestions:**
* **Slide 1:** Title Slide
* **Slide 2:** Simple graphic defining AI (e.g., Venn diagram of AI, ML, DL)
* **Slide 3:** Icons representing different AI applications (e.g., magnifying glass for diagnostics, DNA helix for drug discovery, person icon for personalized medicine).
* **Slide 4:** Infographic summarizing benefits.
* **Slide 5:** Icons representing challenges (e.g., lock for security, scales for bias, gears for integration).
* **Slide 6:** Futuristic image or a graphic showing human-AI collaboration.
* **Slide 7:** Q&A slide.\
**Delivery Tips:**
* Speak clearly and at a moderate pace.
* Use relatable examples.
* Maintain eye contact.
* Manage time strictly for each section."}]
},
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"kind": "artifact-update",
"taskId": "0577d46d-a350-4534-88d1-489bcffb2969"
},
{
"contextId": "31ae1fd5-99ff-41ca-ad65-9e01d356766e",
"final": true,
"kind": "status-update",
"status": {
"state": "completed",
"timestamp": "2025-09-24T20:11:10.829624+00:00"
},
"taskId": "0577d46d-a350-4534-88d1-489bcffb2969"
}
]
}
π Next, check out our Examples to see more use cases.