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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat: add GetBlogPosts utility with GitHub fetch and local fallback
yuneng-jiangbe1a543b55e0
diff --git a/litellm/litellm_core_utils/get_blog_posts.py b/litellm/litellm_core_utils/get_blog_posts.pynew file mode 100644index 00000000000..70fbe7129b5--- /dev/null+++ b/litellm/litellm_core_utils/get_blog_posts.py@@ -0,0 +1,134 @@+"""+Pulls the latest LiteLLM blog posts from GitHub.++Falls back to the bundled local backup on any failure.+GitHub JSON can be overridden via LITELLM_BLOG_POSTS_URL env var.++Disable remote fetching entirely:+ export LITELLM_LOCAL_BLOG_POSTS=True+"""++import json+import os+import time+from importlib.resources import files+from typing import Any, Dict, List, Optional++import httpx+from pydantic import BaseModel++from litellm import verbose_logger++BLOG_POSTS_GITHUB_URL: str = os.getenv(+ "LITELLM_BLOG_POSTS_URL",+ "https://raw.githubusercontent.com/BerriAI/litellm/main/blog_posts.json",+)++BLOG_POSTS_TTL_SECONDS: int = 3600 # 1 hour+++class BlogPost(BaseModel):+ title: str+ description: str+ date: str+ url: str+++class BlogPostsResponse(BaseModel):+ posts: List[BlogPost]+++class GetBlogPosts:+ """+ Fetches, validates, and caches LiteLLM blog posts.++ Mirrors the structure of GetModelCostMap:+ - Fetches from GitHub with a 5-second timeout+ - Validates the response has a non-empty ``posts`` list+ - Caches the result in-process for BLOG_POSTS_TTL_SECONDS (1 hour)+ - Falls back to the bundled local backup on any failure+ """++ _cached_posts: Optional[List[Dict[str, str]]] = None+ _last_fetch_time: float = 0.0++ @staticmethod+ def load_local_blog_posts() -> List[Dict[str, str]]:+ """Load the bundled local backup blog posts."""+ content = json.loads(+ files("litellm")+ .joinpath("blog_posts_backup.json")+ .read_text(encoding="utf-8")+ )+ return content.get("posts", [])++ @staticmethod+ def fetch_remote_blog_posts(url: str, timeout: int = 5) -> Any:+ """+ Fetch blog posts JSON from a remote URL.++ Returns the parsed response. Raises on network/parse errors.+ """+ response = httpx.get(url, timeout=timeout)+ response.raise_for_status()+ return response.json()++ @staticmethod+ def validate_blog_posts(data: Any) -> bool:+ """Return True if data is a dict with a non-empty ``posts`` list."""+ if not isinstance(data, dict):+ verbose_logger.warning(+ "LiteLLM: Blog posts response is not a dict (type=%s). "+ "Falling back to local backup.",+ type(data).__name__,+ )+ return False+ posts = data.get("posts")+ if not isinstance(posts, list) or len(posts) == 0:+ verbose_logger.warning(+ "LiteLLM: Blog posts response has no valid 'posts' list. "+ "Falling back to local backup.",+ )+ return False+ return True++ @classmethod+ def get_blog_posts(cls, url: str = BLOG_POSTS_GITHUB_URL) -> List[Dict[str, str]]:+ """+ Return the blog posts list.++ Uses the in-process cache if within BLOG_POSTS_TTL_SECONDS.+ Fetches from ``url`` otherwise, falling back to local backup on failure.+ """+ if os.getenv("LITELLM_LOCAL_BLOG_POSTS", "").lower() == "true":+ return cls.load_local_blog_posts()++ now = time.time()+ if (+ cls._cached_posts is not None+ and (now - cls._last_fetch_time) < BLOG_POSTS_TTL_SECONDS+ ):+ return cls._cached_posts++ try:+ data = cls.fetch_remote_blog_posts(url)+ except Exception as e:+ verbose_logger.warning(+ "LiteLLM: Failed to fetch blog posts from %s: %s. "+ "Falling back to local backup.",+ url,+ str(e),+ )+ return cls.load_local_blog_posts()++ if not cls.validate_blog_posts(data):+ return cls.load_local_blog_posts()++ cls._cached_posts = data["posts"]+ cls._last_fetch_time = now+ return cls._cached_posts+++def get_blog_posts(url: str = BLOG_POSTS_GITHUB_URL) -> List[Dict[str, str]]:+ """Public entry point — returns the blog posts list."""+ return GetBlogPosts.get_blog_posts(url=url)diff --git a/tests/test_litellm/test_get_blog_posts.py b/tests/test_litellm/test_get_blog_posts.pynew file mode 100644index 00000000000..29cecfaf5d5--- /dev/null+++ b/tests/test_litellm/test_get_blog_posts.py@@ -0,0 +1,157 @@+"""Tests for GetBlogPosts utility class."""+import json+import time+from unittest.mock import MagicMock, patch++import pytest++from litellm.litellm_core_utils.get_blog_posts import (+ BLOG_POSTS_GITHUB_URL,+ BlogPost,+ BlogPostsResponse,+ GetBlogPosts,+ get_blog_posts,+)++SAMPLE_RESPONSE = {+ "posts": [+ {+ "title": "Test Post",+ "description": "A test post.",+ "date": "2026-01-01",+ "url": "https://www.litellm.ai/blog/test",+ }+ ]+}+++def test_load_local_blog_posts_returns_list():+ posts = GetBlogPosts.load_local_blog_posts()+ assert isinstance(posts, list)+ assert len(posts) > 0+ first = posts[0]+ assert "title" in first+ assert "description" in first+ assert "date" in first+ assert "url" in first+++def test_validate_blog_posts_valid():+ assert GetBlogPosts.validate_blog_posts(SAMPLE_RESPONSE) is True+++def test_validate_blog_posts_missing_posts_key():+ assert GetBlogPosts.validate_blog_posts({"other": []}) is False+++def test_validate_blog_posts_empty_list():+ assert GetBlogPosts.validate_blog_posts({"posts": []}) is False+++def test_validate_blog_posts_not_dict():+ assert GetBlogPosts.validate_blog_posts("not a dict") is False+++def test_get_blog_posts_success(monkeypatch):+ """Fetches from remote on first call."""+ # Reset class cache state+ GetBlogPosts._cached_posts = None+ GetBlogPosts._last_fetch_time = 0.0++ mock_response = MagicMock()+ mock_response.json.return_value = SAMPLE_RESPONSE+ mock_response.raise_for_status = MagicMock()++ with patch("litellm.litellm_core_utils.get_blog_posts.httpx.get", return_value=mock_response):+ posts = get_blog_posts()++ assert len(posts) == 1+ assert posts[0]["title"] == "Test Post"+++def test_get_blog_posts_network_error_falls_back_to_local(monkeypatch):+ """Falls back to local backup on network error."""+ GetBlogPosts._cached_posts = None+ GetBlogPosts._last_fetch_time = 0.0++ with patch(+ "litellm.litellm_core_utils.get_blog_posts.httpx.get",+ side_effect=Exception("Network error"),+ ):+ posts = get_blog_posts()++ assert isinstance(posts, list)+ assert len(posts) > 0+++def test_get_blog_posts_invalid_json_falls_back_to_local(monkeypatch):+ """Falls back when remote returns non-dict."""+ GetBlogPosts._cached_posts = None+ GetBlogPosts._last_fetch_time = 0.0++ mock_response = MagicMock()+ mock_response.json.return_value = "not a dict"+ mock_response.raise_for_status = MagicMock()++ with patch("litellm.litellm_core_utils.get_blog_posts.httpx.get", return_value=mock_response):+ posts = get_blog_posts()++ assert isinstance(posts, list)+ assert len(posts) > 0+++def test_get_blog_posts_ttl_cache_not_refetched(monkeypatch):+ """Within TTL window, does not re-fetch."""+ GetBlogPosts._cached_posts = SAMPLE_RESPONSE["posts"]+ GetBlogPosts._last_fetch_time = time.time() # just now++ call_count = 0++ def mock_get(*args, **kwargs):+ nonlocal call_count+ call_count += 1+ m = MagicMock()+ m.json.return_value = SAMPLE_RESPONSE+ m.raise_for_status = MagicMock()+ return m++ with patch("litellm.litellm_core_utils.get_blog_posts.httpx.get", side_effect=mock_get):+ posts = get_blog_posts()++ assert call_count == 0 # cache hit, no fetch+ assert len(posts) == 1+++def test_get_blog_posts_ttl_expired_refetches(monkeypatch):+ """After TTL window, re-fetches from remote."""+ GetBlogPosts._cached_posts = SAMPLE_RESPONSE["posts"]+ GetBlogPosts._last_fetch_time = time.time() - 7200 # 2 hours ago++ mock_response = MagicMock()+ mock_response.json.return_value = SAMPLE_RESPONSE+ mock_response.raise_for_status = MagicMock()++ with patch(+ "litellm.litellm_core_utils.get_blog_posts.httpx.get", return_value=mock_response+ ) as mock_get:+ posts = get_blog_posts()++ mock_get.assert_called_once()+ assert len(posts) == 1+++def test_blog_post_pydantic_model():+ post = BlogPost(+ title="T",+ description="D",+ date="2026-01-01",+ url="https://example.com",+ )+ assert post.title == "T"+++def test_blog_posts_response_pydantic_model():+ resp = BlogPostsResponse(+ posts=[BlogPost(title="T", description="D", date="2026-01-01", url="https://x.com")]+ )+ assert len(resp.posts) == 1