Skip to main content

A powerful AI framework with structured Pydantic responses, flexible LLM integration, and advanced agent capabilities

Project description

LiteLLM2

LiteLLM2 🚀

A powerful AI agent framework with structured Pydantic response handling and LLM integration capabilities.

Overview 🔍

LiteLLM2 is built on top of litellm and focuses on typesafe, structured responses through Pydantic models. Key features:

  • Structured Pydantic responses
  • Flexible LLM client integration 🔌
  • Budget management and caching 💰
  • Advanced agent system with tools 🛠️

Tech Stack 🔋

Installation 📦

pip install litellm2

Set up your API key:

export OPENROUTER_API_KEY=your_api_key_here

Quick Start ⚡

Basic Usage Example

from pydantic import Field
from typing import List, Optional, Any
from litellm2 import Request, LiteLLMClient
from drf_pydantic import BaseModel


class CustomAnswer(BaseModel):
    """Example custom answer model."""
    content: str = Field(..., description="The main content")
    keywords: List[str] = Field(default_factory=list, description="Keywords extracted from the response")
    sentiment: Optional[str] = Field(None, description="Sentiment analysis")


class TextAnalyzer:
    """Service for analyzing text using AI with structured responses."""

    def __init__(self):
        """Initialize the text analyzer with configuration."""
        self.config = Request(
            # Model configuration
            model="openrouter/openai/gpt-4o-mini-2024-07-18",
            answer_model=CustomAnswer,  # Required: Defines response structure
            temperature=0.7,
            max_tokens=500,

            # Performance features
            online=True,              # Enable web search capability
            cache_prompt=False,       # Disable prompt caching
            budget_limit=0.05,        # Set maximum budget per request

            # Debugging options
            verbose=True,             # Enable detailed output
            logs=False                # Enable logging
        )
        self.client = LiteLLMClient(self.config)

    def analyze_text(self, text: str, data_list: Any) -> CustomAnswer:
        """
        Analyze the provided text and return structured insights.

        Args:
            text (str): The text to analyze

        Returns:
            CustomAnswer: Structured analysis results
        """
        # Set up the conversation context
        self.client.msg.add_message_system(
            "You are an AI assistant that provides structured analysis with keywords and sentiment."
        )

        self.client.msg.add_message_block('DATA', data_list)

        # Add the text to analyze
        self.client.msg.add_message_user(f"Analyze the following text: '{text}'")

        # Generate and return structured response
        return self.client.generate_response()


# Example usage
if __name__ == "__main__":
    # Initialize the analyzer
    analyzer = TextAnalyzer()

    data_list = [
        {
            "name": "John Doe",
            "age": 30,
            "email": "john.doe@example.com"
        },
        {
            "name": "Jane Smith",
            "age": 25,
            "email": "jane.smith@example.com"
        }
    ]

    result = analyzer.analyze_text("John Doe is 30 years old and works at Google.", data_list)

    print('CONFIG:')
    print(analyzer.client.config.model_dump_json(indent=2))

    print('-' * 100)

    print('META:')
    print(analyzer.client.meta.model_dump_json(indent=2))

    print('*' * 100)

    print('RESULT:')
    print(result.model_dump_json(indent=2))

Key components in this example:

  • CustomAnswer: Pydantic model defining the response structure
  • Request configuration: Model settings, performance features, and debugging options
  • Message types: system, user, and block messages for structured input
  • Response handling: Typed responses with JSON output

Django Integration Example

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from drf_pydantic import BaseModel
from pydantic import Field
from typing import List
from litellm2 import Request, LiteLLMClient

class FeedbackAnalysis(BaseModel):
    summary: str = Field(..., description="Summary of the feedback")
    sentiment: str = Field(..., description="Detected sentiment")
    key_points: List[str] = Field(..., description="Key points from the feedback")

class FeedbackResponseSerializer(serializers.Serializer):
    answer = FeedbackAnalysis.drf_serializer()

class FeedbackView(APIView):
    def post(self, request):
        feedback = request.data.get('feedback', '')

        client = LiteLLMClient(Request(
            model="openrouter/openai/gpt-4o-mini",
            temperature=0.3,
            answer_model=FeedbackAnalysis
        ))

        client.msg.add_message_system("You are a feedback analysis expert.")
        client.msg.add_message_user(feedback)

        response: FeedbackAnalysis = client.generate_response()

        serializer = FeedbackResponseSerializer(data={
            "answer": response.model_dump()
        })
        serializer.is_valid(raise_exception=True)

        return Response(serializer.data)

Key features:

  • Seamless integration with Django REST framework
  • Automatic serialization of Pydantic models
  • Type-safe response handling
  • Built-in validation

Agent System Example

from litellm2.agents import SimpleAgent
from litellm2.utils.tools import Tool
from pydantic import BaseModel, Field
from typing import List
import datetime

class AgentResponse(BaseModel):
    answer: str = Field(..., description="The main answer")
    reasoning: str = Field(..., description="The reasoning process")
    tools_used: List[str] = Field(default_factory=list)

def get_current_time() -> str:
    """Get the current time."""
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def process_text(text: str) -> str:
    """Process text input."""
    return text.upper()

class MyAgent(SimpleAgent):
    def __init__(self):
        super().__init__(answer_model=AgentResponse)

        # Add tools
        self.add_tool(Tool(
            name="get_time",
            description="Get current time",
            func=get_current_time
        ))
        self.add_tool(Tool(
            name="process_text",
            description="Convert text to uppercase",
            func=process_text
        ))

# Usage
agent = MyAgent()
result = agent.run("What time is it and convert 'hello world' to uppercase")

Key features:

  • Custom tools integration
  • Structured responses with Pydantic
  • Automatic tool selection and execution
  • Type-safe tool inputs and outputs

About 👥

Developed by Unrealos Inc. - We create innovative AI-powered solutions for business.

License 📝

MIT License - see the LICENSE file for details.

Credits ✨

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

litellm2-1.0.4.tar.gz (40.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

litellm2-1.0.4-py2.py3-none-any.whl (45.1 kB view details)

Uploaded Python 2Python 3

File details

Details for the file litellm2-1.0.4.tar.gz.

File metadata

  • Download URL: litellm2-1.0.4.tar.gz
  • Upload date:
  • Size: 40.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for litellm2-1.0.4.tar.gz
Algorithm Hash digest
SHA256 1f75b58c09b8b6ee8d56a926e78732dd7d1d627995ddd3f2c5cbd2b8d3ac5db2
MD5 0e0301a5598ac96841e27f1304d354a7
BLAKE2b-256 d444283d60a0b70b16b6f6f7d32e713f5bc805c2158160461ceed6c0b07d4159

See more details on using hashes here.

File details

Details for the file litellm2-1.0.4-py2.py3-none-any.whl.

File metadata

  • Download URL: litellm2-1.0.4-py2.py3-none-any.whl
  • Upload date:
  • Size: 45.1 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for litellm2-1.0.4-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 758724709cb8968e6c75028e75b59d6251d6d57f95f4318b96cb1cc1889b4228
MD5 f253d86cfc8bbde4e1a4912cb3d04be3
BLAKE2b-256 ddf68be438a86bd0f2d274096eeb03b35a27aa49c0b62078c3788e36143ea313

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page