🐍 DynaSpark Python Client

PyPI Version MIT License

A powerful, free Python client for the DynaSpark API - No API key required! 🆓

Getting Started

Installation

Install the package using pip:

pip install dynaspark
Note: The package requires Python 3.7 or higher.

Quick Start

Here's a simple example to get you started:

from dynaspark import DynaSpark

# Initialize client (no API key needed)
ds = DynaSpark()

# Generate text
response = ds.generate_response("What is artificial intelligence?")
print(response.get('response', ''))

# Generate image
image_url = ds.generate_image("A beautiful sunset over mountains")
print(f"Generated image: {image_url}")

# Generate audio response
audio_data = ds.generate_audio_response("Hello, this is a test!")
ds.save_audio(audio_data, "response.mp3")

Authentication

Currently, no API key is required to use the DynaSpark API. However, you can specify your own API key if needed:

from dynaspark import DynaSpark

# Initialize with custom API key (optional)
ds = DynaSpark(api_key="your_api_key")

API Reference

Client Initialization

DynaSpark()

Initialize a new DynaSpark client instance.

Parameters:

Parameter Type Description Default
api_key str Your API key (optional) None

Text Generation

generate_response(user_input)

Generate text responses using various models and parameters.

Parameters:

Parameter Type Description Default
user_input str The input text to generate a response for Required
model str Model to use for generation None
temperature float Controls randomness (0.0-3.0) 0.8
top_p float Controls diversity (0.0-1.0) 0.9
presence_penalty float Penalizes repeated tokens (-2.0-2.0) 0.0
frequency_penalty float Penalizes frequent tokens (-2.0-2.0) 0.0
system str Custom system prompt to guide the model's behavior None
referrer str Referrer information for tracking None
stream bool Stream the response as it's generated False
private bool Keep generation private (not logged) False
seed int Random seed for reproducible results None
json bool Return response in JSON format False

Example:

# Basic usage
response = ds.generate_response("What is Python?")

# Advanced usage with parameters
response = ds.generate_response(
    "Write a poem about technology",
    model="mistral",
    temperature=0.8,
    top_p=0.9,
    presence_penalty=0.6,
    frequency_penalty=0.6
)

Image Generation

generate_image(prompt)

Generate images from text descriptions.

Parameters:

Parameter Type Description Default
prompt str The prompt to generate an image for Required
width int Image width (64-2048) 768
height int Image height (64-2048) 768
model str Model to use (flux/turbo/gptimage) flux
nologo bool Exclude watermark False
wm str Custom watermark text None

Example:

# Basic usage
image_url = ds.generate_image("A serene mountain landscape")

# Advanced usage
image_url = ds.generate_image(
    "A futuristic city with flying cars",
    width=1024,
    height=768,
    model="flux",
    nologo=True,
    wm="DynaSpark"
)

Audio Generation

generate_audio_response(text, voice="alloy")

Generate audio responses from prompt using various voices.

Parameters:

Parameter Type Description Default
text str The text to convert to speech Required
voice str Voice to use alloy

Available Voices:

Voice Description
alloy Balanced, natural-sounding voice (default)
echo Clear, professional voice
fable Warm, engaging voice
onyx Deep, authoritative voice
nova Bright, energetic voice
shimmer Soft, melodic voice

Example:

# Basic usage
audio_data = ds.generate_audio_response("Hello, this is a test!")

# With different voice
audio_data = ds.generate_audio_response(
    "This is a test with a different voice.",
    voice="nova"
)

# Save to file
ds.save_audio(audio_data, "response.mp3")

Advanced Usage

Error Handling

The client provides custom exceptions for better error handling:

from dynaspark import DynaSpark, DynaSparkError

ds = DynaSpark()

try:
    response = ds.generate_response("Hello")
    print(response.get('response', ''))
except DynaSparkError as e:
    print(f"API Error: {e}")
except ValueError as e:
    print(f"Invalid Parameter: {e}")
except Exception as e:
    print(f"Unexpected Error: {e}")

Common Exceptions:

Exception Description
DynaSparkError Base exception for API errors
RateLimitError Raised when rate limit is exceeded
AuthenticationError Raised for authentication issues
ValidationError Raised for invalid parameters

Rate Limiting

The API implements rate limiting to ensure fair usage. The client automatically handles rate limits and provides information about your current usage:

# Get rate limit information
rate_limit = ds.get_rate_limit()
print(f"Remaining requests: {rate_limit.remaining}")
print(f"Reset time: {rate_limit.reset_time}")

Streaming Responses

For long text generations, you can use streaming to get responses as they're generated:

# Stream a response
for chunk in ds.generate_response(
    "Write a long story",
    stream=True
):
    print(chunk, end='', flush=True)

Examples

Text Generation Examples

Chat Completion:

response = ds.generate_response(
    "You are a helpful assistant. Explain quantum computing.",
    model="mistral",
    temperature=0.7
)
print(response['response'])

Code Generation:

response = ds.generate_response(
    "Write a Python function to sort a list of dictionaries by a key",
    model="qwen-coder",
    temperature=0.2
)
print(response['response'])

Image Generation Examples

Basic Image:

image_url = ds.generate_image(
    "A cute cat playing with yarn",
    model="flux"
)
print(f"Image URL: {image_url}")

High-Resolution Image:

image_url = ds.generate_image(
    "A detailed landscape of mountains at sunset",
    width=1024,
    height=768,
    model="turbo"
)
print(f"Image URL: {image_url}")

Audio Generation Examples

Basic Audio:

audio_data = ds.generate_audio_response(
    "Welcome to DynaSpark! This is a test of the audio generation.",
    voice="alloy"
)
ds.save_audio(audio_data, "welcome.mp3")

Multiple Voices:

# Generate audio with different voices
voices = ["alloy", "echo", "nova"]
for i, voice in enumerate(voices):
    audio_data = ds.generate_audio_response(
        f"This is voice {voice}",
        voice=voice
    )
    ds.save_audio(audio_data, f"voice_{i}.mp3")

Troubleshooting

Common Issues

Rate Limit Exceeded

If you see a rate limit error, wait for the reset time or reduce your request frequency.

Image Generation Fails

If image generation fails, check that your prompt is appropriate and within the allowed parameters.

Audio Generation Issues

If audio generation fails, ensure your text is not too long and contains valid characters.

FAQ

Frequently Asked Questions

Do I need an API key?

No, currently no API key is required to use the API. You can start using it right away!

What are the rate limits?

Free usage is limited to 100 requests per hour. Contact us for higher limits.

Can I use this in production?

Yes, the API is stable and suitable for production use. However, consider getting a custom API key for higher rate limits.