generate_image
Generate images from text prompts using AI models, supporting custom aspect ratios and multiple output formats for creative and practical applications.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | ||
| model | No | grok-imagine-image | |
| image_path | No | ||
| image_url | No | ||
| n | No | ||
| image_format | No | url | |
| aspect_ratio | No |
Implementation Reference
- src/server.py:113-148 (handler)The generate_image function is decorated with @mcp.tool() and handles image generation by communicating with the XAI API. It processes arguments, formats the request, calls the client, and constructs the response.
@mcp.tool() async def generate_image( prompt: str, model: str = "grok-imagine-image", image_path: Optional[str] = None, image_url: Optional[str] = None, n: int = 1, image_format: str = "url", aspect_ratio: Optional[str] = None ): client = Client(api_key=XAI_API_KEY) params = {"model": model, "prompt": prompt, "n": n, "image_format": image_format} if image_path: base64_string = encode_image_to_base64(image_path) ext = Path(image_path).suffix.lower().replace('.', '') params["image_url"] = f"data:image/{ext};base64,{base64_string}" elif image_url: params["image_url"] = image_url if aspect_ratio: params["aspect_ratio"] = aspect_ratio images = client.image.sample_batch(**params) client.close() result = ["## Generated Image(s)"] for i, img in enumerate(images, 1): result.append(f"\n**Image {i}:** {img.url}") if img.prompt and img.prompt != prompt: result.append(f"*Revised prompt:* {img.prompt}") return "\n".join(result)