Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Gitlab based Prompt manager (#14988)

Deepanshu Lulla68adca04c81b
diff --git a/docs/my-website/docs/proxy/native_litellm_prompt.md b/docs/my-website/docs/proxy/native_litellm_prompt.md
index ea326d00690..34edb66fc40 100644
--- a/docs/my-website/docs/proxy/native_litellm_prompt.md
+++ b/docs/my-website/docs/proxy/native_litellm_prompt.md
@@ -9,7 +9,7 @@ Store prompts as `.prompt` files in your repository and use them directly with L
- **File System**: Store `.prompt` files locally
- **BitBucket**: Store `.prompt` files in BitBucket repositories with team-based access control
-
+- **Gitlab**: Store `.prompt` files in Gitlab repositories with team-based access control
## Quick Start
<Tabs>
@@ -90,6 +90,51 @@ response = litellm.completion(
```
</TabItem>
+<TabItem value="gitlab" label="GITLAB">
+
+**1. Create a .prompt file in a gitlab repo**
+
+Create `prompts/hello.prompt` in your gitlab repository:
+
+```yaml
+---
+model: gpt-4
+temperature: 0.7
+---
+System: You are a helpful assistant.
+
+User: {{user_message}}
+```
+
+**2. Configure Gitlab access**
+
+```python
+import litellm
+
+# Configure gitlab access
+gitlab_config = {
+ "workspace": "your-workspace",
+ "repository": "your-repo",
+ "access_token": "your-access-token",
+ "branch": "main"
+}
+
+# Set global gitlab configuration
+litellm.set_global_gitlab_config(gitlab_config)
+```
+
+**3. Use with LiteLLM**
+
+```python
+response = litellm.completion(
+ model="gitlab/gpt-4",
+ prompt_id="hello",
+ prompt_variables={"user_message": "What is the capital of France?"}
+)
+```
+
+</TabItem>
+
<TabItem value="proxy" label="PROXY">
**1. Create a .prompt file**
@@ -124,6 +169,12 @@ litellm_settings:
repository: "your-repo"
access_token: "your-access-token"
branch: "main"
+ # Or use Gitlab for team-based prompt management
+ global_gitlab_config:
+ workspace: "your-workspace"
+ repository: "your-repo"
+ access_token: "your-access-token"
+ branch: "main"
```
**3. Start the proxy**
@@ -213,6 +264,14 @@ prompt_variables: Optional[dict] # optional - variables for template rendering
bitbucket_config: Optional[dict] # optional - BitBucket configuration (if not set globally)
```
+**Gitlab:**
+```
+model: gitlab/<base_model> # required (e.g., gitlab/gpt-4)
+prompt_id: str # required - the .prompt filename without extension
+prompt_variables: Optional[dict] # optional - variables for template rendering
+gitlab_config: Optional[dict] # optional - Gitlab configuration (if not set globally)
+```
+
**Example API calls:**
```python
@@ -235,4 +294,18 @@ response = litellm.completion(
"access_token": "your-token"
}
)
+
+# Gitlab integration
+response = litellm.completion(
+ model="gitlab/gpt-4",
+ prompt_id="hello",
+ prompt_variables={"user_message": "Hello world"},
+ gitlab_config={
+ "project": "a/b/<repo_name>",
+ "access_token": "your-access-token",
+ "base_url": "gitlab url",
+ "prompts_path": "src/prompts", # folder to point to, defaults to root
+ "branch":"main" # optional, defaults to main
+ }
+)
```
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 328b5a6d89b..d961f42efde 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -152,6 +152,7 @@ _custom_logger_compatible_callbacks_literal = Literal[
"vector_store_pre_call_hook",
"dotprompt",
"bitbucket",
+ "gitlab",
"cloudzero",
"posthog",
]
@@ -1358,3 +1359,11 @@ def set_global_bitbucket_config(config: Dict[str, Any]) -> None:
"""Set global BitBucket configuration for prompt management."""
global global_bitbucket_config
global_bitbucket_config = config
+
+### GLOBAL CONFIG ###
+global_gitlab_config: Optional[Dict[str, Any]] = None
+
+def set_global_gitlab_config(config: Dict[str, Any]) -> None:
+ """Set global BitBucket configuration for prompt management."""
+ global global_gitlab_config
+ global_gitlab_config = config
diff --git a/litellm/integrations/gitlab/README.md b/litellm/integrations/gitlab/README.md
new file mode 100644
index 00000000000..14fb62905c8
--- /dev/null
+++ b/litellm/integrations/gitlab/README.md
@@ -0,0 +1,317 @@
+# LiteLLM gitlab Prompt Management
+
+A powerful prompt management system for LiteLLM that fetches `.prompt` files from gitlab repositories. This enables team-based prompt management with gitlab's built-in access control and version control capabilities.
+
+## Features
+
+- **🏢 Team-based access control**: Leverage gitlab's workspace and repository permissions
+- **📁 Repository-based prompt storage**: Store prompts in gitlab repositories
+- **🔐 Multiple authentication methods**: Support for access tokens and basic auth
+- **🎯 YAML frontmatter**: Define model, parameters, and schemas in file headers
+- **🔧 Handlebars templating**: Use `{{variable}}` syntax with Jinja2 backend
+- **✅ Input validation**: Automatic validation against defined schemas
+- **🔗 LiteLLM integration**: Works seamlessly with `litellm.completion()`
+- **💬 Smart message parsing**: Converts prompts to proper chat messages
+- **⚙️ Parameter extraction**: Automatically applies model settings from prompts
+
+## Quick Start
+
+### 1. Set up gitlab Repository
+
+Create a repository in your gitlab workspace and add `.prompt` files:
+
+```
+your-repo/
+├── prompts/
+│ ├── chat_assistant.prompt
+│ ├── code_reviewer.prompt
+│ └── data_analyst.prompt
+```
+
+### 2. Create a `.prompt` file
+
+Create a file called `prompts/chat_assistant.prompt`:
+
+```yaml
+---
+model: gpt-4
+temperature: 0.7
+max_tokens: 150
+input:
+ schema:
+ user_message: string
+ system_context?: string
+---
+
+{% if system_context %}System: {{system_context}}
+
+{% endif %}User: {{user_message}}
+```
+
+### 3. Configure gitlab Access
+
+#### Option A: Access Token (Recommended)
+
+```python
+import litellm
+
+# Configure gitlab access
+gitlab_config = {
+ "project": "a/b/<repo_name>",
+ "access_token": "your-access-token",
+ "base_url": "gitlab url",
+ "prompts_path": "src/prompts", # folder to point to, defaults to root
+ "branch":"main" # optional, defaults to main
+}
+
+# Set global gitlab configuration
+litellm.set_global_gitlab_config(gitlab_config)
+```
+
+#### Option B: Basic Authentication
+
+```python
+import litellm
+
+# Configure gitlab access with basic auth
+gitlab_config = {
+ "project": "a/b/<repo_name>",
+ "base_url": "base url",
+ "access_token": "your-app-password", # Use app password for basic auth
+ "branch": "main",
+ "prompts_path": "src/prompts", # folder to point to, defaults to root
+}
+
+litellm.set_global_gitlab_config(gitlab_config)
+```
+
+### 4. Use with LiteLLM
+
+```python
+# Use with completion - the model prefix 'gitlab/' tells LiteLLM to use gitlab prompt management
+response = litellm.completion(
+ model="gitlab/gpt-4", # The actual model comes from the .prompt file
+ prompt_id="prompts/chat_assistant", # Location of the prompt file
+ prompt_variables={
+ "user_message": "What is machine learning?",
+ "system_context": "You are a helpful AI tutor."
+ },
+ # Any additional messages will be appended after the prompt
+ messages=[{"role": "user", "content": "Please explain it simply."}]
+)
+
+print(response.choices[0].message.content)
+```
+
+## Proxy Server Configuration
+
+### 1. Create a `.prompt` file
+
+Create `prompts/hello.prompt`:
+
+```yaml
+---
+model: gpt-4
+temperature: 0.7
+---
+System: You are a helpful assistant.
+
+User: {{user_message}}
+```
+
+### 2. Setup config.yaml
+
+```yaml
+model_list:
+ - model_name: my-gitlab-model
+ litellm_params:
+ model: gitlab/gpt-4
+ prompt_id: "prompts/hello"
+ api_key: os.environ/OPENAI_API_KEY
+
+litellm_settings:
+ global_gitlab_config:
+ workspace: "your-workspace"
+ repository: "your-repo"
+ access_token: "your-access-token"
+ branch: "main"
+```
+
+### 3. Start the proxy
+
+```bash
+litellm --config config.yaml --detailed_debug
+```
+
+### 4. Test it!
+
+```bash
+curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
+-H 'Content-Type: application/json' \
+-H 'Authorization: Bearer sk-1234' \
+-d '{
+ "model": "my-gitlab-model",
+ "messages": [{"role": "user", "content": "IGNORED"}],
+ "prompt_variables": {
+ "user_message": "What is the capital of France?"
+ }
+}'
+```
+
+## Prompt File Format
+
+### Basic Structure
+
+```yaml
+---
+# Model configuration
+model: gpt-4
+temperature: 0.7
+max_tokens: 500
+
+# Input schema (optional)
+input:
+ schema:
+ user_message: string
+ system_context?: string
+---
+
+System: You are a helpful {{role}} assistant.
+
+User: {{user_message}}
+```
+
+### Advanced Features
+
+**Multi-role conversations:**
+
+```yaml
+---
+model: gpt-4
+temperature: 0.3
+---
+System: You are a helpful coding assistant.
+
+User: {{user_question}}
+```
+
+**Dynamic model selection:**
+
+```yaml
+---
+model: "{{preferred_model}}" # Model can be a variable
+temperature: 0.7
+---
+System: You are a helpful assistant specialized in {{domain}}.
+
+User: {{user_message}}
+```
+
+## Team-Based Access Control
+
+gitlab's built-in permission system provides team-based access control:
+
+1. **Workspace-level permissions**: Control access to entire workspaces
+2. **Repository-level permissions**: Control access to specific repositories
+3. **Branch-level permissions**: Control access to specific branches
+4. **User and group management**: Manage team members and their access levels
+
+### Setting up Team Access
+
+1. **Create workspaces for each team**:
+ ```
+ team-a-prompts/
+ team-b-prompts/
+ team-c-prompts/
+ ```
+
+2. **Configure repository permissions**:
+ - Grant read access to team members
+ - Grant write access to prompt maintainers
+ - Use branch protection rules for production prompts
+
+3. **Use different access tokens**:
+ - Each team can have their own access token
+ - Tokens can be scoped to specific repositories
+ - Use app passwords for additional security
+
+## API Reference
+
+### gitlab Configuration
+
+```python
+gitlab_config = {
+ "workspace": str, # Required: gitlab workspace name
+ "repository": str, # Required: Repository name
+ "access_token": str, # Required: gitlab access token or app password
+ "branch": str, # Optional: Branch to fetch from (default: "main")
+ "base_url": str, # Optional: Custom gitlab API URL
+ "auth_method": str, # Optional: "token" or "basic" (default: "token")
+ "username": str, # Optional: Username for basic auth
+ "base_url" : str # Optional: Incase where the base url is not https://api.gitlab.org/2.0
+}
+```
+
+### LiteLLM Integration
+
+```python
+response = litellm.completion(
+ model="gitlab/<base_model>", # required (e.g., gitlab/gpt-4)
+ prompt_id=str, # required - the .prompt filename without extension
+ prompt_variables=dict, # optional - variables for template rendering
+ gitlab_config=dict, # optional - gitlab configuration (if not set globally)
+ messages=list, # optional - additional messages
+)
+```
+
+## Error Handling
+
+The gitlab integration provides detailed error messages for common issues:
+
+- **Authentication errors**: Invalid access tokens or credentials
+- **Permission errors**: Insufficient access to workspace/repository
+- **File not found**: Missing .prompt files
+- **Network errors**: Connection issues with gitlab API
+
+## Security Considerations
+
+1. **Access Token Security**: Store access tokens securely using environment variables or secret management systems
+2. **Repository Permissions**: Use gitlab's permission system to control access
+3. **Branch Protection**: Protect main branches from unauthorized changes
+4. **Audit Logging**: gitlab provides audit logs for all repository access
+
+## Troubleshooting
+
+### Common Issues
+
+1. **"Access denied" errors**: Check your gitlab permissions for the workspace and repository
+2. **"Authentication failed" errors**: Verify your access token or credentials
+3. **"File not found" errors**: Ensure the .prompt file exists in the specified branch
+4. **Template rendering errors**: Check your Handlebars syntax in the .prompt file
+
+### Debug Mode
+
+Enable debug logging to troubleshoot issues:
+
+```python
+import litellm
+litellm.set_verbose = True
+
+# Your gitlab prompt calls will now show detailed logs
+response = litellm.completion(
+ model="gitlab/gpt-4",
+ prompt_id="your_prompt",
+ prompt_variables={"key": "value"}
+)
+```
+
+## Migration from File-Based Prompts
+
+If you're currently using file-based prompts with the dotprompt integration, you can easily migrate to gitlab:
+
+1. **Upload your .prompt files** to a gitlab repository
+2. **Update your configuration** to use gitlab instead of local files
+3. **Set up team access** using gitlab's permission system
+4. **Update your code** to use `gitlab/` model prefix instead of `dotprompt/`
+
+This provides better collaboration, version control, and team-based access control for your prompts.
diff --git a/litellm/integrations/gitlab/__init__.py b/litellm/integrations/gitlab/__init__.py
new file mode 100644
index 00000000000..cd22afc2ba0
--- /dev/null
+++ b/litellm/integrations/gitlab/__init__.py
@@ -0,0 +1,95 @@
+from typing import TYPE_CHECKING, Optional, Dict, Any
+
+if TYPE_CHECKING:
+ from .gitlab_prompt_manager import GitLabPromptManager
+ from litellm.types.prompts.init_prompts import PromptLiteLLMParams, PromptSpec
+ from litellm.integrations.custom_prompt_management import CustomPromptManagement
+
+from litellm.types.prompts.init_prompts import SupportedPromptIntegrations
+from litellm.integrations.custom_prompt_management import CustomPromptManagement
+from litellm.types.prompts.init_prompts import PromptSpec, PromptLiteLLMParams
+from .gitlab_prompt_manager import GitLabPromptManager
+
+# Global instances
+global_gitlab_config: Optional[dict] = None
+
+
+def set_global_gitlab_config(config: dict) -> None:
+ """
+ Set the global BitBucket configuration for prompt management.
+
+ Args:
+ config: Dictionary containing BitBucket configuration
+ - workspace: BitBucket workspace name
+ - repository: Repository name
+ - access_token: BitBucket access token
+ - branch: Branch to fetch prompts from (default: main)
+ """
+ import litellm
+
+ litellm.global_gitlab_config = config # type: ignore
+
+
+def prompt_initializer(
+ litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec"
+) -> "CustomPromptManagement":
+ """
+ Initialize a prompt from a BitBucket repository.
+ """
+ gitlab_config = getattr(litellm_params, "gitlab_config", None)
+ prompt_id = getattr(litellm_params, "prompt_id", None)
+
+
+ if not gitlab_config:
+ raise ValueError(
+ "bitbucket_config is required for BitBucket prompt integration"
+ )
+
+ try:
+ bitbucket_prompt_manager = GitLabPromptManager(
+ gitlab_config=gitlab_config,
+ prompt_id=prompt_id,
+ )
+
+ return bitbucket_prompt_manager
+ except Exception as e:
+ raise e
+
+def _gitlab_prompt_initializer(
+ litellm_params: PromptLiteLLMParams,
+ prompt: PromptSpec,
+) -> CustomPromptManagement:
+ """
+ Build a GitLab-backed prompt manager for this prompt.
+ Expected fields on litellm_params:
+ - prompt_integration="gitlab" (handled by the caller)
+ - gitlab_config: Dict[str, Any] (project/access_token/branch/prompts_path/etc.)
+ - git_ref (optional): per-prompt tag/branch/SHA override
+ """
+ # You can store arbitrary integration-specific config on PromptLiteLLMParams.
+ # If your dataclass doesn't have these attributes, add them or put inside
+ # `litellm_params.extra` and pull them from there.
+ gitlab_config: Dict[str, Any] = getattr(litellm_params, "gitlab_config", None) or {}
+ git_ref: Optional[str] = getattr(litellm_params, "git_ref", None)
+
+ if not gitlab_config:
+ raise ValueError("gitlab_config is required for gitlab prompt integration")
+
+ # prompt.prompt_id can map to a file path under prompts_path (e.g. "chat/greet/hi")
+ return GitLabPromptManager(
+ gitlab_config=gitlab_config,
+ prompt_id=prompt.prompt_id,
+ ref=git_ref,
+ )
+
+
+prompt_initializer_registry = {
+ SupportedPromptIntegrations.GITLAB.value: _gitlab_prompt_initializer,
+}
+
+# Export public API
+__all__ = [
+ "GitLabPromptManager",
+ "set_global_gitlab_config",
+ "global_gitlab_config",
+]
diff --git a/litellm/integrations/gitlab/gitlab_client.py b/litellm/integrations/gitlab/gitlab_client.py
new file mode 100644
index 00000000000..ce03a35d48e
--- /dev/null
+++ b/litellm/integrations/gitlab/gitlab_client.py
@@ -0,0 +1,285 @@
+"""
+GitLab API client for fetching files from GitLab repositories.
+Now supports selecting a tag via `config["tag"]`; falls back to branch ("main").
+"""
+
+import base64
+from typing import Any, Dict, List, Optional
+from urllib.parse import quote
+
+from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+
+class GitLabClient:
+ """
+ Client for interacting with the GitLab API to fetch files.
+
+ Supports:
+ - Authentication with personal/access tokens or OAuth bearer tokens
+ - Fetching file contents from repositories (raw endpoint with JSON fallback)
+ - Namespace/project path or numeric project ID addressing
+ - Ref selection via tag (preferred) or branch (default "main")
+ - Directory listing via the repository tree API
+ """
+
+ def __init__(self, config: Dict[str, Any]):
+ """
+ Initialize the GitLab client.
+
+ Args:
+ config: Dictionary containing:
+ - project: Project path ("group/subgroup/repo") or numeric project ID (str|int) [required]
+ - access_token: GitLab personal/access token or OAuth token [required] (str)
+ - auth_method: 'token' (default; sends Private-Token) or 'oauth' (Authorization: Bearer)
+ - tag: Tag name to fetch from (takes precedence over branch if provided)
+ - branch: Branch to fetch from (default: "main")
+ - base_url: Base GitLab API URL (default: "https://gitlab.com/api/v4")
+ """
+ project = config.get("project")
+ access_token = config.get("access_token")
+ if project is None or access_token is None:
+ raise ValueError("project and access_token are required")
+
+ self.project: str | int = project
+ self.access_token: str = str(access_token)
+ self.auth_method = config.get("auth_method", "token") # 'token' or 'oauth'
+ self.branch = config.get("branch", None)
+ if not self.branch:
+ self.branch = 'main'
+ self.tag = config.get("tag")
+ self.base_url = config.get("base_url", "https://gitlab.com/api/v4")
+
+ if not all([self.project, self.access_token]):
+ raise ValueError("project and access_token are required")
+
+ # Effective ref: prefer tag if provided, else branch ("main")
+ self.ref = str(self.tag or self.branch)
+
+ # Build headers
+ self.headers = {
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+ if self.auth_method == "oauth":
+ self.headers["Authorization"] = f"Bearer {self.access_token}"
+ else:
+ # Default GitLab token header
+ self.headers["Private-Token"] = self.access_token
+
+ # Project identifier must be URL-encoded (slashes become %2F)
+ self._project_enc = quote(str(self.project), safe="")
+
+ # HTTP handler
+ self.http_handler = HTTPHandler()
+
+ # ------------------------
+ # Core helpers
+ # ------------------------
+
+ def _file_raw_url(self, file_path: str, *, ref: Optional[str] = None) -> str:
+ file_enc = quote(file_path, safe="")
+ ref_q = quote(ref or self.ref, safe="")
+ return f"{self.base_url}/projects/{self._project_enc}/repository/files/{file_enc}/raw?ref={ref_q}"
+
+ def _file_json_url(self, file_path: str, *, ref: Optional[str] = None) -> str:
+ file_enc = quote(file_path, safe="")
+ ref_q = quote(ref or self.ref, safe="")
+ return f"{self.base_url}/projects/{self._project_enc}/repository/files/{file_enc}?ref={ref_q}"
+
+ def _tree_url(self, directory_path: str = "", recursive: bool = False, *, ref: Optional[str] = None) -> str:
+ path_q = f"&path={quote(directory_path, safe='')}" if directory_path else ""
+ rec_q = "&recursive=true" if recursive else ""
+ ref_q = quote(ref or self.ref, safe="")
+ return f"{self.base_url}/projects/{self._project_enc}/repository/tree?ref={ref_q}{path_q}{rec_q}"
+
+ # ------------------------
+ # Public API
+ # ------------------------
+
+ def set_ref(self, ref: str) -> None:
+ """Override the default ref (tag/branch) for subsequent calls."""
+ if not ref:
+ raise ValueError("ref must be a non-empty string")
+ self.ref = ref
+
+ def get_file_content(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]:
+ """
+ Fetch the content of a file from the GitLab repository at the given ref
+ (tag, branch, or commit SHA). If `ref` is None, uses self.ref.
+
+ Strategy:
+ 1) Try the RAW endpoint (returns bytes of the file)
+ 2) Fallback to the JSON endpoint (returns base64-encoded content)
+
+ Returns:
+ File content as UTF-8 string, or None if file not found.
+ """
+ raw_url = self._file_raw_url(file_path, ref=ref)
+
+ try:
+ resp = self.http_handler.get(raw_url, headers=self.headers)
+ if resp.status_code == 404:
+ # Fallback to JSON endpoint
+ return self._get_file_content_via_json(file_path, ref=ref)
+ resp.raise_for_status()
+
+ ctype = (resp.headers.get("content-type") or "").lower()
+ if ctype.startswith("text/") or "charset=" in ctype or ctype.startswith("application/json"):
+ return resp.text
+ try:
+ return resp.content.decode("utf-8")
+ except Exception:
+ return resp.content.decode("utf-8", errors="replace")
+
+ except Exception as e:
+ status = getattr(getattr(e, "response", None), "status_code", None)
+ if status == 404:
+ return None
+ if status == 403:
+ raise Exception(
+ f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'."
+ )
+ if status == 401:
+ raise Exception("Authentication failed. Check your GitLab token and auth_method.")
+ raise Exception(f"Failed to fetch file '{file_path}': {e}")
+
+ def _get_file_content_via_json(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]:
+ """
+ Fallback for get_file_content(): use the JSON file API which returns base64 content.
+ """
+ json_url = self._file_json_url(file_path, ref=ref)
+ try:
+ resp = self.http_handler.get(json_url, headers=self.headers)
+ if resp.status_code == 404:
+ return None
+ resp.raise_for_status()
+ data = resp.json()
+ content = data.get("content")
+ encoding = data.get("encoding", "")
+ if content and encoding == "base64":
+ try:
+ return base64.b64decode(content).decode("utf-8")
+ except Exception:
+ return base64.b64decode(content).decode("utf-8", errors="replace")
+ return content
+ except Exception as e:
+ status = getattr(getattr(e, "response", None), "status_code", None)
+ if status == 404:
+ return None
+ if status == 403:
+ raise Exception(
+ f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'."
+ )
+ if status == 401:
+ raise Exception("Authentication failed. Check your GitLab token and auth_method.")
+ raise Exception(f"Failed to fetch file '{file_path}' via JSON endpoint: {e}")
+
+ def list_files(
+ self,
+ directory_path: str = "",
+ file_extension: str = ".prompt",
+ recursive: bool = False,
+ *,
+ ref: Optional[str] = None,
+ ) -> List[str]:
+ """
+ List files in a directory with a specific extension using the repository tree API.
+
+ Args:
+ directory_path: Directory path in the repository (empty for repo root)
+ file_extension: File extension to filter by (default: .prompt)
+ recursive: If True, traverses subdirectories
+ ref: Optional override (tag/branch/SHA). Defaults to self.ref.
+
+ Returns:
+ List of file paths (relative to repo root)
+ """
+ url = self._tree_url(directory_path, recursive=recursive, ref=ref)
+
+ try:
+ resp = self.http_handler.get(url, headers=self.headers)
+ if resp.status_code == 404:
+ return []
+ resp.raise_for_status()
+
+ data = resp.json() or []
+ files: List[str] = []
+ for item in data:
+ if item.get("type") == "blob":
+ file_path = item.get("path", "")
+ if not file_extension or file_path.endswith(file_extension):
+ files.append(file_path)
+ return files
+
+ except Exception as e:
+ status = getattr(getattr(e, "response", None), "status_code", None)
+ if status == 404:
+ return []
+ if status == 403:
+ raise Exception(
+ f"Access denied to directory '{directory_path}'. Check your GitLab permissions for project '{self.project}'."
+ )
+ if status == 401:
+ raise Exception("Authentication failed. Check your GitLab token and auth_method.")
+ raise Exception(f"Failed to list files in '{directory_path}': {e}")
+
+ def get_repository_info(self) -> Dict[str, Any]:
+ """Get information about the project/repository."""
+ url = f"{self.base_url}/projects/{self._project_enc}"
+ try:
+ resp = self.http_handler.get(url, headers=self.headers)
+ resp.raise_for_status()
+ return resp.json()
+ except Exception as e:
+ raise Exception(f"Failed to get repository info: {e}")
+
+ def test_connection(self) -> bool:
+ """Test the connection to the GitLab project."""
+ try:
+ self.get_repository_info()
+ return True
+ except Exception:
+ return False
+
+ def get_branches(self) -> List[Dict[str, Any]]:
+ """Get list of branches in the repository."""
+ url = f"{self.base_url}/projects/{self._project_enc}/repository/branches"
+ try:
+ resp = self.http_handler.get(url, headers=self.headers)
+ resp.raise_for_status()
+ data = resp.json()
+ return data if isinstance(data, list) else []
+ except Exception as e:
+ raise Exception(f"Failed to get branches: {e}")
+
+ def get_file_metadata(self, file_path: str, *, ref: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ """
+ Get minimal metadata about a file via RAW endpoint headers at a given ref.
+
+ Args:
+ file_path: Path to the file in the repository.
+ ref: Optional override (tag/branch/SHA). Defaults to self.ref.
+ """
+ url = self._file_raw_url(file_path, ref=ref)
+ try:
+ headers = dict(self.headers)
+ headers["Range"] = "bytes=0-0"
+ resp = self.http_handler.get(url, headers=headers)
+ if resp.status_code == 404:
+ return None
+ resp.raise_for_status()
+ return {
+ "content_type": resp.headers.get("content-type"),
+ "content_length": resp.headers.get("content-length"),
+ "last_modified": resp.headers.get("last-modified"),
+ }
+ except Exception as e:
+ status = getattr(getattr(e, "response", None), "status_code", None)
+ if status == 404:
+ return None
+ raise Exception(f"Failed to get file metadata for '{file_path}': {e}")
+
+ def close(self):
+ """Close the HTTP handler to free resources."""
+ if hasattr(self, "http_handler"):
+ self.http_handler.close()
diff --git a/litellm/integrations/gitlab/gitlab_prompt_manager.py b/litellm/integrations/gitlab/gitlab_prompt_manager.py
new file mode 100644
index 00000000000..b782f10ccc5
--- /dev/null
+++ b/litellm/integrations/gitlab/gitlab_prompt_manager.py
@@ -0,0 +1,488 @@
+"""
+GitLab prompt manager with configurable prompts folder.
+"""
+
+from typing import Any, Dict, List, Optional, Tuple, Union
+from jinja2 import DictLoader, Environment, select_autoescape
+
+from litellm.integrations.custom_prompt_management import CustomPromptManagement
+from litellm.integrations.prompt_management_base import (
+ PromptManagementBase,
+ PromptManagementClient,
+)
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import StandardCallbackDynamicParams
+
+from litellm.integrations.gitlab.gitlab_client import GitLabClient
+
+
+class GitLabPromptTemplate:
+ def __init__(
+ self,
+ template_id: str,
+ content: str,
+ metadata: Dict[str, Any],
+ model: Optional[str] = None,
+ ):
+ self.template_id = template_id
+ self.content = content
+ self.metadata = metadata
+ self.model = model or metadata.get("model")
+ self.temperature = metadata.get("temperature")
+ self.max_tokens = metadata.get("max_tokens")
+ self.input_schema = metadata.get("input", {}).get("schema", {})
+ self.optional_params = {
+ k: v for k, v in metadata.items() if k not in ["model", "input", "content"]
+ }
+
+ def __repr__(self):
+ return f"GitLabPromptTemplate(id='{self.template_id}', model='{self.model}')"
+
+
+class GitLabTemplateManager:
+ """
+ Manager for loading and rendering .prompt files from GitLab repositories.
+
+ New: supports `prompts_path` (or `folder`) in gitlab_config to scope where prompts live.
+ """
+
+
+ def __init__(
+ self,
+ gitlab_config: Dict[str, Any],
+ prompt_id: Optional[str] = None,
+ ref: Optional[str] = None,
+ gitlab_client: Optional[GitLabClient] = None
+ ):
+ self.gitlab_config = dict(gitlab_config)
+ self.prompt_id = prompt_id
+ self.prompts: Dict[str, GitLabPromptTemplate] = {}
+ self.gitlab_client = gitlab_client or GitLabClient(self.gitlab_config)
+
+ if ref:
+ self.gitlab_client.set_ref(ref)
+
+ # Folder inside repo to look for prompts (e.g., "prompts" or "prompts/chat")
+ self.prompts_path: str = (
+ self.gitlab_config.get("prompts_path")
+ or self.gitlab_config.get("folder")
+ or ""
+ ).strip("/")
+
+ self.jinja_env = Environment(
+ loader=DictLoader({}),
+ autoescape=select_autoescape(["html", "xml"]),
+ variable_start_string="{{",
+ variable_end_string="}}",
+ block_start_string="{%",
+ block_end_string="%}",
+ comment_start_string="{#",
+ comment_end_string="#}",
+ )
+
+ if self.prompt_id:
+ self._load_prompt_from_gitlab(self.prompt_id)
+
+ # ---------- path helpers ----------
+
+ def _id_to_repo_path(self, prompt_id: str) -> str:
+ """Map a prompt_id to a repo path (respects prompts_path and adds .prompt)."""
+ if self.prompts_path:
+ return f"{self.prompts_path}/{prompt_id}.prompt"
+ return f"{prompt_id}.prompt"
+
+ def _repo_path_to_id(self, repo_path: str) -> str:
+ """
+ Map a repo path like 'prompts/chat/greeting.prompt' to an ID relative
+ to prompts_path without the extension (e.g., 'chat/greeting').
+ """
+ path = repo_path.strip("/")
+ if self.prompts_path and path.startswith(self.prompts_path.strip("/") + "/"):
+ path = path[len(self.prompts_path.strip("/")) + 1 :]
+ if path.endswith(".prompt"):
+ path = path[: -len(".prompt")]
+ return path
+
+ # ---------- loading ----------
+
+ def _load_prompt_from_gitlab(self, prompt_id: str, *, ref: Optional[str] = None) -> None:
+ """Load a specific .prompt file from GitLab (scoped under prompts_path if set)."""
+ try:
+ file_path = self._id_to_repo_path(prompt_id)
+ prompt_content = self.gitlab_client.get_file_content(file_path, ref=ref)
+ if prompt_content:
+ template = self._parse_prompt_file(prompt_content, prompt_id)
+ self.prompts[prompt_id] = template
+ except Exception as e:
+ raise Exception(f"Failed to load prompt '{prompt_id}' from GitLab: {e}")
+
+ def load_all_prompts(self, *, recursive: bool = True) -> List[str]:
+ """
+ Eagerly load all .prompt files from prompts_path. Returns loaded IDs.
+ """
+ files = self.list_templates(recursive=recursive) # reuse logic
+ loaded: List[str] = []
+ for pid in files:
+ if pid not in self.prompts:
+ self._load_prompt_from_gitlab(pid)
+ loaded.append(pid)
+ return loaded
+
+ # ---------- parsing & rendering ----------
+
+ def _parse_prompt_file(
+ self, content: str, prompt_id: str
+ ) -> GitLabPromptTemplate:
+ if content.startswith("---"):
+ parts = content.split("---", 2)
+ if len(parts) >= 3:
+ frontmatter_str = parts[1].strip()
+ template_content = parts[2].strip()
+ else:
+ frontmatter_str = ""
+ template_content = content
+ else:
+ frontmatter_str = ""
+ template_content = content
+
+ metadata: Dict[str, Any] = {}
+ if frontmatter_str:
+ try:
+ import yaml
+ metadata = yaml.safe_load(frontmatter_str) or {}
+ except ImportError:
+ metadata = self._parse_yaml_basic(frontmatter_str)
+ except Exception:
+ metadata = {}
+
+ return GitLabPromptTemplate(
+ template_id=prompt_id,
+ content=template_content,
+ metadata=metadata,
+ )
+
+ def _parse_yaml_basic(self, yaml_str: str) -> Dict[str, Any]:
+ result: Dict[str, Any] = {}
+ for line in yaml_str.split("\n"):
+ line = line.strip()
+ if ":" in line and not line.startswith("#"):
+ key, value = line.split(":", 1)
+ key = key.strip()
+ value = value.strip()
+ if value.lower() in ["true", "false"]:
+ result[key] = value.lower() == "true"
+ elif value.isdigit():
+ result[key] = int(value)
+ elif value.replace(".", "").isdigit():
+ try:
+ result[key] = float(value)
+ except Exception:
+ result[key] = value
+ else:
+ result[key] = value.strip("\"'")
+ return result
+
+ def render_template(
+ self, template_id: str, variables: Optional[Dict[str, Any]] = None
+ ) -> str:
+ if template_id not in self.prompts:
+ raise ValueError(f"Template '{template_id}' not found")
+ template = self.prompts[template_id]
+ jinja_template = self.jinja_env.from_string(template.content)
+ return jinja_template.render(**(variables or {}))
+
+ def get_template(self, template_id: str) -> Optional[GitLabPromptTemplate]:
+ return self.prompts.get(template_id)
+
+ def list_templates(self, *, recursive: bool = True) -> List[str]:
+ """
+ List available prompt IDs discovered under prompts_path (no extension, relative to prompts_path).
+ """
+ """
+ List available prompt IDs under prompts_path (no extension).
+ Compatible with both list_files signatures:
+ - list_files(directory_path=..., file_extension=..., recursive=...)
+ - list_files(path=..., ref=None, recursive=...)
+ """
+ # First try the "new" signature (directory_path/file_extension)
+ try:
+ files = self.gitlab_client.list_files(
+ directory_path=self.prompts_path,
+ file_extension=".prompt",
+ recursive=recursive,
+ )
+ base = self.prompts_path.strip("/")
+ out: List[str] = []
+ for p in files or []:
+ path = str(p).strip("/")
+ if base and not path.startswith(base + "/"):
+ # if the client returns extra files outside the folder, skip them
+ continue
+ if not path.endswith(".prompt"):
+ continue
+ out.append(self._repo_path_to_id(path))
+ return out
+ except TypeError:
+ # Fallback to the "classic" signature
+ raw = self.gitlab_client.list_files(
+ directory_path=self.prompts_path or "",
+ ref=None,
+ recursive=recursive,
+ )
+ # Classic returns GitLab tree entries; filter *.prompt blobs
+ files = []
+ for f in (raw or []):
+ if isinstance(f, dict) and f.get("type") == "blob" and str(f.get("path", "")).endswith(".prompt") and 'path' in f:
+ files.append(f['path'])
+
+ return [self._repo_path_to_id(p) for p in files]
+
+
+class GitLabPromptManager(CustomPromptManagement):
+ """
+ GitLab prompt manager with folder support.
+
+ Example config:
+ gitlab_config = {
+ "project": "group/subgroup/repo",
+ "access_token": "glpat_***",
+ "tag": "v1.2.3", # optional; takes precedence
+ "branch": "main", # default fallback
+ "prompts_path": "prompts/chat" # <--- NEW
+ }
+ """
+
+ def __init__(
+ self,
+ gitlab_config: Dict[str, Any],
+ prompt_id: Optional[str] = None,
+ ref: Optional[str] = None, # tag/branch/SHA override
+ gitlab_client: Optional[GitLabClient] = None
+ ):
+ self.gitlab_config = gitlab_config
+ self.prompt_id = prompt_id
+ self._prompt_manager: Optional[GitLabTemplateManager] = None
+ self._ref_override = ref
+ self._injected_gitlab_client = gitlab_client
+ if self.prompt_id:
+ self._prompt_manager = GitLabTemplateManager(
+ gitlab_config=self.gitlab_config,
+ prompt_id=self.prompt_id,
+ ref=self._ref_override,
+ )
+
+ @property
+ def integration_name(self) -> str:
+ return "gitlab"
+
+ @property
+ def prompt_manager(self) -> GitLabTemplateManager:
+ if self._prompt_manager is None:
+ self._prompt_manager = GitLabTemplateManager(
+ gitlab_config=self.gitlab_config,
+ prompt_id=self.prompt_id,
+ ref=self._ref_override,
+ gitlab_client=self._injected_gitlab_client
+ )
+ return self._prompt_manager
+
+ def get_prompt_template(
+ self,
+ prompt_id: str,
+ prompt_variables: Optional[Dict[str, Any]] = None,
+ *,
+ ref: Optional[str] = None,
+ ) -> Tuple[str, Dict[str, Any]]:
+ if prompt_id not in self.prompt_manager.prompts:
+ self.prompt_manager._load_prompt_from_gitlab(prompt_id, ref=ref)
+
+ template = self.prompt_manager.get_template(prompt_id)
+ if not template:
+ raise ValueError(f"Prompt template '{prompt_id}' not found")
+
+ rendered_prompt = self.prompt_manager.render_template(
+ prompt_id, prompt_variables or {}
+ )
+
+ metadata = {
+ "model": template.model,
+ "temperature": template.temperature,
+ "max_tokens": template.max_tokens,
+ **template.optional_params,
+ }
+ return rendered_prompt, metadata
+
+ def pre_call_hook(
+ self,
+ user_id: Optional[str],
+ messages: List[AllMessageValues],
+ function_call: Optional[Union[Dict[str, Any], str]] = None,
+ litellm_params: Optional[Dict[str, Any]] = None,
+ prompt_id: Optional[str] = None,
+ prompt_variables: Optional[Dict[str, Any]] = None,
+ prompt_version: Optional[str] = None,
+ **kwargs,
+ ) -> Tuple[List[AllMessageValues], Optional[Dict[str, Any]]]:
+ if not prompt_id:
+ return messages, litellm_params
+ try:
+ # Precedence: explicit prompt_version → per-call git_ref kwarg → manager override → config default
+ git_ref = prompt_version or kwargs.get("git_ref") or self._ref_override
+
+ rendered_prompt, prompt_metadata = self.get_prompt_template(
+ prompt_id, prompt_variables, ref=git_ref
+ )
+ parsed_messages = self._parse_prompt_to_messages(rendered_prompt)
+
+ if parsed_messages:
+ final_messages: List[AllMessageValues] = parsed_messages
+ else:
+ final_messages = [{"role": "user", "content": rendered_prompt}] + messages # type: ignore
+
+ if litellm_params is None:
+ litellm_params = {}
+
+ if prompt_metadata.get("model"):
+ litellm_params["model"] = prompt_metadata["model"]
+
+ for param in ["temperature", "max_tokens", "top_p", "frequency_penalty", "presence_penalty"]:
+ if param in prompt_metadata:
+ litellm_params[param] = prompt_metadata[param]
+
+ return final_messages, litellm_params
+ except Exception as e:
+ import litellm
+ litellm._logging.verbose_proxy_logger.error(f"Error in GitLab prompt pre_call_hook: {e}")
+ return messages, litellm_params
+
+
+ def _parse_prompt_to_messages(self, prompt_content: str) -> List[AllMessageValues]:
+ messages: List[AllMessageValues] = []
+ lines = prompt_content.strip().split("\n")
+ current_role: Optional[str] = None
+ current_content: List[str] = []
+
+ for raw in lines:
+ line = raw.strip()
+ if not line:
+ continue
+ low = line.lower()
+ if low.startswith("system:"):
+ if current_role and current_content:
+ messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # type: ignore
+ current_role = "system"
+ current_content = [line[7:].strip()]
+ elif low.startswith("user:"):
+ if current_role and current_content:
+ messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # type: ignore
+ current_role = "user"
+ current_content = [line[5:].strip()]
+ elif low.startswith("assistant:"):
+ if current_role and current_content:
+ messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # type: ignore
+ current_role = "assistant"
+ current_content = [line[10:].strip()]
+ else:
+ current_content.append(line)
+
+ if current_role and current_content:
+ messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # type: ignore
+ if not messages and prompt_content.strip():
+ messages = [{"role": "user", "content": prompt_content.strip()}] # type: ignore
+ return messages
+
+ def post_call_hook(
+ self,
+ user_id: Optional[str],
+ response: Any,
+ input_messages: List[AllMessageValues],
+ function_call: Optional[Union[Dict[str, Any], str]] = None,
+ litellm_params: Optional[Dict[str, Any]] = None,
+ prompt_id: Optional[str] = None,
+ prompt_variables: Optional[Dict[str, Any]] = None,
+ **kwargs,
+ ) -> Any:
+ return response
+
+ def get_available_prompts(self) -> List[str]:
+ """
+ Return prompt IDs. Prefer already-loaded templates in memory to avoid
+ unnecessary network calls (and to make tests deterministic).
+ """
+ ids = set(self.prompt_manager.prompts.keys())
+ try:
+ ids.update(self.prompt_manager.list_templates())
+ except Exception:
+ # If GitLab list fails (auth, network), still return what we've loaded.
+ pass
+ return sorted(ids)
+
+ def reload_prompts(self) -> None:
+ if self.prompt_id:
+ self._prompt_manager = None
+ _ = self.prompt_manager # trigger re-init/load
+
+ def should_run_prompt_management(
+ self,
+ prompt_id: str,
+ dynamic_callback_params: StandardCallbackDynamicParams,
+ ) -> bool:
+ return True
+
+ def _compile_prompt_helper(
+ self,
+ prompt_id: str,
+ prompt_variables: Optional[dict],
+ dynamic_callback_params: StandardCallbackDynamicParams,
+ prompt_label: Optional[str] = None,
+ prompt_version: Optional[int] = None,
+ ) -> PromptManagementClient:
+ try:
+ if prompt_id not in self.prompt_manager.prompts:
+ git_ref = getattr(dynamic_callback_params, "extra", {}).get("git_ref") if hasattr(dynamic_callback_params, "extra") else None
+ self.prompt_manager._load_prompt_from_gitlab(prompt_id, ref=git_ref)
+
+ rendered_prompt, prompt_metadata = self.get_prompt_template(
+ prompt_id, prompt_variables
+ )
+
+ messages = self._parse_prompt_to_messages(rendered_prompt)
+ template_model = prompt_metadata.get("model")
+
+ optional_params: Dict[str, Any] = {}
+ for param in ["temperature", "max_tokens", "top_p", "frequency_penalty", "presence_penalty"]:
+ if param in prompt_metadata:
+ optional_params[param] = prompt_metadata[param]
+
+ return PromptManagementClient(
+ prompt_id=prompt_id,
+ prompt_template=messages,
+ prompt_template_model=template_model,
+ prompt_template_optional_params=optional_params,
+ completed_messages=None,
+ )
+ except Exception as e:
+ raise ValueError(f"Error compiling prompt '{prompt_id}': {e}")
+
+ def get_chat_completion_prompt(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ non_default_params: dict,
+ prompt_id: Optional[str],
+ prompt_variables: Optional[dict],
+ dynamic_callback_params: StandardCallbackDynamicParams,
+ prompt_label: Optional[str] = None,
+ prompt_version: Optional[int] = None,
+ ) -> Tuple[str, List[AllMessageValues], dict]:
+ return PromptManagementBase.get_chat_completion_prompt(
+ self,
+ model,
+ messages,
+ non_default_params,
+ prompt_id,
+ prompt_variables,
+ dynamic_callback_params,
+ prompt_label,
+ prompt_version,
+ )
diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.py
index 4957c97e5b2..09794bf2677 100644
--- a/litellm/litellm_core_utils/custom_logger_registry.py
+++ b/litellm/litellm_core_utils/custom_logger_registry.py
@@ -16,6 +16,7 @@ from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheCont
from litellm.integrations.argilla import ArgillaLogger
from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLogger
from litellm.integrations.bitbucket import BitBucketPromptManager
+from litellm.integrations.gitlab import GitLabPromptManager
from litellm.integrations.braintrust_logging import BraintrustLogger
from litellm.integrations.datadog.datadog import DataDogLogger
from litellm.integrations.datadog.datadog_llm_obs import DataDogLLMObsLogger
@@ -92,6 +93,7 @@ class CustomLoggerRegistry:
"vector_store_pre_call_hook": VectorStorePreCallHook,
"dotprompt": DotpromptManager,
"bitbucket": BitBucketPromptManager,
+ "gitlab": GitLabPromptManager,
"cloudzero": CloudZeroLogger,
"posthog": PostHogLogger,
}
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 265e1eccb4d..b5ab5aeefe3 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -3669,6 +3669,25 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915
bitbucket_logger = BitBucketPromptManager(bitbucket_config=bitbucket_config)
_in_memory_loggers.append(bitbucket_logger)
return bitbucket_logger # type: ignore
+ elif logging_integration == "gitlab":
+ from litellm.integrations.gitlab.gitlab_prompt_manager import (
+ GitLabPromptManager,
+ )
+
+ for callback in _in_memory_loggers:
+ if isinstance(callback, GitLabPromptManager):
+ return callback
+
+ # Get global BitBucket config
+ gitlab_config = getattr(litellm, "global_gitlab_config", None)
+ if gitlab_config is None:
+ raise ValueError(
+ "Gitlab configuration not found. Please set litellm.global_gitlab_config first."
+ )
+
+ gitlab_logger = GitLabPromptManager(gitlab_config=gitlab_config)
+ _in_memory_loggers.append(gitlab_logger)
+ return gitlab_logger # type: ignore
return None
except Exception as e:
verbose_logger.exception(
diff --git a/litellm/proxy/prompts/prompt_registry.py b/litellm/proxy/prompts/prompt_registry.py
index a6fc377c1a7..b4717687704 100644
--- a/litellm/proxy/prompts/prompt_registry.py
+++ b/litellm/proxy/prompts/prompt_registry.py
@@ -175,4 +175,4 @@ class InMemoryPromptRegistry:
return self.prompt_id_to_custom_prompt.get(prompt_id)
-IN_MEMORY_PROMPT_REGISTRY = InMemoryPromptRegistry()
+IN_MEMORY_PROMPT_REGISTRY = InMemoryPromptRegistry()
\ No newline at end of file
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index f9cd1003a90..55e4a96b5b0 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -1877,6 +1877,15 @@ class ProxyConfig:
verbose_proxy_logger.info(
f"{blue_color_code}Set Global BitBucket Config on LiteLLM Proxy{reset_color_code}"
)
+ elif key == "global_gitlab_config":
+ from litellm.integrations.gitlab import (
+ set_global_gitlab_config,
+ )
+
+ set_global_gitlab_config(value)
+ verbose_proxy_logger.info(
+ f"{blue_color_code}Set Global Gitlab Config on LiteLLM Proxy{reset_color_code}"
+ )
elif key == "callbacks":
initialize_callbacks_on_proxy(
value=value,
diff --git a/litellm/types/prompts/init_prompts.py b/litellm/types/prompts/init_prompts.py
index 3c48cd131c3..184f0448b33 100644
--- a/litellm/types/prompts/init_prompts.py
+++ b/litellm/types/prompts/init_prompts.py
@@ -10,6 +10,7 @@ class SupportedPromptIntegrations(str, Enum):
LANGFUSE = "langfuse"
CUSTOM = "custom"
BITBUCKET = "bitbucket"
+ GITLAB = "gitlab"
class PromptInfo(BaseModel):
diff --git a/tests/test_litellm/integrations/gitlab/__init__.py b/tests/test_litellm/integrations/gitlab/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/integrations/gitlab/test_gitlab_client.py b/tests/test_litellm/integrations/gitlab/test_gitlab_client.py
new file mode 100644
index 00000000000..6e12fe7a08b
--- /dev/null
+++ b/tests/test_litellm/integrations/gitlab/test_gitlab_client.py
@@ -0,0 +1,281 @@
+import base64
+import json
+import os
+import sys
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+from litellm.integrations.gitlab.gitlab_client import GitLabClient
+
+
+# -----------------------------
+# Test doubles for HTTP layer
+# -----------------------------
+class HTTPError(Exception):
+ def __init__(self, msg, response=None):
+ super().__init__(msg)
+ self.response = response
+
+
+class FakeResponse:
+ def __init__(self, *, status_code=200, headers=None, text="", content=b"", json_data=None):
+ self.status_code = status_code
+ self.headers = headers or {}
+ self.text = text
+ self.content = content if content else text.encode("utf-8")
+ self._json_data = json_data
+
+ def json(self):
+ if self._json_data is not None:
+ return self._json_data
+ try:
+ return json.loads(self.text)
+ except Exception:
+ raise ValueError("Invalid JSON")
+
+ def raise_for_status(self):
+ if 400 <= self.status_code:
+ raise HTTPError(f"HTTP {self.status_code}", response=self)
+
+
+class StubHTTPHandler:
+ """
+ Minimal stub that returns a FakeResponse based on url.
+ Configure behavior by customizing self.routes in each test.
+ """
+ def __init__(self):
+ self.routes = {} # url -> FakeResponse or Exception
+ self.calls = [] # [(method, url, headers)]
+
+ def get(self, url, headers=None):
+ self.calls.append(("GET", url, headers or {}))
+ resp_or_exc = self.routes.get(url)
+ if isinstance(resp_or_exc, Exception):
+ raise resp_or_exc
+ if resp_or_exc is None:
+ # default: 404 not found
+ return FakeResponse(status_code=404, headers={"content-type": "application/json"}, text="{}")
+ return resp_or_exc
+
+ def close(self):
+ pass
+
+
+# -----------------------------
+# Fixtures / helpers
+# -----------------------------
+def make_client(**overrides):
+ cfg = {
+ "project": "group/sub/repo",
+ "access_token": "glpat_xxx",
+ "branch": "develop",
+ "base_url": "https://gitlab.example.com/api/v4",
+ }
+ cfg.update(overrides)
+ client = GitLabClient(cfg)
+ # swap in stub http handler
+ client.http_handler = StubHTTPHandler()
+ return client
+
+
+def enc_project(p): # how client encodes project in urls
+ return p.replace("/", "%2F")
+
+
+# -----------------------------
+# Constructor / config tests
+# -----------------------------
+def test_init_requires_project_and_token():
+ with pytest.raises(ValueError):
+ GitLabClient({"project": "p"})
+ with pytest.raises(ValueError):
+ GitLabClient({"access_token": "t"})
+
+
+def test_ref_prefers_tag_over_branch():
+ c = make_client(tag="v1.2.3", branch="main")
+ assert c.ref == "v1.2.3"
+
+
+def test_default_branch_is_main_when_absent():
+ c = make_client(branch=None) # explicit None
+ assert c.ref == 'main'
+
+
+def test_auth_header_token_default():
+ c = make_client()
+ assert c.headers.get("Private-Token") == "glpat_xxx"
+ assert "Authorization" not in c.headers
+
+
+def test_auth_header_oauth():
+ c = make_client(auth_method="oauth")
+ assert c.headers.get("Authorization") == "Bearer glpat_xxx"
+ assert "Private-Token" not in c.headers
+
+
+def test_set_ref_updates_effective_ref():
+ c = make_client(branch="main")
+ c.set_ref("feature/x")
+ assert c.ref == "feature/x"
+ with pytest.raises(ValueError):
+ c.set_ref("")
+
+
+# -----------------------------
+# get_file_content
+# -----------------------------
+def test_get_file_content_raw_text_success():
+ c = make_client(tag="release-1")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/path%2Fto%2Ffile.prompt/raw?ref=release-1"
+ c.http_handler.routes[raw_url] = FakeResponse(
+ status_code=200,
+ headers={"content-type": "text/plain; charset=utf-8"},
+ text="Hello world"
+ )
+ out = c.get_file_content("path/to/file.prompt")
+ assert out == "Hello world"
+ # ensure it used the expected URL
+ assert c.http_handler.calls[-1][1] == raw_url
+
+
+def test_get_file_content_raw_binary_utf8_decodes():
+ c = make_client(branch="main")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/bin%2Ffile.raw/raw?ref=main"
+ c.http_handler.routes[raw_url] = FakeResponse(
+ status_code=200,
+ headers={"content-type": "application/octet-stream"},
+ content="προμ pt".encode("utf-8")
+ )
+ out = c.get_file_content("bin/file.raw")
+ assert out == "προμ pt"
+
+
+def test_get_file_content_fallbacks_to_json_when_raw_404_and_decodes_base64():
+ c = make_client(branch="main")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/prompts%2Ffoo.prompt/raw?ref=main"
+ json_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/prompts%2Ffoo.prompt?ref=main"
+
+ c.http_handler.routes[raw_url] = FakeResponse(status_code=404, headers={"content-type": "application/json"}, text="{}")
+ encoded = base64.b64encode("FROM JSON".encode("utf-8")).decode("ascii")
+ c.http_handler.routes[json_url] = FakeResponse(
+ status_code=200,
+ headers={"content-type": "application/json"},
+ json_data={"content": encoded, "encoding": "base64"}
+ )
+
+ out = c.get_file_content("prompts/foo.prompt")
+ assert out == "FROM JSON"
+
+
+def test_get_file_content_returns_none_on_404_everywhere():
+ c = make_client(branch="main")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/ghost%2Fmissing.prompt/raw?ref=main"
+ json_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/ghost%2Fmissing.prompt?ref=main"
+ c.http_handler.routes[raw_url] = FakeResponse(status_code=404)
+ c.http_handler.routes[json_url] = FakeResponse(status_code=404)
+ assert c.get_file_content("ghost/missing.prompt") is None
+
+
+def test_get_file_content_permission_errors_are_mapped():
+ c = make_client(branch="main")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/secure%2Ffile.prompt/raw?ref=main"
+ # raise_for_status will be called, so return 403 response (not an exception from transport)
+ c.http_handler.routes[raw_url] = FakeResponse(status_code=403)
+ with pytest.raises(Exception) as ei:
+ c.get_file_content("secure/file.prompt")
+ assert "Access denied" in str(ei.value)
+
+ c.http_handler.routes[raw_url] = FakeResponse(status_code=401)
+ with pytest.raises(Exception) as ei2:
+ c.get_file_content("secure/file.prompt")
+ assert "Authentication failed" in str(ei2.value)
+
+
+# -----------------------------
+# list_files
+# -----------------------------
+def test_list_files_filters_by_extension_and_handles_recursive_flag():
+ c = make_client(branch="dev")
+ tree_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/tree?ref=dev&path=prompts&recursive=true"
+ c.http_handler.routes[tree_url] = FakeResponse(
+ status_code=200,
+ headers={"content-type": "application/json"},
+ json_data=[
+ {"type": "blob", "path": "prompts/a.prompt"},
+ {"type": "blob", "path": "prompts/b.txt"},
+ {"type": "blob", "path": "prompts/sub/c.prompt"},
+ {"type": "tree", "path": "prompts/sub"},
+ ],
+ )
+ files = c.list_files("prompts", ".prompt", recursive=True)
+ assert files == ["prompts/a.prompt", "prompts/sub/c.prompt"]
+
+
+def test_list_files_404_returns_empty_list():
+ c = make_client()
+ tree_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/tree?ref=develop&path=does%20not%20exist"
+ c.http_handler.routes[tree_url] = FakeResponse(status_code=404)
+ out = c.list_files("does not exist", ".prompt", recursive=False)
+ assert out == []
+
+
+def test_list_files_allows_ref_override():
+ c = make_client(branch="main")
+ url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/tree?ref=v2&path=prompts"
+ c.http_handler.routes[url] = FakeResponse(status_code=200, json_data=[])
+ out = c.list_files("prompts", ".prompt", ref="v2")
+ assert out == []
+ # verify correct URL used
+ assert c.http_handler.calls[-1][1] == url
+
+
+# -----------------------------
+# repo info / branches / metadata / connection
+# -----------------------------
+def test_get_repository_info_success():
+ c = make_client()
+ url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}"
+ c.http_handler.routes[url] = FakeResponse(status_code=200, json_data={"id": 123})
+ info = c.get_repository_info()
+ assert info["id"] == 123
+
+
+def test_test_connection_true_and_false():
+ c = make_client()
+ ok_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}"
+ c.http_handler.routes[ok_url] = FakeResponse(status_code=200, json_data={"id": 1})
+ assert c.test_connection() is True
+
+ # make it fail next time
+ c.http_handler.routes[ok_url] = FakeResponse(status_code=500)
+ assert c.test_connection() is False
+
+
+def test_get_branches_returns_list():
+ c = make_client()
+ url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/branches"
+ c.http_handler.routes[url] = FakeResponse(status_code=200, json_data=[{"name": "main"}])
+ branches = c.get_branches()
+ assert isinstance(branches, list)
+ assert branches[0]["name"] == "main"
+
+
+def test_get_file_metadata_parses_headers_and_handles_404():
+ c = make_client(branch="x")
+ raw_url = f"https://gitlab.example.com/api/v4/projects/{enc_project('group/sub/repo')}/repository/files/foo%2Fbar.raw/raw?ref=x"
+ c.http_handler.routes[raw_url] = FakeResponse(
+ status_code=200,
+ headers={"content-type": "application/octet-stream", "content-length": "1234", "last-modified": "Thu, 01 Jan 1970 00:00:00 GMT"},
+ content=b"\x00"
+ )
+ meta = c.get_file_metadata("foo/bar.raw")
+ assert meta["content_type"] == "application/octet-stream"
+ assert meta["content_length"] == "1234"
+
+ c.http_handler.routes[raw_url] = FakeResponse(status_code=404)
+ assert c.get_file_metadata("foo/bar.raw") is None
diff --git a/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py b/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py
new file mode 100644
index 00000000000..6ad7901459d
--- /dev/null
+++ b/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py
@@ -0,0 +1,455 @@
+import os
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from litellm.integrations.gitlab.gitlab_prompt_manager import GitLabPromptManager
+
+
+# -----------------------------
+# Basic init & template loading
+# -----------------------------
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_initialization_with_root_folder(mock_client_class):
+ """Loads a prompt from the repo root when no prompts_path is specified."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+temperature: 0.7
+max_tokens: 150
+---
+System: You are a helpful assistant.
+
+User: {{user_message}}"""
+ mock_client_class.return_value = mock_client
+
+ config = {
+ "project": "group/sub/repo",
+ "access_token": "glpat_xxx",
+ # no prompts_path -> root
+ }
+
+ manager = GitLabPromptManager(config, prompt_id="test_prompt")
+ # Should have loaded the prompt
+ assert "test_prompt" in manager.prompt_manager.prompts
+ template = manager.prompt_manager.prompts["test_prompt"]
+ assert template.model == "gpt-4"
+ assert template.temperature == 0.7
+ assert template.max_tokens == 150
+
+ # Ensures correct file path was requested at repo root (test_prompt.prompt)
+ mock_client.get_file_content.assert_called_with("test_prompt.prompt", ref=None)
+
+ # Rendering
+ rendered = manager.prompt_manager.render_template(
+ "test_prompt", {"user_message": "What is AI?"}
+ )
+ assert "You are a helpful assistant." in rendered
+ assert "What is AI?" in rendered
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_with_prompts_path(mock_client_class):
+ """Loads a prompt from a configured prompts folder; ID maps to folder + .prompt."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "Hello {{name}}!"
+ mock_client_class.return_value = mock_client
+
+ config = {
+ "project": "group/repo",
+ "access_token": "token",
+ "prompts_path": "prompts/chat", # folder setting
+ }
+
+ manager = GitLabPromptManager(config, prompt_id="greet/hi")
+ # Expected path: prompts/chat/greet/hi.prompt
+ mock_client.get_file_content.assert_called_with("prompts/chat/greet/hi.prompt", ref=None)
+
+ rendered = manager.prompt_manager.render_template("greet/hi", {"name": "World"})
+ assert rendered == "Hello World!"
+
+
+# -----------------------------
+# Error handling / validation
+# -----------------------------
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_error_handling_load(mock_client_class):
+ """Errors from GitLabClient surface with helpful context."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.side_effect = Exception("GitLab API error")
+ mock_client_class.return_value = mock_client
+
+ config = {"project": "g/s/r", "access_token": "tkn"}
+
+ with pytest.raises(Exception, match="Failed to load prompt 'oops' from GitLab"):
+ GitLabPromptManager(config, prompt_id="oops").prompt_manager # triggers load
+
+
+def test_gitlab_prompt_manager_config_validation_via_client_ctor():
+ """
+ If GitLabClient validates config in __init__, simulate that with a side_effect.
+ Ensures manager surfaces the ValueError while building prompt_manager.
+ """
+ with patch(
+ "litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient",
+ side_effect=ValueError("project and access_token are required"),
+ ):
+ with pytest.raises(ValueError, match="project and access_token are required"):
+ GitLabPromptManager({}).prompt_manager
+
+
+# -----------------------------
+# Message parsing
+# -----------------------------
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_message_parsing(mock_client_class):
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+---
+System: You are a helpful assistant.
+
+User: {{user_message}}
+
+Assistant: I'll help you with that."""
+ mock_client_class.return_value = mock_client
+
+ config = {"project": "g/s/r", "access_token": "t"}
+
+ manager = GitLabPromptManager(config, prompt_id="conversation_prompt")
+
+ messages = manager._parse_prompt_to_messages(
+ "System: You are a helpful assistant.\n\nUser: Hello!\n\nAssistant: Hi there!"
+ )
+ assert len(messages) == 3
+ assert messages[0]["role"] == "system"
+ assert messages[0]["content"] == "You are a helpful assistant."
+ assert messages[1]["role"] == "user"
+ assert messages[1]["content"] == "Hello!"
+ assert messages[2]["role"] == "assistant"
+ assert messages[2]["content"] == "Hi there!"
+
+
+# -----------------------------
+# pre_call_hook behavior & ref precedence
+# -----------------------------
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_pre_call_hook_updates_params(mock_client_class):
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4o
+temperature: 0.8
+max_tokens: 256
+---
+System: You are a helpful assistant.
+
+User: {{user_message}}"""
+ mock_client_class.return_value = mock_client
+
+ config = {"project": "g/s/r", "access_token": "tkn"}
+
+ manager = GitLabPromptManager(config, prompt_id="test_prompt")
+
+ original_messages = [{"role": "user", "content": "This will be ignored"}]
+ litellm_params = {"api_key": "keep-me"}
+
+ result_messages, result_params = manager.pre_call_hook(
+ user_id="u",
+ messages=original_messages,
+ litellm_params=litellm_params,
+ prompt_id="test_prompt",
+ prompt_variables={"user_message": "What is AI?"},
+ )
+
+ # Prompt parsed into messages
+ assert len(result_messages) == 2
+ assert result_messages[0]["role"] == "system"
+ assert result_messages[1]["role"] == "user"
+ assert result_messages[1]["content"] == "What is AI?"
+
+ # Params merged + preserved
+ assert result_params["model"] == "gpt-4o"
+ assert result_params["temperature"] == 0.8
+ assert result_params["max_tokens"] == 256
+ assert result_params["api_key"] == "keep-me"
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_pre_call_hook_ref_precedence(mock_client_class):
+ """
+ Precedence for selecting git ref:
+ prompt_version (arg) > git_ref kwarg > manager's _ref_override > client's default
+ Validate that the chosen ref gets passed down to client.get_file_content.
+ """
+ mock_client = MagicMock()
+
+ # Return any minimal valid prompt; we just need the call path to succeed.
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+---
+User: {{q}}"""
+ mock_client_class.return_value = mock_client
+
+ config = {"project": "g/s/r", "access_token": "tkn"}
+
+ # Set a manager-level default ref override
+ manager = GitLabPromptManager(config, prompt_id=None, ref="manager-default")
+
+ # 1) No prior load; call with prompt_version -> should win
+ _msgs, _params = manager.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="p1",
+ prompt_variables={"q": "hello"},
+ prompt_version="explicit-sha",
+ )
+ # get_file_content called with ref="explicit-sha"
+ mock_client.get_file_content.assert_any_call("p1.prompt", ref="explicit-sha")
+
+ # 2) Use git_ref kwarg (when no prompt_version)
+ _msgs, _params = manager.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="p2",
+ prompt_variables={"q": "hello"},
+ git_ref="per-call-branch",
+ )
+ mock_client.get_file_content.assert_any_call("p2.prompt", ref="per-call-branch")
+
+ # 3) Neither prompt_version nor git_ref -> falls back to manager _ref_override
+ _msgs, _params = manager.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="p3",
+ prompt_variables={"q": "hello"},
+ )
+ mock_client.get_file_content.assert_any_call("p3.prompt", ref="manager-default")
+
+
+# -----------------------------
+# Listing & availability
+# -----------------------------
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_list_templates_with_prompts_path(mock_client_class):
+ mock_client = MagicMock()
+ mock_client.list_files.return_value = [
+ "prompts/chat/a.prompt",
+ "prompts/chat/sub/b.prompt",
+ "prompts/chat/ignore.txt",
+ ]
+ mock_client.get_file_content.return_value = "Hello"
+ mock_client_class.return_value = mock_client
+
+ config = {
+ "project": "g/s/r",
+ "access_token": "tkn",
+ "prompts_path": "prompts/chat",
+ }
+
+ manager = GitLabPromptManager(config, prompt_id="a")
+
+ # list_templates strips folder prefix + extension
+ ids = manager.get_available_prompts()
+ assert "a" in ids
+ assert "sub/b" in ids
+ assert all(not x.endswith(".prompt") for x in ids)
+ assert all("/prompts/chat/" not in x for x in ids)
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_template_manager_load_all_prompts(mock_client_class):
+ """load_all_prompts should fetch all .prompt files and populate the internal cache."""
+ mock_client = MagicMock()
+ mock_client.list_files.return_value = [
+ "prompts/a.prompt",
+ "prompts/sub/b.prompt",
+ ]
+ mock_client.get_file_content.side_effect = [
+ "Hello {{x}}", # for a.prompt
+ "---\nmodel: gpt-4\n---\nUser: {{y}}", # for b.prompt with frontmatter
+ ]
+ mock_client_class.return_value = mock_client
+
+ config = {
+ "project": "g/s/r",
+ "access_token": "tkn",
+ "prompts_path": "prompts",
+ }
+
+ pm = GitLabPromptManager(config).prompt_manager
+ loaded = pm.load_all_prompts()
+ assert set(loaded) == {"a", "sub/b"}
+ assert "a" in pm.prompts and "sub/b" in pm.prompts
+
+
+# -----------------------------
+# post_call & integration name
+# -----------------------------
+def test_gitlab_prompt_manager_integration_name():
+ config = {"project": "g/s/r", "access_token": "tkn"}
+ manager = GitLabPromptManager(config)
+ assert manager.integration_name == "gitlab"
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_post_call_hook_passthrough(mock_client_class):
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{m}}"
+ mock_client_class.return_value = mock_client
+
+ config = {"project": "g/s/r", "access_token": "tkn"}
+
+ manager = GitLabPromptManager(config, prompt_id="p")
+
+ dummy_response = MagicMock()
+ out = manager.post_call_hook(
+ user_id="u",
+ response=dummy_response,
+ input_messages=[{"role": "user", "content": "x"}],
+ litellm_params={},
+ prompt_id="p",
+ )
+ assert out is dummy_response
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_version_precedence_prompt_version_wins(mock_client_class):
+ """
+ prompt_version > git_ref kwarg > manager _ref_override.
+ Ensure prompt_version wins and is passed down to GitLabClient.get_file_content.
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+---
+User: {{q}}"""
+ mock_client_class.return_value = mock_client
+
+ cfg = {"project": "g/s/r", "access_token": "tkn"}
+
+ # Manager with a default override ref
+ mgr = GitLabPromptManager(cfg, ref="manager-default")
+
+ # Provide both git_ref kwarg and prompt_version, the latter should win
+ msgs, params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="promptA",
+ prompt_variables={"q": "hello"},
+ prompt_version="sha-111", # highest precedence
+ git_ref="feature/branch-xyz", # should be ignored because prompt_version provided
+ )
+
+ mock_client.get_file_content.assert_any_call("promptA.prompt", ref="sha-111")
+ # sanity — prompt parsed and params returned
+ assert any(m["role"] == "user" for m in msgs)
+ assert params.get("model") == "gpt-4"
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_version_ref_kwarg_used_when_no_prompt_version(mock_client_class):
+ """
+ If prompt_version is omitted, git_ref kwarg should be used.
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{q}}"
+ mock_client_class.return_value = mock_client
+
+ cfg = {"project": "g/s/r", "access_token": "tkn"}
+ mgr = GitLabPromptManager(cfg, ref="fallback-manager-ref")
+
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="promptB",
+ prompt_variables={"q": "hi"},
+ git_ref="hotfix/ref-2", # used since prompt_version not provided
+ )
+
+ mock_client.get_file_content.assert_any_call("promptB.prompt", ref="hotfix/ref-2")
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_version_manager_override_used_when_no_prompt_version_or_kwarg(mock_client_class):
+ """
+ If neither prompt_version nor git_ref is supplied, fall back to manager-level ref override.
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{q}}"
+ mock_client_class.return_value = mock_client
+
+ cfg = {"project": "g/s/r", "access_token": "tkn"}
+ mgr = GitLabPromptManager(cfg, ref="manager-override-ref")
+
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="promptC",
+ prompt_variables={"q": "hey"},
+ )
+
+ mock_client.get_file_content.assert_any_call("promptC.prompt", ref="manager-override-ref")
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_get_prompt_template_explicit_ref_param(mock_client_class):
+ """
+ Directly calling get_prompt_template(ref=...) should pass that ref to GitLabClient.
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4o
+---
+User: {{x}}"""
+ mock_client_class.return_value = mock_client
+
+ cfg = {"project": "g/s/r", "access_token": "tkn"}
+ mgr = GitLabPromptManager(cfg)
+
+ rendered, metadata = mgr.get_prompt_template(
+ prompt_id="promptD",
+ prompt_variables={"x": "value"},
+ ref="v1.2.3", # explicit tag
+ )
+ mock_client.get_file_content.assert_any_call("promptD.prompt", ref="v1.2.3")
+ assert "value" in rendered
+ assert metadata.get("model") == "gpt-4o"
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_version_with_prompts_path(mock_client_class):
+ """
+ Ensure prompts_path + prompt_version work together (path resolution + ref).
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{q}}"
+ mock_client_class.return_value = mock_client
+
+ cfg = {
+ "project": "g/s/r",
+ "access_token": "tkn",
+ "prompts_path": "prompts/chat",
+ }
+ mgr = GitLabPromptManager(cfg)
+
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="folder/sub/my_prompt",
+ prompt_variables={"q": "ok"},
+ prompt_version="commit-sha-999",
+ )
+
+ # Path should include prompts_path and end with .prompt
+ mock_client.get_file_content.assert_any_call(
+ "prompts/chat/folder/sub/my_prompt.prompt", ref="commit-sha-999"
+ )
diff --git a/tests/test_litellm/integrations/gitlab/test_gitlab_prompt_manager.py b/tests/test_litellm/integrations/gitlab/test_gitlab_prompt_manager.py
new file mode 100644
index 00000000000..5b533fe7653
--- /dev/null
+++ b/tests/test_litellm/integrations/gitlab/test_gitlab_prompt_manager.py
@@ -0,0 +1,477 @@
+import os
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path
+
+from litellm.integrations.gitlab.gitlab_client import GitLabClient
+from litellm.integrations.gitlab.gitlab_prompt_manager import (
+ GitLabPromptManager,
+ GitLabPromptTemplate,
+)
+
+# -----------------------
+# GitLabPromptTemplate
+# -----------------------
+
+def test_gitlab_prompt_template_creation():
+ """Test GitLabPromptTemplate creation and metadata extraction."""
+ metadata = {
+ "model": "gpt-4",
+ "temperature": 0.7,
+ "input": {"schema": {"text": "string"}},
+ "output": {"format": "json"},
+ }
+
+ template = GitLabPromptTemplate(
+ template_id="test_template",
+ content="Hello {{name}}!",
+ metadata=metadata,
+ )
+
+ assert template.template_id == "test_template"
+ assert template.content == "Hello {{name}}!"
+ assert template.model == "gpt-4"
+ assert template.optional_params["temperature"] == 0.7
+ assert template.input_schema == {"text": "string"}
+
+
+# -----------------------
+# GitLabClient init & validation
+# -----------------------
+
+def test_gitlab_client_initialization_token_vs_oauth():
+ """Test GitLabClient initialization with token and oauth auth methods."""
+ # token (default)
+ config_token = {
+ "project": "group/sub/repo",
+ "access_token": "glpat-XYZ",
+ "branch": "main",
+ }
+ client = GitLabClient(config_token)
+ assert client.project == "group/sub/repo"
+ assert client.access_token == "glpat-XYZ"
+ assert client.branch == "main"
+ assert client.auth_method == "token"
+ # token header is used
+ assert client.headers.get("Private-Token") == "glpat-XYZ"
+ assert "Authorization" not in client.headers
+
+ # oauth
+ config_oauth = {
+ "project": 123456, # numeric project id supported
+ "access_token": "oauth-bearer",
+ "auth_method": "oauth",
+ }
+ client_oauth = GitLabClient(config_oauth)
+ assert client_oauth.auth_method == "oauth"
+ assert client_oauth.headers.get("Authorization") == "Bearer oauth-bearer"
+ assert "Private-Token" not in client_oauth.headers
+
+
+def test_gitlab_client_missing_required_fields():
+ """Test GitLabClient initialization with missing required fields."""
+ with pytest.raises(ValueError, match="project and access_token are required"):
+ GitLabClient({"project": "group/x/repo"})
+ with pytest.raises(ValueError, match="project and access_token are required"):
+ GitLabClient({"access_token": "tok"})
+
+
+# -----------------------
+# GitLabClient: get_file_content
+# -----------------------
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_get_file_content_raw_success(mock_get):
+ """Successful file content retrieval via RAW endpoint."""
+ mock_response = MagicMock()
+ mock_response.text = "file content"
+ mock_response.content = b"file content"
+ mock_response.headers = {"content-type": "text/plain"}
+ mock_response.status_code = 200
+ mock_response.raise_for_status.return_value = None
+ mock_get.return_value = mock_response
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ content = client.get_file_content("prompts/test.prompt")
+ assert content == "file content"
+ mock_get.assert_called_once()
+
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_get_file_content_raw_404_fallback_json_base64(mock_get):
+ """When RAW returns 404, fallback to JSON endpoint and decode base64 content."""
+ import base64
+
+ # First RAW 404
+ resp_raw = MagicMock()
+ resp_raw.status_code = 404
+ resp_raw.raise_for_status.side_effect = Exception()
+ mock_get.side_effect = [resp_raw]
+
+ # Then JSON OK
+ resp_json = MagicMock()
+ encoded = base64.b64encode(b"json-content").decode("utf-8")
+ resp_json.json.return_value = {"content": encoded, "encoding": "base64"}
+ resp_json.status_code = 200
+ resp_json.raise_for_status.return_value = None
+
+ # We need mock_get to return JSON response second time; easiest: reset side_effect to list of returns
+ def side_effect(url, headers):
+ if "/raw?" in url:
+ return resp_raw
+ else:
+ return resp_json
+
+ mock_get.side_effect = side_effect
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ content = client.get_file_content("prompts/test.prompt")
+ assert content == "json-content"
+
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_get_file_content_not_found(mock_get):
+ """File not found returns None."""
+ # Simulate RAW 404 and JSON 404
+ resp_404 = MagicMock()
+ resp_404.status_code = 404
+ resp_404.raise_for_status.side_effect = Exception()
+ def side_effect(url, headers):
+ return resp_404
+ mock_get.side_effect = side_effect
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ content = client.get_file_content("missing.prompt")
+ assert content is None
+
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_get_file_content_access_denied(mock_get):
+ """403 raises a helpful message."""
+ import httpx
+ resp = MagicMock()
+ resp.status_code = 403
+ # raise_for_status inside client only called on non-404 success path;
+ # simulate exception path by making the request itself raise an httpx error wrapper
+ err = httpx.HTTPStatusError("403", request=MagicMock(), response=resp)
+ mock_get.side_effect = err
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ with pytest.raises(Exception, match="Access denied to file 'test.prompt'"):
+ client.get_file_content("test.prompt")
+
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_get_file_content_auth_failed(mock_get):
+ """401 raises auth error."""
+ import httpx
+ resp = MagicMock()
+ resp.status_code = 401
+ err = httpx.HTTPStatusError("401", request=MagicMock(), response=resp)
+ mock_get.side_effect = err
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ with pytest.raises(Exception, match="Authentication failed"):
+ client.get_file_content("test.prompt")
+
+
+# -----------------------
+# GitLabClient: list_files
+# -----------------------
+
+@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.get")
+def test_gitlab_client_list_files_success(mock_get):
+ """List .prompt files via repository tree API."""
+ mock_response = MagicMock()
+ mock_response.json.return_value = [
+ {"type": "blob", "path": "prompts/test1.prompt"},
+ {"type": "blob", "path": "prompts/test2.prompt"},
+ {"type": "blob", "path": "prompts/other.txt"},
+ {"type": "tree", "path": "prompts/subdir"},
+ ]
+ mock_response.status_code = 200
+ mock_response.raise_for_status.return_value = None
+ mock_get.return_value = mock_response
+
+ client = GitLabClient({"project": "g/s/r", "access_token": "tok"})
+ files = client.list_files("prompts", ".prompt", recursive=True)
+
+ assert files == ["prompts/test1.prompt", "prompts/test2.prompt"]
+
+
+# -----------------------
+# GitLabTemplateManager: parsing & rendering
+# -----------------------
+
+def test_gitlab_prompt_manager_parse_prompt_file():
+ """Parse .prompt with YAML frontmatter."""
+ prompt_content = """---
+model: gpt-4
+temperature: 0.7
+max_tokens: 150
+input:
+ schema:
+ user_message: string
+ system_context?: string
+---
+
+{% if system_context %}System: {{system_context}}
+
+{% endif %}User: {{user_message}}"""
+
+ manager = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+ template = manager.prompt_manager._parse_prompt_file(prompt_content, "test_prompt")
+
+ assert template.template_id == "test_prompt"
+ assert template.model == "gpt-4"
+ assert template.temperature == 0.7
+ assert template.max_tokens == 150
+ assert template.input_schema == {"user_message": "string", "system_context?": "string"}
+ assert "{% if system_context %}" in template.content
+
+
+def test_gitlab_prompt_manager_parse_prompt_file_no_frontmatter():
+ """Parse .prompt without YAML frontmatter."""
+ prompt_content = "Simple prompt: {{message}}"
+ manager = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+ template = manager.prompt_manager._parse_prompt_file(prompt_content, "simple_prompt")
+ assert template.template_id == "simple_prompt"
+ assert template.content == "Simple prompt: {{message}}"
+ assert template.metadata == {}
+
+
+def test_gitlab_prompt_manager_render_template_and_errors():
+ """Render a stored template; error if missing."""
+ manager = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+
+ tpl = GitLabPromptTemplate(
+ template_id="t1",
+ content="Hello {{name}}! Welcome to {{place}}.",
+ metadata={"model": "gpt-4"},
+ )
+ manager.prompt_manager.prompts["t1"] = tpl
+
+ rendered = manager.prompt_manager.render_template("t1", {"name": "World", "place": "Earth"})
+ assert rendered == "Hello World! Welcome to Earth."
+
+ with pytest.raises(ValueError, match="Template 'nope' not found"):
+ manager.prompt_manager.render_template("nope", {})
+
+
+# -----------------------
+# GitLabPromptManager: integration & behavior
+# -----------------------
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_integration(mock_client_class):
+ """Load prompt on init and render."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+temperature: 0.7
+---
+Hello {{name}}!"""
+ mock_client_class.return_value = mock_client
+
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"}, prompt_id="test_prompt")
+ assert "test_prompt" in mgr.prompt_manager.prompts
+
+ template = mgr.prompt_manager.prompts["test_prompt"]
+ assert template.model == "gpt-4"
+ assert template.temperature == 0.7
+
+ rendered = mgr.prompt_manager.render_template("test_prompt", {"name": "World"})
+ assert rendered == "Hello World!"
+
+
+def test_gitlab_prompt_manager_parse_prompt_to_messages():
+ """Parse prompt content into chat messages."""
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+
+ # single user msg
+ simple = "Hello there!"
+ msgs = mgr._parse_prompt_to_messages(simple)
+ assert msgs == [{"role": "user", "content": "Hello there!"}]
+
+ # multi-role
+ multi = """System: You are helpful.
+
+User: Hi?
+
+Assistant: Hello!"""
+ msgs = mgr._parse_prompt_to_messages(multi)
+ assert len(msgs) == 3
+ assert msgs[0]["role"] == "system" and msgs[0]["content"] == "You are helpful."
+ assert msgs[1]["role"] == "user" and msgs[1]["content"] == "Hi?"
+ assert msgs[2]["role"] == "assistant" and msgs[2]["content"] == "Hello!"
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_pre_call_hook_basic(mock_client_class):
+ """Pre-call hook parses messages and injects params."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+temperature: 0.7
+---
+System: You are helpful.
+
+User: {{q}}"""
+ mock_client_class.return_value = mock_client
+
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"}, prompt_id="p1")
+
+ original = [{"role": "user", "content": "ignored"}]
+ msgs, params = mgr.pre_call_hook(
+ user_id="u",
+ messages=original,
+ litellm_params={},
+ prompt_id="p1",
+ prompt_variables={"q": "What is AI?"},
+ )
+
+ assert len(msgs) == 2
+ assert msgs[0]["role"] == "system"
+ assert msgs[1]["role"] == "user" and msgs[1]["content"] == "What is AI?"
+ assert params["model"] == "gpt-4" and params["temperature"] == 0.7
+
+
+def test_gitlab_prompt_manager_pre_call_hook_no_prompt_id():
+ """If no prompt_id provided, messages/params unchanged."""
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+ original = [{"role": "user", "content": "Hello"}]
+ msgs, params = mgr.pre_call_hook(user_id="u", messages=original, litellm_params={}, prompt_id=None)
+ assert msgs == original and params == {}
+
+
+def test_gitlab_prompt_manager_get_available_prompts():
+ """Return keys of stored templates."""
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+ mgr.prompt_manager.prompts.update({
+ "p1": GitLabPromptTemplate("p1", "c1", {}),
+ "p2": GitLabPromptTemplate("p2", "c2", {}),
+ })
+ assert set(mgr.get_available_prompts()) == {"p1", "p2"}
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_reload_prompts(mock_client_class):
+ """Ensure reload resets and re-inits manager."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = """---
+model: gpt-4
+---
+Hello {{x}}"""
+ mock_client_class.return_value = mock_client
+
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"}, prompt_id="t0")
+ assert "t0" in mgr.prompt_manager.prompts
+
+ # force reset
+ with patch.object(mgr, "_prompt_manager", None):
+ mgr.reload_prompts()
+ _ = mgr.prompt_manager
+ # No assertion beyond not raising and property access works
+
+
+# -----------------------
+# YAML fallback parsing
+# -----------------------
+
+def test_gitlab_prompt_manager_yaml_parsing_fallback_and_types():
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"})
+ yaml_content = """model: gpt-4
+temperature: 0.7
+max_tokens: 150
+enabled: true
+disabled: false
+count: 42
+rate: 0.5"""
+ parsed = mgr.prompt_manager._parse_yaml_basic(yaml_content)
+ assert parsed["model"] == "gpt-4"
+ assert parsed["temperature"] == 0.7
+ assert parsed["max_tokens"] == 150
+ assert parsed["enabled"] is True
+ assert parsed["disabled"] is False
+ assert parsed["count"] == 42
+ assert parsed["rate"] == 0.5
+
+
+# -----------------------
+# prompts_path handling + prompt_version (ref) precedence
+# -----------------------
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_prompts_path_resolution_and_version(mock_client_class):
+ """prompts_path + explicit prompt_version should produce correct repo path and ref."""
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{q}}"
+ mock_client_class.return_value = mock_client
+
+ cfg = {
+ "project": "g/s/r",
+ "access_token": "tok",
+ "prompts_path": "prompts/chat",
+ }
+ mgr = GitLabPromptManager(cfg)
+
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="folder/sub/my_prompt",
+ prompt_variables={"q": "ok"},
+ prompt_version="commit-sha-999",
+ )
+
+ mock_client.get_file_content.assert_any_call(
+ "prompts/chat/folder/sub/my_prompt.prompt", ref="commit-sha-999"
+ )
+
+
+@patch("litellm.integrations.gitlab.gitlab_prompt_manager.GitLabClient")
+def test_gitlab_prompt_manager_version_precedence(mock_client_class):
+ """
+ prompt_version > git_ref kwarg > manager _ref_override.
+ """
+ mock_client = MagicMock()
+ mock_client.get_file_content.return_value = "User: {{q}}"
+ mock_client_class.return_value = mock_client
+
+ mgr = GitLabPromptManager({"project": "g/s/r", "access_token": "tok"}, ref="manager-default")
+
+ # prompt_version wins over git_ref kwarg
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="pA",
+ prompt_variables={"q": "hello"},
+ prompt_version="sha-111",
+ git_ref="feature/branch-xyz",
+ )
+ mock_client.get_file_content.assert_any_call("pA.prompt", ref="sha-111")
+
+ # If no prompt_version, use git_ref kwarg
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="pB",
+ prompt_variables={"q": "hello"},
+ git_ref="hotfix/ref-2",
+ )
+ mock_client.get_file_content.assert_any_call("pB.prompt", ref="hotfix/ref-2")
+
+ # If neither provided, fall back to manager override
+ _msgs, _params = mgr.pre_call_hook(
+ user_id="u",
+ messages=[],
+ litellm_params={},
+ prompt_id="pC",
+ prompt_variables={"q": "hello"},
+ )
+ mock_client.get_file_content.assert_any_call("pC.prompt", ref="manager-default")