|
| 1 | +# structllm |
| 2 | + |
| 3 | +<div style="text-align: center;"> |
| 4 | + <img width="100%" src="structllm.svg" alt="Logo"> |
| 5 | +</div> |
| 6 | + |
| 7 | +[](https://badge.fury.io/py/structllm) |
| 8 | +[](https://pypi.org/project/structllm/) |
| 9 | +[](https://opensource.org/licenses/MIT) |
| 10 | + |
| 11 | +**structllm** is a universal and lightweight Python library that provides [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses) functionality for any LLM provider (OpenAI, Anthropic, Mistral, local models, etc.), not just OpenAI. It guarantees that LLM responses conform to your provided JSON schema using Pydantic models. |
| 12 | + |
| 13 | +If your LLM model has 7B parameters or more, it can be used with structllm. |
| 14 | + |
| 15 | +## Installation |
| 16 | + |
| 17 | +```bash |
| 18 | +pip install structllm |
| 19 | +``` |
| 20 | + |
| 21 | +Or using uv (recommended): |
| 22 | + |
| 23 | +```bash |
| 24 | +uv add structllm |
| 25 | +``` |
| 26 | + |
| 27 | +## Quick Start |
| 28 | + |
| 29 | +```python |
| 30 | +from pydantic import BaseModel |
| 31 | +from structllm import StructLLM |
| 32 | +from typing import List |
| 33 | + |
| 34 | +class CalendarEvent(BaseModel): |
| 35 | + name: str |
| 36 | + date: str |
| 37 | + participants: List[str] |
| 38 | + |
| 39 | +client = StructLLM( |
| 40 | + api_base="https://openrouter.ai/api/v1", |
| 41 | + api_key="sk-or-v1-...", |
| 42 | +) |
| 43 | + |
| 44 | +messages = [ |
| 45 | + {"role": "system", "content": "Extract the event information."}, |
| 46 | + {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."}, |
| 47 | +] |
| 48 | + |
| 49 | +response = client.parse( |
| 50 | + model="openrouter/moonshotai/kimi-k2", |
| 51 | + messages=messages, |
| 52 | + response_format=CalendarEvent, |
| 53 | +) |
| 54 | + |
| 55 | +if response.output_parsed: |
| 56 | + print(response.output_parsed) |
| 57 | + # {"name": "science fair", "date": "Friday", "participants": ["Alice", "Bob"]} |
| 58 | +else: |
| 59 | + print("Failed to parse structured output") |
| 60 | +``` |
| 61 | + |
| 62 | +## Provider Support |
| 63 | + |
| 64 | +StructLLM works with **100+ LLM providers** through LiteLLM. Check the [LiteLLM documentation](https://docs.litellm.ai/docs/providers) for the full list of supported providers. |
| 65 | + |
| 66 | +## Advanced Usage |
| 67 | + |
| 68 | +### Complex Data Structures |
| 69 | + |
| 70 | +```python |
| 71 | +from pydantic import BaseModel, Field |
| 72 | +from typing import List, Optional |
| 73 | +from enum import Enum |
| 74 | + |
| 75 | +class Priority(str, Enum): |
| 76 | + LOW = "low" |
| 77 | + MEDIUM = "medium" |
| 78 | + HIGH = "high" |
| 79 | + |
| 80 | +class Task(BaseModel): |
| 81 | + title: str = Field(description="The task title") |
| 82 | + description: Optional[str] = Field(default=None, description="Task description") |
| 83 | + priority: Priority = Field(description="Task priority level") |
| 84 | + assignees: List[str] = Field(description="List of assigned people") |
| 85 | + due_date: Optional[str] = Field(default=None, description="Due date in YYYY-MM-DD format") |
| 86 | + |
| 87 | +client = StructLLM( |
| 88 | + api_base="https://openrouter.ai/api/v1", |
| 89 | + api_key="sk-or-v1-...", |
| 90 | +) |
| 91 | + |
| 92 | +response = client.parse( |
| 93 | + model="gpt-4o-2024-08-06", |
| 94 | + messages=[ |
| 95 | + { |
| 96 | + "role": "user", |
| 97 | + "content": "Create a high-priority task for John and Sarah to review the quarterly report by next Friday." |
| 98 | + } |
| 99 | + ], |
| 100 | + response_format=Task, |
| 101 | +) |
| 102 | + |
| 103 | +task = response.output_parsed |
| 104 | +print(f"Task: {task.title}") |
| 105 | +print(f"Priority: {task.priority}") |
| 106 | +print(f"Assignees: {task.assignees}") |
| 107 | +``` |
| 108 | + |
| 109 | +### Error Handling |
| 110 | + |
| 111 | +```python |
| 112 | +response = client.parse( |
| 113 | + model="gpt-4o-2024-08-06", |
| 114 | + messages=messages, |
| 115 | + response_format=CalendarEvent, |
| 116 | +) |
| 117 | + |
| 118 | +if response.output_parsed: |
| 119 | + # Successfully parsed |
| 120 | + event = response.output_parsed |
| 121 | + print(f"Parsed event: {event}") |
| 122 | +else: |
| 123 | + # Parsing failed, but raw response is available |
| 124 | + print("Failed to parse structured output") |
| 125 | + print(f"Raw response: {response.raw_response.choices[0].message.content}") |
| 126 | +``` |
| 127 | + |
| 128 | +### Custom Configuration |
| 129 | + |
| 130 | +```python |
| 131 | +client = StructLLM( |
| 132 | + api_base="https://api.custom-provider.com/v1", |
| 133 | + api_key="your-api-key" |
| 134 | +) |
| 135 | + |
| 136 | +response = client.parse( |
| 137 | + model="custom/model-name", |
| 138 | + messages=messages, |
| 139 | + response_format=YourModel, |
| 140 | + temperature=0.1, |
| 141 | + top_p=0.1, |
| 142 | + max_tokens=1000, |
| 143 | + # Any additional parameters supported by the LiteLLM interface |
| 144 | + custom_parameter="value" |
| 145 | +) |
| 146 | +``` |
| 147 | + |
| 148 | +## How It Works |
| 149 | + |
| 150 | +StructLLM uses prompt engineering to ensure structured outputs: |
| 151 | + |
| 152 | +1. **Schema Injection**: Automatically injects your Pydantic model's JSON schema into the system prompt |
| 153 | +2. **Format Instructions**: Adds specific instructions for JSON-only responses |
| 154 | +3. **Intelligent Parsing**: Extracts JSON from responses even when wrapped in additional text |
| 155 | +4. **Validation**: Uses Pydantic for robust type checking and validation |
| 156 | +5. **Fallback Handling**: Gracefully handles parsing failures while preserving raw responses |
| 157 | + |
| 158 | +By default it uses low `temperature` and `top_p` settings to ensure consistent outputs, but you can customize these parameters as needed. |
| 159 | + |
| 160 | +## Testing |
| 161 | + |
| 162 | +Run the test suite: |
| 163 | + |
| 164 | +```bash |
| 165 | +# Install dependencies |
| 166 | +uv sync |
| 167 | + |
| 168 | +# Run tests |
| 169 | +uv run pytest |
| 170 | +uv run pytest -m "not integration" |
| 171 | + |
| 172 | +# Run integration tests (requires external services) |
| 173 | +uv run pytest -m "integration" |
| 174 | + |
| 175 | +# Run linting |
| 176 | +uv run ruff check . |
| 177 | +``` |
| 178 | + |
| 179 | +## Contributing |
| 180 | + |
| 181 | +Contributions are welcome! Please feel free to submit a Pull Request. |
| 182 | + |
| 183 | +1. Fork the repository |
| 184 | +2. Create a feature branch: `git checkout -b feature/amazing-feature` |
| 185 | +3. Make your changes with tests |
| 186 | +4. Run the test suite: `uv run pytest` |
| 187 | +5. Run linting: `uv run ruff check .` |
| 188 | +6. Submit a pull request |
| 189 | + |
| 190 | +## License |
| 191 | + |
| 192 | +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. |
| 193 | + |
| 194 | +## Acknowledgments |
| 195 | + |
| 196 | +- [LiteLLM](https://github.com/BerriAI/litellm) for providing the universal LLM interface |
| 197 | +- [Pydantic](https://github.com/pydantic/pydantic) for structured data validation |
0 commit comments