Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions examples/images/google.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import json
import os

from dotenv import load_dotenv

from langbase import Langbase

load_dotenv()


def main():
# Check if API keys are available
langbase_api_key = os.getenv("LANGBASE_API_KEY")
google_api_key = os.getenv("GOOGLE_API_KEY")

if not langbase_api_key:
print("❌ LANGBASE_API_KEY is not set in environment variables")
return

if not google_api_key:
print("❌ GOOGLE_API_KEY is not set in environment variables")
print("Please add your Google API key to the .env file")
return

langbase = Langbase(api_key=langbase_api_key)

try:
result = langbase.images.generate(
prompt="A futuristic cityscape with flying cars and neon lights, cyberpunk style, highly detailed, 8k resolution",
model="google:gemini-2.5-flash-image-preview",
api_key=google_api_key,
)

print("✅ Image generated successfully!")
print("Generated images:", json.dumps(result, indent=2))

except Exception as error:
print(f"❌ Error generating image: {error}")


if __name__ == "__main__":
main()
41 changes: 41 additions & 0 deletions examples/images/openai.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import os

from dotenv import load_dotenv

from langbase import Langbase

load_dotenv()


def main():
# Check if API keys are available
langbase_api_key = os.getenv("LANGBASE_API_KEY")
openai_api_key = os.getenv("OPENAI_API_KEY")

if not langbase_api_key:
print("❌ LANGBASE_API_KEY is not set in environment variables")
return

if not openai_api_key:
print("❌ OPENAI_API_KEY is not set in environment variables")
print("Please add your OpenAI API key to the .env file")
return

langbase = Langbase(api_key=langbase_api_key)

try:
result = langbase.images.generate(
prompt="A futuristic cityscape with flying cars and neon lights, cyberpunk style, highly detailed, 8k resolution",
model="openai:gpt-image-1",
api_key=openai_api_key,
)

print("✅ Image generated successfully!")
print("Generated images:", result)

except Exception as error:
print(f"❌ Error generating image: {error}")


if __name__ == "__main__":
main()
42 changes: 42 additions & 0 deletions examples/images/openrouter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import os

from dotenv import load_dotenv

from langbase import Langbase

load_dotenv()


def main():
# Check if API keys are available
langbase_api_key = os.getenv("LANGBASE_API_KEY")
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")

if not langbase_api_key:
print("❌ LANGBASE_API_KEY is not set in environment variables")
return

if not openrouter_api_key:
print("❌ OPENROUTER_API_KEY is not set in environment variables")
print("Please add your OpenRouter API key to the .env file")
return

langbase = Langbase(api_key=langbase_api_key)

try:
result = langbase.images.generate(
prompt="A majestic dragon soaring through clouds above a fantasy castle, epic fantasy art style, detailed scales and wings",
model="openrouter:google/gemini-2.5-flash-image-preview",
api_key=openrouter_api_key,
)

print("✅ Image generated successfully via OpenRouter!")
print("Generated images:", result)

except Exception as error:
print(f"❌ Error generating image: {error}")
print("Note: Make sure you have a valid OpenRouter API key and credits")


if __name__ == "__main__":
main()
55 changes: 55 additions & 0 deletions examples/images/together.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import json
import os

from dotenv import load_dotenv

from langbase import Langbase

load_dotenv()


def main():
# Check if API keys are available
langbase_api_key = os.getenv("LANGBASE_API_KEY")
together_api_key = os.getenv("TOGETHER_API_KEY")

if not langbase_api_key:
print("❌ LANGBASE_API_KEY is not set in environment variables")
return

if not together_api_key:
print("❌ TOGETHER_API_KEY is not set in environment variables")
print("Please add your Together API key to the .env file")
return

langbase = Langbase(api_key=langbase_api_key)

try:
result = langbase.images.generate(
prompt="A serene mountain landscape at sunset with a crystal clear lake reflecting the sky",
model="together:black-forest-labs/FLUX.1-schnell-Free",
width=1024,
height=1024,
n=1,
api_key=together_api_key,
)

if (
not result.get("choices", [{}])[0]
.get("message", {})
.get("images", [{}])[0]
.get("image_url", {})
.get("url")
):
print("❌ Image generation did not return an image. Full response:", result)
return

print("✅ Image generated successfully!")
print(json.dumps(result, indent=2))

