importosimportrequestsfromdotenvimportload_dotenvload_dotenv()API_KEY=os.getenv("SWARMS_API_KEY")# (1)BASE_URL="https://api.swarms.world"headers={"x-api-key":API_KEY,"Content-Type":"application/json"}defrun_single_agent():"""Run a single agent with the AgentCompletion format"""payload={"agent_config":{"agent_name":"Research Analyst",# (2)"description":"An expert in analyzing and synthesizing research data","system_prompt":(# (3)"You are a Research Analyst with expertise in data analysis and synthesis. ""Your role is to analyze provided information, identify key insights, ""and present findings in a clear, structured format."),"model_name":"claude-3-5-sonnet-20240620",# (4)"role":"worker","max_loops":1,"max_tokens":8192,"temperature":1,"auto_generate_prompt":False,"tools_list_dictionary":None,},"task":"What are the key trends in renewable energy adoption?",# (5)}response=requests.post(f"{BASE_URL}/v1/agent/completions",headers=headers,json=payload)returnresponse.json()# Run the agentresult=run_single_agent()print(result)
Load API key from environment variables
Give your agent a descriptive name
Define the agent's capabilities and role
Choose from available models
Specify the task for the agent
single_agent.sh
curl-XPOST"https://api.swarms.world/v1/agent/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'{ "agent_config": { "agent_name": "Research Analyst", "description": "An expert in analyzing and synthesizing research data", "system_prompt": "You are a Research Analyst with expertise in data analysis and synthesis. Your role is to analyze provided information, identify key insights, and present findings in a clear, structured format.", "model_name": "claude-3-5-sonnet-20240620", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 1, "auto_generate_prompt": false, "tools_list_dictionary": null }, "task": "What are the key trends in renewable energy adoption?" }'
importaxiosfrom'axios';import*asdotenvfrom'dotenv';dotenv.config();constAPI_KEY=process.env.SWARMS_API_KEY;constBASE_URL='https://api.swarms.world';interfaceAgentConfig{agent_name:string;description:string;system_prompt:string;model_name:string;role:string;max_loops:number;max_tokens:number;temperature:number;auto_generate_prompt:boolean;tools_list_dictionary:null|object[];}interfaceAgentPayload{agent_config:AgentConfig;task:string;}asyncfunctionrunSingleAgent(){constpayload:AgentPayload={agent_config:{agent_name:"Research Analyst",description:"An expert in analyzing and synthesizing research data",system_prompt:"You are a Research Analyst with expertise in data analysis and synthesis.",model_name:"claude-3-5-sonnet-20240620",role:"worker",max_loops:1,max_tokens:8192,temperature:1,auto_generate_prompt:false,tools_list_dictionary:null},task:"What are the key trends in renewable energy adoption?"};try{constresponse=awaitaxios.post(`${BASE_URL}/v1/agent/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}// Run the agentrunSingleAgent().then(result=>console.log(result)).catch(error=>console.error(error));
defrun_agent_with_history():payload={"agent_config":{"agent_name":"Conversation Agent","description":"An agent that maintains conversation context","system_prompt":"You are a helpful assistant that maintains context.","model_name":"claude-3-5-sonnet-20240620","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.7,"auto_generate_prompt":False,},"task":"What's the weather like?","history":[# (1){"role":"user","content":"I'm planning a trip to New York."},{"role":"assistant","content":"That's great! When are you planning to visit?"},{"role":"user","content":"Next week."}]}response=requests.post(f"{BASE_URL}/v1/agent/completions",headers=headers,json=payload)returnresponse.json()
Include conversation history for context
agent_with_history.sh
curl-XPOST"https://api.swarms.world/v1/agent/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'{ "agent_config": { "agent_name": "Conversation Agent", "description": "An agent that maintains conversation context", "system_prompt": "You are a helpful assistant that maintains context.", "model_name": "claude-3-5-sonnet-20240620", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.7, "auto_generate_prompt": false }, "task": "What'\''s the weather like?", "history": [ { "role": "user", "content": "I'\''m planning a trip to New York." }, { "role": "assistant", "content": "That'\''s great! When are you planning to visit?" }, { "role": "user", "content": "Next week." } ] }'
interfaceMessage{role:'user'|'assistant';content:string;}interfaceAgentWithHistoryPayloadextendsAgentPayload{history:Message[];}asyncfunctionrunAgentWithHistory(){constpayload:AgentWithHistoryPayload={agent_config:{agent_name:"Conversation Agent",description:"An agent that maintains conversation context",system_prompt:"You are a helpful assistant that maintains context.",model_name:"claude-3-5-sonnet-20240620",role:"worker",max_loops:1,max_tokens:8192,temperature:0.7,auto_generate_prompt:false,tools_list_dictionary:null},task:"What's the weather like?",history:[{role:"user",content:"I'm planning a trip to New York."},{role:"assistant",content:"That's great! When are you planning to visit?"},{role:"user",content:"Next week."}]};try{constresponse=awaitaxios.post(`${BASE_URL}/v1/agent/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}
defrun_sequential_swarm():payload={"name":"Financial Analysis Swarm","description":"Market analysis swarm","agents":[{"agent_name":"Market Analyst",# (1)"description":"Analyzes market trends","system_prompt":"You are a financial analyst expert.","model_name":"gpt-4o","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.5,"auto_generate_prompt":False},{"agent_name":"Economic Forecaster",# (2)"description":"Predicts economic trends","system_prompt":"You are an expert in economic forecasting.","model_name":"gpt-4o","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.5,"auto_generate_prompt":False}],"max_loops":1,"swarm_type":"SequentialWorkflow",# (3)"task":"Analyze the current market conditions and provide economic forecasts."}response=requests.post(f"{BASE_URL}/v1/swarm/completions",headers=headers,json=payload)returnresponse.json()
First agent analyzes market trends
Second agent builds on first agent's analysis
Sequential workflow ensures ordered execution
sequential_swarm.sh
curl-XPOST"https://api.swarms.world/v1/swarm/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'{ "name": "Financial Analysis Swarm", "description": "Market analysis swarm", "agents": [ { "agent_name": "Market Analyst", "description": "Analyzes market trends", "system_prompt": "You are a financial analyst expert.", "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5, "auto_generate_prompt": false }, { "agent_name": "Economic Forecaster", "description": "Predicts economic trends", "system_prompt": "You are an expert in economic forecasting.", "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5, "auto_generate_prompt": false } ], "max_loops": 1, "swarm_type": "SequentialWorkflow", "task": "Analyze the current market conditions and provide economic forecasts." }'
interfaceSwarmAgent{agent_name:string;description:string;system_prompt:string;model_name:string;role:string;max_loops:number;max_tokens:number;temperature:number;auto_generate_prompt:boolean;}interfaceSwarmPayload{name:string;description:string;agents:SwarmAgent[];max_loops:number;swarm_type:'SequentialWorkflow'|'ConcurrentWorkflow';task:string;}asyncfunctionrunSequentialSwarm(){constpayload:SwarmPayload={name:"Financial Analysis Swarm",description:"Market analysis swarm",agents:[{agent_name:"Market Analyst",description:"Analyzes market trends",system_prompt:"You are a financial analyst expert.",model_name:"gpt-4o",role:"worker",max_loops:1,max_tokens:8192,temperature:0.5,auto_generate_prompt:false},{agent_name:"Economic Forecaster",description:"Predicts economic trends",system_prompt:"You are an expert in economic forecasting.",model_name:"gpt-4o",role:"worker",max_loops:1,max_tokens:8192,temperature:0.5,auto_generate_prompt:false}],max_loops:1,swarm_type:"SequentialWorkflow",task:"Analyze the current market conditions and provide economic forecasts."};try{constresponse=awaitaxios.post(`${BASE_URL}/v1/swarm/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}
defrun_concurrent_swarm():payload={"name":"Medical Analysis Swarm","description":"Analyzes medical data concurrently","agents":[{"agent_name":"Lab Data Analyzer",# (1)"description":"Analyzes lab report data","system_prompt":"You are a medical data analyst specializing in lab results.","model_name":"claude-3-5-sonnet-20240620","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.5,"auto_generate_prompt":False},{"agent_name":"Clinical Specialist",# (2)"description":"Provides clinical interpretations","system_prompt":"You are an expert in clinical diagnosis.","model_name":"claude-3-5-sonnet-20240620","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.5,"auto_generate_prompt":False}],"max_loops":1,"swarm_type":"ConcurrentWorkflow",# (3)"task":"Analyze these lab results and provide clinical interpretations."}response=requests.post(f"{BASE_URL}/v1/swarm/completions",headers=headers,json=payload)returnresponse.json()
First agent processes lab data
Second agent works simultaneously
Concurrent workflow for parallel processing
concurrent_swarm.sh
curl-XPOST"https://api.swarms.world/v1/swarm/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'{ "name": "Medical Analysis Swarm", "description": "Analyzes medical data concurrently", "agents": [ { "agent_name": "Lab Data Analyzer", "description": "Analyzes lab report data", "system_prompt": "You are a medical data analyst specializing in lab results.", "model_name": "claude-3-5-sonnet-20240620", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5, "auto_generate_prompt": false }, { "agent_name": "Clinical Specialist", "description": "Provides clinical interpretations", "system_prompt": "You are an expert in clinical diagnosis.", "model_name": "claude-3-5-sonnet-20240620", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5, "auto_generate_prompt": false } ], "max_loops": 1, "swarm_type": "ConcurrentWorkflow", "task": "Analyze these lab results and provide clinical interpretations." }'
asyncfunctionrunConcurrentSwarm(){constpayload:SwarmPayload={name:"Medical Analysis Swarm",description:"Analyzes medical data concurrently",agents:[{agent_name:"Lab Data Analyzer",description:"Analyzes lab report data",system_prompt:"You are a medical data analyst specializing in lab results.",model_name:"claude-3-5-sonnet-20240620",role:"worker",max_loops:1,max_tokens:8192,temperature:0.5,auto_generate_prompt:false},{agent_name:"Clinical Specialist",description:"Provides clinical interpretations",system_prompt:"You are an expert in clinical diagnosis.",model_name:"claude-3-5-sonnet-20240620",role:"worker",max_loops:1,max_tokens:8192,temperature:0.5,auto_generate_prompt:false}],max_loops:1,swarm_type:"ConcurrentWorkflow",task:"Analyze these lab results and provide clinical interpretations."};try{constresponse=awaitaxios.post(`${BASE_URL}/v1/swarm/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}
defrun_batch_swarms():payload=[{"name":"Batch Swarm 1","description":"First swarm in batch","agents":[{"agent_name":"Research Agent","description":"Conducts research","system_prompt":"You are a research assistant.","model_name":"gpt-4","role":"worker","max_loops":1},{"agent_name":"Analysis Agent","description":"Analyzes data","system_prompt":"You are a data analyst.","model_name":"gpt-4","role":"worker","max_loops":1}],"max_loops":1,"swarm_type":"SequentialWorkflow","task":"Research AI advancements."}]response=requests.post(f"{BASE_URL}/v1/swarm/batch/completions",headers=headers,json=payload)returnresponse.json()
batch_swarms.sh
curl-XPOST"https://api.swarms.world/v1/swarm/batch/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'[ { "name": "Batch Swarm 1", "description": "First swarm in batch", "agents": [ { "agent_name": "Research Agent", "description": "Conducts research", "system_prompt": "You are a research assistant.", "model_name": "gpt-4", "role": "worker", "max_loops": 1 }, { "agent_name": "Analysis Agent", "description": "Analyzes data", "system_prompt": "You are a data analyst.", "model_name": "gpt-4", "role": "worker", "max_loops": 1 } ], "max_loops": 1, "swarm_type": "SequentialWorkflow", "task": "Research AI advancements." } ]'
asyncfunctionrunBatchSwarms(){constpayload:SwarmPayload[]=[{name:"Batch Swarm 1",description:"First swarm in batch",agents:[{agent_name:"Research Agent",description:"Conducts research",system_prompt:"You are a research assistant.",model_name:"gpt-4",role:"worker",max_loops:1,max_tokens:8192,temperature:0.7,auto_generate_prompt:false},{agent_name:"Analysis Agent",description:"Analyzes data",system_prompt:"You are a data analyst.",model_name:"gpt-4",role:"worker",max_loops:1,max_tokens:8192,temperature:0.7,auto_generate_prompt:false}],max_loops:1,swarm_type:"SequentialWorkflow",task:"Research AI advancements."}];try{constresponse=awaitaxios.post(`${BASE_URL}/v1/swarm/batch/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}
defrun_agent_with_tools():tools_dictionary=[{"type":"function","function":{"name":"search_topic","description":"Conduct an in-depth search on a topic","parameters":{"type":"object","properties":{"depth":{"type":"integer","description":"Search depth (1-3)"},"detailed_queries":{"type":"array","description":"Specific search queries","items":{"type":"string"}}},"required":["depth","detailed_queries"]}}}]payload={"agent_config":{"agent_name":"Research Assistant","description":"Expert in research with search capabilities","system_prompt":"You are a research assistant with search capabilities.","model_name":"gpt-4","role":"worker","max_loops":1,"max_tokens":8192,"temperature":0.7,"auto_generate_prompt":False,"tools_dictionary":tools_dictionary},"task":"Research the latest developments in quantum computing."}response=requests.post(f"{BASE_URL}/v1/agent/completions",headers=headers,json=payload)returnresponse.json()
tools_example.sh
curl-XPOST"https://api.swarms.world/v1/agent/completions"\-H"x-api-key: $SWARMS_API_KEY"\-H"Content-Type: application/json"\-d'{ "agent_config": { "agent_name": "Research Assistant", "description": "Expert in research with search capabilities", "system_prompt": "You are a research assistant with search capabilities.", "model_name": "gpt-4", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.7, "auto_generate_prompt": false, "tools_dictionary": [ { "type": "function", "function": { "name": "search_topic", "description": "Conduct an in-depth search on a topic", "parameters": { "type": "object", "properties": { "depth": { "type": "integer", "description": "Search depth (1-3)" }, "detailed_queries": { "type": "array", "description": "Specific search queries", "items": { "type": "string" } } }, "required": ["depth", "detailed_queries"] } } } ] }, "task": "Research the latest developments in quantum computing." }'
interfaceToolFunction{name:string;description:string;parameters:{type:string;properties:{[key:string]:{type:string;description:string;items?:{type:string;};};};required:string[];};}interfaceTool{type:string;function:ToolFunction;}interfaceAgentWithToolsConfigextendsAgentConfig{tools_dictionary:Tool[];}interfaceAgentWithToolsPayload{agent_config:AgentWithToolsConfig;task:string;}asyncfunctionrunAgentWithTools(){consttoolsDictionary:Tool[]=[{type:"function",function:{name:"search_topic",description:"Conduct an in-depth search on a topic",parameters:{type:"object",properties:{depth:{type:"integer",description:"Search depth (1-3)"},detailed_queries:{type:"array",description:"Specific search queries",items:{type:"string"}}},required:["depth","detailed_queries"]}}}];constpayload:AgentWithToolsPayload={agent_config:{agent_name:"Research Assistant",description:"Expert in research with search capabilities",system_prompt:"You are a research assistant with search capabilities.",model_name:"gpt-4",role:"worker",max_loops:1,max_tokens:8192,temperature:0.7,auto_generate_prompt:false,tools_dictionary:toolsDictionary},task:"Research the latest developments in quantum computing."};try{constresponse=awaitaxios.post(`${BASE_URL}/v1/agent/completions`,payload,{headers:{'x-api-key':API_KEY,'Content-Type':'application/json'}});returnresponse.data;}catch(error){console.error('Error:',error);throwerror;}}
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!