Skip to content

Usage examples

Examples

Browse examples in the LiteLLM public model hub. You can find Postman requests examples JSON for every endpoint in the Teams Inference Channel on the "Released" section

Sending Requests to the API

You can use any OpenAI-API-compatible package. Example code snippet:

#!/usr/bin/env python
from typing import Dict, Any

from openai import OpenAI


class ServiceConnectionError(Exception):
    """Custom exception for LLM service connection issues."""
    pass


class Settings:
    DEFAULT_TEMPERATURE: float = 0.7


settings = Settings()


class LLMService:

    def __init__(self, api_key: str):
        # IMPORTANT: put your real PAT instead of the placeholder
        self.client = OpenAI(
            base_url="https://inference.mlmp.ti.bfh.ch/api/v1",
            api_key=api_key,  # your MLMP API key
        )

    def generate_completion(
        self,
        system_prompt: str,
        user_prompt: str,
        temperature: float = settings.DEFAULT_TEMPERATURE,
    ) -> Dict[str, Any]:
        try:
            response = self.client.chat.completions.create(
                model="gpt-oss:120b",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt},
                ],
                temperature=temperature,
            )

            return {
                "text": response.choices[0].message.content.strip(),
            }

        except Exception as e:
            # Name updated to match this service instead of "Ollama"
            raise ServiceConnectionError(
                f"Error connecting to LLM service: {str(e)}"
            ) from e


if __name__ == "__main__":
    # 1. Insert your real PAT here
    API_KEY = "<YOUR_API_KEY>"

    # 2. Instantiate the service
    llm_service = LLMService(api_key=API_KEY)

    # 3. Define prompts
    system_prompt = "You are a helpful assistant."
    user_prompt = "Give me a short explanation of what a Large Language Model is."

    # 4. Call the model
    try:
        result = llm_service.generate_completion(system_prompt, user_prompt)
        print("Model output:")
        print(result["text"])
    except ServiceConnectionError as e:
        print(f"Request failed: {e}")
# EOF

Create Embeddings

from openai import OpenAI


class ServiceConnectionError(Exception):
    pass


class EmbeddingService:

    def __init__(self):
        self.client = OpenAI(
            base_url="https://inference.mlmp.ti.bfh.ch/api/v1",
            api_key="<YOUR_API_KEY>"
        )

    def create_embedding(self, text: str) -> list[float]:
        try:
            response = self.client.embeddings.create(
                model="embeddinggemma:300m",
                input=text
            )

            return response.data[0].embedding

        except Exception as e:
            raise ServiceConnectionError(
                f"Error creating embedding: {str(e)}"
            )


if __name__ == "__main__":
    service = EmbeddingService()

    text = "This is a test sentence for generating an embedding."

    try:
        embedding = service.create_embedding(text)

        print(f"Embedding dimension: {len(embedding)}")
        print(f"First 10 values: {embedding[:10]}")

    except ServiceConnectionError as e:
        print(f"Failed to create embedding: {e}")

Create Transcriptions (No Diarization)

from openai import OpenAI
from typing import Dict, Any


class AudioTranscriptionService:

    def __init__(self):
        self.client = OpenAI(
            base_url="https://inference.mlmp.ti.bfh.ch/api/v1",
            api_key="<YOUR_API_KEY>"
        )

    def transcribe(
        self,
        file_path: str,
        model: str = "whisperx"
    ) -> Dict[str, Any]:
        try:
            with open(file_path, "rb") as audio_file:
                response = self.client.audio.transcriptions.create(
                    file=audio_file,
                    model=model
                )

            return {
                "text": response.text
            }

        except Exception as e:
            raise Exception(f"Transcription failed: {str(e)}")


def main():
    service = AudioTranscriptionService()

    file_path = "output.mp3"

    try:
        result = service.transcribe(file_path)

        print("Transcription:")
        print(result["text"])

    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()

Create Transcriptions + Diarization

Diarization data is dropped by our standard endpoint. Therefore, we have to grant you explicit access to a separate API. Please let us know in advance if you require diarization so we can provide you with the right API key.

There are more fields that you can use additional to 'diarize': 'true', For details go to the API reference section here: WhisperX Documentation

import requests
from typing import Dict, Any


class AudioTranscriptionService:

    def __init__(self, base_url: str = "https://inference.mlmp.ti.bfh.ch/api/v1", api_key: str = "<YOUR_API_KEY>"):
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key

    def transcribe(self, file_path: str, model: str = "whisperx", diarize: str = "true") -> Dict[str, Any]:
        url = self.base_url + "/audio/transcriptions"
        headers = {"Authorization": "Bearer " + self.api_key}

        with open(file_path, "rb") as audio_file:
            files = {"file": audio_file}
            data = {"model": model, "diarize": diarize}
            response = requests.post(url, headers=headers, files=files, data=data, timeout=300)

        response.raise_for_status()
        return response.json()  # full raw JSON, nothing dropped


# Usage example:
if __name__ == "__main__":
    service = AudioTranscriptionService()
    result = service.transcribe("output.mp3")
    print(result)

Create Audio

For details, visit the Qwen3 Documentation

from openai import OpenAI
from typing import Dict, Any


class AudioGenerationService:

    def __init__(self):
        self.client = OpenAI(
            base_url="https://inference.mlmp.ti.bfh.ch/api/v1",
            api_key="<YOUR_API_KEY>"
        )

    def generate(
        self,
        text: str,
        model: str = "qwen3-tts",
        voice: str = "Vivian",
        language: str = "English",
        instruct: str = "neutral, no emotion",
        output_file: str = "output.mp3"
    ) -> Dict[str, Any]:

        try:
            response = self.client.audio.speech.create(
                model=model,
                voice=voice,
                input=text
            )

            # Save audio to file
            with open(output_file, "wb") as f:
                f.write(response.content)

            return {
                "file": output_file
            }

        except Exception as e:
            raise Exception(f"TTS generation failed: {str(e)}")


def main():
    service = AudioGenerationService()

    text = (
        "Do not upload sensitive or personal data. "
        "You are responsible for how you use the platform and its outputs. "
        "The MLMP team does not guarantee accuracy and is not liable for misuse."
    )

    try:
        result = service.generate(
            text=text,
            output_file="output.mp3"
        )

        print(f"Audio saved to: {result['file']}")

    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()

Function calling

{
    "model": "gpt-oss:120b",
    "messages": [
        {
          "role": "user",
          "content": "What is the weather like in Paris today?"
        }
      ],
"tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
                "type": "string",
                "description": "The city and country, eg. San Francisco, USA"
            },
            "format": { "type": "string", "enum": ["celsius", "fahrenheit"] }
          },
          "required": ["location", "format"]
        }
      }
    }
   ]
  }

Source

Remote MCP tool calling

{
    "model": "gpt-oss:120b",
    "tools": [{
      "type": "mcp",
      "server_label": "tiktoken",
      "server_url": "https://gitmcp.io/openai/tiktoken",
      "allowed_tools": ["fetch_tiktoken_documentation"]
    }],
    "input": "What is the first sentence of the tiktoken documentation?"
}

Source

{
    "model": "gpt-oss:120b",
    "input": "What is happening in Switzerland today?",
    "tools": [
        {
            "type": "mcp",
            "server_label": "litellm",
            "server_url": "litellm_proxy",
            "require_approval": "never"
        }
    ],
    "stream": false,
    "tool_choice": "required"
}