except Exception as error:
print(f"❌ Error generating image: {error}")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions langbase/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,4 @@
CHUNKER_ENDPOINT = "/v1/chunker"
PARSER_ENDPOINT = "/v1/parser"
AGENT_RUN_ENDPOINT = "/v1/agent/run"
IMAGES_ENDPOINT = "/v1/images"
2 changes: 2 additions & 0 deletions langbase/langbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .primitives.agent import Agent
from .primitives.chunker import Chunker
from .primitives.embed import Embed
from .primitives.images import Images
from .primitives.memories import Memories
from .primitives.parser import Parser
from .primitives.pipes import Pipes
Expand Down Expand Up @@ -43,6 +44,7 @@ def __init__(self, api_key: str = "", base_url: str = "https://api.langbase.com"
self.agent = Agent(self)
self.chunker_client = Chunker(self)
self.embed_client = Embed(self)
self.images = Images(self)
self.memories = Memories(self)
self.parser_client = Parser(self)
self.pipes = Pipes(self)
Expand Down
106 changes: 106 additions & 0 deletions langbase/primitives/images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""
Images API client for the Langbase SDK.
"""

from typing import Any, Dict, List, Optional

from langbase.constants import IMAGES_ENDPOINT
from langbase.request import Request
from langbase.types import ImageGenerationResponse


class Images:
"""
Client for image generation operations.

This class provides methods for generating images using various AI providers.
"""

def __init__(self, parent):
"""
Initialize the Images client.

Args:
parent: The parent Langbase instance
"""
self.parent = parent
self.request: Request = parent.request

def generate(
self,
prompt: str,
model: str,
api_key: str,
width: Optional[int] = None,
height: Optional[int] = None,
image_url: Optional[str] = None,
steps: Optional[int] = None,
n: Optional[int] = None,
negative_prompt: Optional[str] = None,
**kwargs: Any,
) -> ImageGenerationResponse:
"""
Generate images using various AI providers.

Args:
prompt: The text prompt to generate images from
model: The model to use for image generation
api_key: The API key for the image generation provider
width: Optional width of the generated image
height: Optional height of the generated image
image_url: Optional URL of an image for image-to-image generation
steps: Optional number of generation steps
n: Optional number of images to generate
negative_prompt: Optional negative prompt to avoid certain elements
**kwargs: Additional parameters for image generation

Returns:
ImageGenerationResponse containing generated images

Raises:
ValueError: If required options are missing
Exception: If the API request fails
"""
# Comprehensive input validation
if not prompt:
raise ValueError("Image generation prompt is required.")

if not model:
raise ValueError("Image generation model is required.")

if not api_key:
raise ValueError("Image generation API key is required.")

# Build image parameters
image_params: Dict[str, Any] = {
"prompt": prompt,
"model": model,
}

if width is not None:
image_params["width"] = width

if height is not None:
image_params["height"] = height

if image_url is not None:
image_params["image_url"] = image_url

if steps is not None:
image_params["steps"] = steps

if n is not None:
image_params["n"] = n

if negative_prompt is not None:
image_params["negative_prompt"] = negative_prompt

# Add any additional parameters
image_params.update(kwargs)

try:
return self.request.post(
IMAGES_ENDPOINT, image_params, headers={"LB-LLM-Key": api_key}
)
except Exception as error:
raise Exception(f"Image generation failed: {str(error)}")
39 changes: 39 additions & 0 deletions langbase/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,3 +774,42 @@ class AgentRunOptionsStreamT(TypedDict):

# Agent response type (reuses RunResponse)
AgentRunResponse = RunResponse


# Image generation types
class ImageUrlContent(TypedDict):
"""Image URL content structure."""

url: str


class ImageChoice(TypedDict):
"""Image generation choice structure."""

logprobs: None
finish_reason: str
native_finish_reason: str
index: int
message: Dict[str, Any]


class ImageUsage(TypedDict):
"""Image generation usage information."""

prompt_tokens: int
completion_tokens: int
total_tokens: int
prompt_tokens_details: Dict[str, int]
completion_tokens_details: Dict[str, int]


class ImageGenerationResponse(TypedDict):
"""Response from image generation."""

id: str
provider: str
model: str
object: str
created: int
choices: List[ImageChoice]
usage: ImageUsage