parent
d1cb8a6da2
commit
20e0fb7fd1
@ -0,0 +1,188 @@
|
||||
# Loading Prompts from the Swarms Marketplace
|
||||
|
||||
Load production-ready prompts from the Swarms Marketplace directly into your agents with a single parameter. This feature enables one-line prompt loading, making it easy to leverage community-created prompts without manual copy-pasting.
|
||||
|
||||
## Overview
|
||||
|
||||
The Swarms Marketplace hosts a collection of expertly crafted prompts for various use cases. Instead of manually copying prompts or managing them in separate files, you can now load them directly into your agent using the `marketplace_prompt_id` parameter.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before using this feature, ensure you have:
|
||||
|
||||
1. **Swarms installed**:
|
||||
```bash
|
||||
pip install -U swarms
|
||||
```
|
||||
|
||||
2. **A Swarms API key** - Get yours at [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys)
|
||||
|
||||
3. **Set your API key** as an environment variable:
|
||||
```bash
|
||||
export SWARMS_API_KEY="your-api-key-here"
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Usage
|
||||
|
||||
Load a marketplace prompt in one line by providing the `marketplace_prompt_id`:
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
agent = Agent(
|
||||
model_name="gpt-4o-mini",
|
||||
marketplace_prompt_id="your-prompt-uuid-here",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
response = agent.run("Your task here")
|
||||
print(response)
|
||||
```
|
||||
|
||||
That's it! The agent automatically fetches the prompt from the marketplace and uses it as the system prompt.
|
||||
|
||||
### Finding Prompt IDs
|
||||
|
||||
To find prompt IDs:
|
||||
|
||||
1. Visit the [Swarms Marketplace](https://swarms.world/marketplace)
|
||||
2. Browse or search for prompts that fit your use case
|
||||
3. Click on a prompt to view its details
|
||||
4. Copy the prompt's UUID from the URL or the prompt details page
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a complete working example:
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
# Create an agent with a marketplace prompt
|
||||
agent = Agent(
|
||||
model_name="gpt-4o-mini",
|
||||
marketplace_prompt_id="0ff9cc2f-390a-4eb1-9d3d-3a045cd2682e",
|
||||
max_loops="auto",
|
||||
interactive=True,
|
||||
)
|
||||
|
||||
# Run the agent - it uses the system prompt from the marketplace
|
||||
response = agent.run("Hello, what can you help me with?")
|
||||
print(response)
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
When you provide a `marketplace_prompt_id`, the agent:
|
||||
|
||||
1. **Fetches the prompt** from the Swarms Marketplace API during initialization
|
||||
2. **Sets the system prompt** from the marketplace data
|
||||
3. **Optionally updates agent metadata** - If you haven't set a custom `agent_name` or `agent_description`, these will be populated from the marketplace prompt data
|
||||
4. **Logs the operation** - You'll see a confirmation message when the prompt is loaded successfully
|
||||
|
||||
```
|
||||
🛒 [MARKETPLACE] Loaded prompt 'Your Prompt Name' from Swarms Marketplace
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Combining with Other Parameters
|
||||
|
||||
You can combine `marketplace_prompt_id` with any other agent parameters:
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
|
||||
agent = Agent(
|
||||
# Marketplace prompt
|
||||
marketplace_prompt_id="your-prompt-uuid",
|
||||
|
||||
# Model configuration
|
||||
model_name="gpt-4o",
|
||||
max_tokens=4096,
|
||||
temperature=0.7,
|
||||
|
||||
# Agent behavior
|
||||
max_loops=3,
|
||||
verbose=True,
|
||||
|
||||
# Tools
|
||||
tools=[your_tool_function],
|
||||
)
|
||||
```
|
||||
|
||||
### Overriding Agent Name and Description
|
||||
|
||||
By default, the agent will use the name and description from the marketplace prompt if you haven't set them. To use your own:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
marketplace_prompt_id="your-prompt-uuid",
|
||||
agent_name="My Custom Agent Name", # This overrides the marketplace name
|
||||
agent_description="My custom description", # This overrides the marketplace description
|
||||
model_name="gpt-4o-mini",
|
||||
)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The feature includes built-in error handling:
|
||||
|
||||
### Prompt Not Found
|
||||
|
||||
If the prompt ID doesn't exist:
|
||||
|
||||
```python
|
||||
# This will raise a ValueError with a helpful message
|
||||
agent = Agent(
|
||||
marketplace_prompt_id="non-existent-id",
|
||||
model_name="gpt-4o-mini",
|
||||
)
|
||||
# ValueError: Prompt with ID 'non-existent-id' not found in the marketplace.
|
||||
# Please verify the prompt ID is correct.
|
||||
```
|
||||
|
||||
### Missing API Key
|
||||
|
||||
If the `SWARMS_API_KEY` environment variable is not set:
|
||||
|
||||
```python
|
||||
# This will raise a ValueError
|
||||
agent = Agent(
|
||||
marketplace_prompt_id="your-prompt-uuid",
|
||||
model_name="gpt-4o-mini",
|
||||
)
|
||||
# ValueError: Swarms API key is not set. Please set the SWARMS_API_KEY environment variable.
|
||||
# You can get your key here: https://swarms.world/platform/api-keys
|
||||
```
|
||||
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Store prompt IDs in configuration** - Keep your prompt IDs in environment variables or config files for easy updates
|
||||
|
||||
2. **Handle errors gracefully** - Wrap agent creation in try-except blocks for production code
|
||||
|
||||
3. **Cache prompts for offline use** - If you need offline capability, fetch and store prompts locally as backup
|
||||
|
||||
4. **Version your prompts** - When updating marketplace prompts, consider creating new versions rather than overwriting
|
||||
|
||||
5. **Monitor prompt usage** - Track which prompts are being used in your applications for analytics
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| `ValueError: Swarms API key is not set` | Set the `SWARMS_API_KEY` environment variable |
|
||||
| `ValueError: Prompt not found` | Verify the prompt ID is correct on the marketplace |
|
||||
| `Connection timeout` | Check your internet connection and try again |
|
||||
| Agent not using expected prompt | Ensure you're not also setting `system_prompt` parameter |
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Swarms Marketplace](https://swarms.world/marketplace) - Browse available prompts
|
||||
- [Publishing Prompts](../../../swarms_platform/monetize.md) - Share your own prompts
|
||||
- [Agent Reference](../../structs/agent.md) - Full agent documentation
|
||||
- [API Key Management](../../../swarms_platform/apikeys.md) - Manage your API keys
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,34 @@
|
||||
# FairySwarm Examples
|
||||
|
||||
Examples demonstrating the FairySwarm multi-agent coordination system, inspired by tldraw's "fairies" feature.
|
||||
|
||||
## Examples
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `basic_fairy_swarm.py` | Simple landing page wireframe task |
|
||||
| `selected_fairies.py` | Run with subset of fairies (orchestrator election) |
|
||||
| `custom_tools.py` | Add custom tools like color palette generator |
|
||||
| `standalone_tools.py` | Use canvas/todo tools without full swarm |
|
||||
| `multi_page_wireframe.py` | Complex multi-page coordination task |
|
||||
| `analytical_research.py` | Research-heavy dashboard design |
|
||||
| `custom_fairy.py` | Create custom fairy agents |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Set your API key
|
||||
export OPENAI_API_KEY="your-key"
|
||||
|
||||
# Run an example
|
||||
python fairy_swarm_examples/basic_fairy_swarm.py
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
1. **Orchestrator Fairy** - Plans and delegates tasks
|
||||
2. **Worker Fairies** - Creative, Operational, Analytical, Harmonizer
|
||||
3. **Shared Todo List** - Coordination between agents
|
||||
4. **Canvas Tools** - Functions for manipulating shared state
|
||||
5. **Context Refresh** - Mid-work updates when needed
|
||||
|
||||
@ -0,0 +1,25 @@
|
||||
"""
|
||||
Analytical Research Example
|
||||
|
||||
Use the Analytical Fairy's strengths for research-heavy tasks.
|
||||
The orchestrator will delegate analysis work appropriately.
|
||||
"""
|
||||
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Research Team",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = swarm.run(
|
||||
"Research and design an information dashboard for tracking:\n"
|
||||
"1. Key performance metrics with charts\n"
|
||||
"2. Data tables with sorting capabilities\n"
|
||||
"3. Filter controls and search functionality\n"
|
||||
"Include recommendations for data visualization best practices."
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,27 @@
|
||||
"""
|
||||
Basic FairySwarm Example
|
||||
|
||||
A simple example showing how to create a FairySwarm and run a design task.
|
||||
The swarm coordinates multiple fairy agents to work on a shared canvas.
|
||||
|
||||
Inspired by tldraw's fairies feature for multi-agent coordination.
|
||||
"""
|
||||
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Design Team",
|
||||
description="A collaborative team of fairies for UI design",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = swarm.run(
|
||||
"Create a wireframe for a simple landing page with:\n"
|
||||
"1. A header with logo and navigation menu\n"
|
||||
"2. A hero section with headline and CTA button\n"
|
||||
"3. A footer with copyright and social links"
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,59 @@
|
||||
"""
|
||||
Custom Fairy Example
|
||||
|
||||
Create a swarm with custom fairy agents instead of the defaults.
|
||||
Useful when you need specialized agent personalities.
|
||||
"""
|
||||
|
||||
from swarms import Agent
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
copywriter = Agent(
|
||||
agent_name="Copywriter-Fairy",
|
||||
agent_description="Expert at writing compelling marketing copy and headlines",
|
||||
system_prompt="""You are the Copywriter Fairy - a wordsmith who crafts compelling copy.
|
||||
|
||||
Your Specialties:
|
||||
- Headlines and taglines
|
||||
- Call-to-action text
|
||||
- Marketing copy
|
||||
- Brand messaging
|
||||
|
||||
Always USE YOUR TOOLS to add text elements to the canvas.
|
||||
Output format: COPY CREATED: [your copy], ACTIONS TAKEN: [tools used]""",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
ux_designer = Agent(
|
||||
agent_name="UX-Designer-Fairy",
|
||||
agent_description="Focused on user experience and interaction design",
|
||||
system_prompt="""You are the UX Designer Fairy - focused on user experience.
|
||||
|
||||
Your Specialties:
|
||||
- User flows and journeys
|
||||
- Interaction patterns
|
||||
- Accessibility considerations
|
||||
- Usability optimization
|
||||
|
||||
Always USE YOUR TOOLS to create UX elements on the canvas.
|
||||
Output format: UX DESIGN: [your design], ACTIONS TAKEN: [tools used]""",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Marketing Team",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2,
|
||||
verbose=True,
|
||||
fairies=[copywriter, ux_designer],
|
||||
auto_create_default_fairies=False,
|
||||
)
|
||||
|
||||
result = swarm.run(
|
||||
"Create a product launch landing page with compelling headlines, "
|
||||
"persuasive copy, and an optimized user flow for conversions."
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,65 @@
|
||||
"""
|
||||
Custom Tools Example
|
||||
|
||||
Add custom tools to fairies for specialized functionality.
|
||||
This example adds a color palette generator tool.
|
||||
"""
|
||||
|
||||
import json
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
|
||||
def generate_color_palette(theme: str, num_colors: int = 5) -> str:
|
||||
"""
|
||||
Generate a color palette for a given theme.
|
||||
|
||||
Args:
|
||||
theme: The theme for the palette (ocean, sunset, forest)
|
||||
num_colors: Number of colors to generate
|
||||
|
||||
Returns:
|
||||
JSON string with the color palette
|
||||
"""
|
||||
palettes = {
|
||||
"ocean": [
|
||||
"#0077B6",
|
||||
"#00B4D8",
|
||||
"#90E0EF",
|
||||
"#CAF0F8",
|
||||
"#03045E",
|
||||
],
|
||||
"sunset": [
|
||||
"#FF6B6B",
|
||||
"#FFA06B",
|
||||
"#FFD93D",
|
||||
"#FF8E53",
|
||||
"#C44536",
|
||||
],
|
||||
"forest": [
|
||||
"#2D5A27",
|
||||
"#5B8C5A",
|
||||
"#8BC34A",
|
||||
"#C8E6C9",
|
||||
"#1B5E20",
|
||||
],
|
||||
}
|
||||
colors = palettes.get(theme.lower(), palettes["ocean"])[
|
||||
:num_colors
|
||||
]
|
||||
return json.dumps({"theme": theme, "colors": colors})
|
||||
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Color-Aware Design Team",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2,
|
||||
verbose=True,
|
||||
additional_tools=[generate_color_palette],
|
||||
)
|
||||
|
||||
result = swarm.run(
|
||||
"Design a landing page for an ocean-themed travel agency. "
|
||||
"Use the color palette tool to get appropriate colors for the design."
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,26 @@
|
||||
"""
|
||||
Multi-Page Wireframe Example
|
||||
|
||||
A complex task demonstrating context coordination between fairies.
|
||||
Creates a multi-page website wireframe with consistent elements.
|
||||
"""
|
||||
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Website Design Team",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=3,
|
||||
enable_context_refresh=True,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = swarm.run(
|
||||
"Create a multi-page website wireframe:\n"
|
||||
"1. Home page with hero section and feature highlights\n"
|
||||
"2. About page with team member cards\n"
|
||||
"3. Contact page with a form layout\n"
|
||||
"All pages must have consistent header and footer styling."
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,24 @@
|
||||
"""
|
||||
Selected Fairies Example
|
||||
|
||||
Run a task with a subset of fairies where one is elected as orchestrator.
|
||||
This mimics tldraw's behavior when you select multiple fairies and prompt the group.
|
||||
|
||||
The first fairy in the list becomes the orchestrator for the task.
|
||||
"""
|
||||
|
||||
from fairy_swarm import FairySwarm
|
||||
|
||||
swarm = FairySwarm(
|
||||
name="Creative Duo",
|
||||
model_name="gpt-4o-mini",
|
||||
max_loops=2,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
result = swarm.run_with_selected_fairies(
|
||||
task="Design a colorful banner for a summer music festival with bold typography and vibrant imagery",
|
||||
fairy_names=["Creative-Fairy", "Harmonizer-Fairy"],
|
||||
)
|
||||
|
||||
print(result)
|
||||
@ -0,0 +1,40 @@
|
||||
"""
|
||||
Standalone Tools Example
|
||||
|
||||
Use the fairy tools directly without creating a full swarm.
|
||||
Useful for understanding how the canvas and todo tools work.
|
||||
"""
|
||||
|
||||
import json
|
||||
from fairy_swarm import (
|
||||
SharedCanvasState,
|
||||
SharedTodoList,
|
||||
create_canvas_tool,
|
||||
create_spatial_layout_tool,
|
||||
)
|
||||
|
||||
canvas = SharedCanvasState()
|
||||
todos = SharedTodoList()
|
||||
|
||||
add_to_canvas = create_canvas_tool(canvas)
|
||||
calculate_layout = create_spatial_layout_tool()
|
||||
|
||||
layout_result = calculate_layout(
|
||||
layout_type="header-body-footer",
|
||||
num_elements=3,
|
||||
canvas_width=1200,
|
||||
canvas_height=800,
|
||||
)
|
||||
|
||||
layout = json.loads(layout_result)
|
||||
for pos in layout["positions"]:
|
||||
add_to_canvas(
|
||||
element_type="wireframe-section",
|
||||
content=f"Placeholder for {pos['role']}",
|
||||
position_x=pos["x"],
|
||||
position_y=pos["y"],
|
||||
width=pos["width"],
|
||||
height=pos["height"],
|
||||
)
|
||||
|
||||
print(json.dumps(canvas.get_snapshot(), indent=2, default=str))
|
||||
@ -0,0 +1,13 @@
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from swarms.utils.fetch_prompts_marketplace import (
|
||||
fetch_prompts_from_marketplace,
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
if __name__ == "__main__":
|
||||
prompt = fetch_prompts_from_marketplace(
|
||||
prompt_id="0ff9cc2f-390a-4eb1-9d3d-3a045cd2682e"
|
||||
)
|
||||
print(prompt)
|
||||
@ -0,0 +1,14 @@
|
||||
from swarms import Agent
|
||||
|
||||
# Create an agent with a marketplace prompt loaded in one line
|
||||
# Replace the marketplace_prompt_id with your actual prompt ID from the marketplace
|
||||
agent = Agent(
|
||||
model_name="gpt-4o-mini",
|
||||
marketplace_prompt_id="0ff9cc2f-390a-4eb1-9d3d-3a045cd2682e", # The prompt ID from the Swarms marketplace
|
||||
max_loops="auto",
|
||||
interactive=True,
|
||||
)
|
||||
|
||||
# Run the agent - it will use the system prompt loaded from the marketplace
|
||||
response = agent.run("Hello, what can you help me with?")
|
||||
print(response)
|
||||
@ -0,0 +1,193 @@
|
||||
"""
|
||||
Fetch Prompts from the Swarms Marketplace
|
||||
|
||||
This module provides utilities for fetching prompts from the Swarms marketplace API.
|
||||
It supports fetching prompts by either their unique UUID or by their name.
|
||||
|
||||
Environment Variables:
|
||||
SWARMS_API_KEY: Optional API key for authenticated requests. Required for
|
||||
accessing paid/premium prompt content.
|
||||
|
||||
Example:
|
||||
>>> from swarms.utils.fetch_prompts_marketplace import fetch_prompts_from_marketplace
|
||||
>>> name, description, prompt = fetch_prompts_from_marketplace(name="my-prompt")
|
||||
>>> print(f"Prompt: {name}")
|
||||
"""
|
||||
|
||||
import os
|
||||
import traceback
|
||||
from typing import Any, Dict, Optional, Tuple, Union
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
|
||||
def return_params(
|
||||
data: dict,
|
||||
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""
|
||||
Extract and return the core parameters from a prompt data dictionary.
|
||||
|
||||
Parses a dictionary containing prompt information and extracts the name,
|
||||
description, and prompt content fields.
|
||||
|
||||
Args:
|
||||
data (dict): A dictionary containing prompt data with the following
|
||||
expected keys:
|
||||
- "name": The name/title of the prompt
|
||||
- "description": A description of what the prompt does
|
||||
- "prompt": The actual prompt content/template
|
||||
|
||||
Returns:
|
||||
Tuple[Optional[str], Optional[str], Optional[str]]: A tuple containing:
|
||||
- name (Optional[str]): The prompt name, or None if not present
|
||||
- description (Optional[str]): The prompt description, or None if not present
|
||||
- prompt (Optional[str]): The prompt content, or None if not present
|
||||
|
||||
Example:
|
||||
>>> data = {
|
||||
... "name": "Code Review Assistant",
|
||||
... "description": "A prompt for reviewing code",
|
||||
... "prompt": "Review the following code for bugs..."
|
||||
... }
|
||||
>>> name, desc, prompt = return_params(data)
|
||||
>>> print(name)
|
||||
'Code Review Assistant'
|
||||
"""
|
||||
name = data.get("name")
|
||||
description = data.get("description")
|
||||
prompt = data.get("prompt")
|
||||
return name, description, prompt
|
||||
|
||||
|
||||
def fetch_prompts_from_marketplace(
|
||||
prompt_id: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
timeout: float = 30.0,
|
||||
return_params_on: bool = True,
|
||||
) -> Optional[
|
||||
Union[
|
||||
Dict[str, Any],
|
||||
Tuple[Optional[str], Optional[str], Optional[str]],
|
||||
]
|
||||
]:
|
||||
"""
|
||||
Fetch a prompt from the Swarms marketplace by UUID or by prompt name.
|
||||
|
||||
Retrieves prompt data from the Swarms marketplace API. You can fetch a prompt
|
||||
either by its unique UUID identifier or by its name. At least one of these
|
||||
parameters must be provided.
|
||||
|
||||
API Endpoints:
|
||||
- GET https://swarms.world/api/get-prompts/<uuid>
|
||||
- GET https://swarms.world/api/get-prompts/<prompt-name> (URL-encoded)
|
||||
|
||||
Args:
|
||||
prompt_id (Optional[str]): The unique UUID identifier of the prompt.
|
||||
Takes precedence over `name` if both are provided. Defaults to None.
|
||||
name (Optional[str]): The name of the prompt to fetch. Will be URL-encoded
|
||||
automatically. Defaults to None.
|
||||
timeout (float): Request timeout in seconds. Defaults to 30.0.
|
||||
return_params_on (bool): If True, returns a tuple of (name, description, prompt).
|
||||
If False, returns the full JSON response dictionary. Defaults to True.
|
||||
|
||||
Returns:
|
||||
Optional[Union[Dict[str, Any], Tuple[Optional[str], Optional[str], Optional[str]]]]:
|
||||
- If `return_params_on` is True: A tuple of (name, description, prompt)
|
||||
- If `return_params_on` is False: The full JSON response as a dictionary
|
||||
- None if the prompt was not found (404 response)
|
||||
|
||||
Raises:
|
||||
ValueError: If neither `prompt_id` nor `name` is provided.
|
||||
httpx.HTTPStatusError: If the API returns an error status code (except 404).
|
||||
httpx.TimeoutException: If the request exceeds the specified timeout.
|
||||
Exception: For any other unexpected errors during the request.
|
||||
|
||||
Note:
|
||||
Set the `SWARMS_API_KEY` environment variable to access paid/premium
|
||||
prompt content. The API key will be included as a Bearer token in
|
||||
the Authorization header.
|
||||
|
||||
Example:
|
||||
Fetch a prompt by name and get parsed parameters:
|
||||
|
||||
>>> name, description, prompt = fetch_prompts_from_marketplace(
|
||||
... name="code-review-assistant"
|
||||
... )
|
||||
>>> print(f"Name: {name}")
|
||||
>>> print(f"Description: {description}")
|
||||
|
||||
Fetch a prompt by UUID and get the full response:
|
||||
|
||||
>>> response = fetch_prompts_from_marketplace(
|
||||
... prompt_id="550e8400-e29b-41d4-a716-446655440000",
|
||||
... return_params_on=False
|
||||
... )
|
||||
>>> print(response.keys())
|
||||
|
||||
Handle a non-existent prompt:
|
||||
|
||||
>>> result = fetch_prompts_from_marketplace(name="non-existent-prompt")
|
||||
>>> if result is None:
|
||||
... print("Prompt not found")
|
||||
"""
|
||||
if not prompt_id and not name:
|
||||
raise ValueError("Either prompt_id or name must be provided")
|
||||
|
||||
api_key = os.getenv("SWARMS_API_KEY")
|
||||
|
||||
if api_key is None:
|
||||
raise ValueError(
|
||||
"Swarms API key is not set. Please set the SWARMS_API_KEY environment variable. "
|
||||
"You can get your key here: https://swarms.world/platform/api-keys"
|
||||
)
|
||||
|
||||
# New endpoint
|
||||
base_url = "https://swarms.world/api/get-prompts"
|
||||
id_or_name = (
|
||||
prompt_id if prompt_id else name
|
||||
) # exactly one is set here
|
||||
url = f"{base_url}/{quote(str(id_or_name), safe='')}"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
try:
|
||||
logger.debug(
|
||||
f"Fetching prompt: prompt_id={prompt_id}, name={name} url={url}"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=timeout) as client:
|
||||
response = client.get(url, headers=headers)
|
||||
|
||||
# 404 => not found
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
if return_params_on:
|
||||
return return_params(response.json())
|
||||
else:
|
||||
return response.json()
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"HTTP error fetching prompt: {e}")
|
||||
if e.response is not None:
|
||||
try:
|
||||
logger.error(
|
||||
f"Error response body: {e.response.json()}"
|
||||
)
|
||||
except Exception:
|
||||
logger.error(
|
||||
f"Error response text: {e.response.text}"
|
||||
)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error fetching prompt: {e} Traceback: {traceback.format_exc()}"
|
||||
)
|
||||
raise
|
||||
Loading…
Reference in new issue