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]

[Feat] New Provider - add langgraph (#17783)

Ishaan Jaff5ee32167c0f8
diff --git a/docs/my-website/docs/providers/langgraph.md b/docs/my-website/docs/providers/langgraph.md
new file mode 100644
index 00000000000..7361100ed85
--- /dev/null
+++ b/docs/my-website/docs/providers/langgraph.md
@@ -0,0 +1,240 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# LangGraph
+
+Call LangGraph agents through LiteLLM using the OpenAI chat completions format.
+
+| Property | Details |
+|----------|---------|
+| Description | LangGraph is a framework for building stateful, multi-actor applications with LLMs. LiteLLM supports calling LangGraph agents via their streaming and non-streaming endpoints. |
+| Provider Route on LiteLLM | `langgraph/{agent_id}` |
+| Provider Doc | [LangGraph Platform ↗](https://langchain-ai.github.io/langgraph/cloud/quick_start/) |
+
+**Prerequisites:** You need a running LangGraph server. See [Setting Up a Local LangGraph Server](#setting-up-a-local-langgraph-server) below.
+
+## Quick Start
+
+### Model Format
+
+```shell showLineNumbers title="Model Format"
+langgraph/{agent_id}
+```
+
+**Example:**
+- `langgraph/agent` - calls the default agent
+
+### LiteLLM Python SDK
+
+```python showLineNumbers title="Basic LangGraph Completion"
+import litellm
+
+response = litellm.completion(
+ model="langgraph/agent",
+ messages=[
+ {"role": "user", "content": "What is 25 * 4?"}
+ ],
+ api_base="http://localhost:2024",
+)
+
+print(response.choices[0].message.content)
+```
+
+```python showLineNumbers title="Streaming LangGraph Response"
+import litellm
+
+response = litellm.completion(
+ model="langgraph/agent",
+ messages=[
+ {"role": "user", "content": "What is the weather in Tokyo?"}
+ ],
+ api_base="http://localhost:2024",
+ stream=True,
+)
+
+for chunk in response:
+ if chunk.choices[0].delta.content:
+ print(chunk.choices[0].delta.content, end="")
+```
+
+### LiteLLM Proxy
+
+#### 1. Configure your model in config.yaml
+
+<Tabs>
+<TabItem value="config-yaml" label="config.yaml">
+
+```yaml showLineNumbers title="LiteLLM Proxy Configuration"
+model_list:
+ - model_name: langgraph-agent
+ litellm_params:
+ model: langgraph/agent
+ api_base: http://localhost:2024
+```
+
+</TabItem>
+</Tabs>
+
+#### 2. Start the LiteLLM Proxy
+
+```bash showLineNumbers title="Start LiteLLM Proxy"
+litellm --config config.yaml
+```
+
+#### 3. Make requests to your LangGraph agent
+
+<Tabs>
+<TabItem value="curl" label="Curl">
+
+```bash showLineNumbers title="Basic Request"
+curl http://localhost:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $LITELLM_API_KEY" \
+ -d '{
+ "model": "langgraph-agent",
+ "messages": [
+ {"role": "user", "content": "What is 25 * 4?"}
+ ]
+ }'
+```
+
+```bash showLineNumbers title="Streaming Request"
+curl http://localhost:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $LITELLM_API_KEY" \
+ -d '{
+ "model": "langgraph-agent",
+ "messages": [
+ {"role": "user", "content": "What is the weather in Tokyo?"}
+ ],
+ "stream": true
+ }'
+```
+
+</TabItem>
+
+<TabItem value="openai-sdk" label="OpenAI Python SDK">
+
+```python showLineNumbers title="Using OpenAI SDK with LiteLLM Proxy"
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://localhost:4000",
+ api_key="your-litellm-api-key"
+)
+
+response = client.chat.completions.create(
+ model="langgraph-agent",
+ messages=[
+ {"role": "user", "content": "What is 25 * 4?"}
+ ]
+)
+
+print(response.choices[0].message.content)
+```
+
+```python showLineNumbers title="Streaming with OpenAI SDK"
+from openai import OpenAI
+
+client = OpenAI(
+ base_url="http://localhost:4000",
+ api_key="your-litellm-api-key"
+)
+
+stream = client.chat.completions.create(
+ model="langgraph-agent",
+ messages=[
+ {"role": "user", "content": "What is the weather in Tokyo?"}
+ ],
+ stream=True
+)
+
+for chunk in stream:
+ if chunk.choices[0].delta.content is not None:
+ print(chunk.choices[0].delta.content, end="")
+```
+
+</TabItem>
+</Tabs>
+
+## Environment Variables
+
+| Variable | Description |
+|----------|-------------|
+| `LANGGRAPH_API_BASE` | Base URL of your LangGraph server (default: `http://localhost:2024`) |
+| `LANGGRAPH_API_KEY` | Optional API key for authentication |
+
+## Supported Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `model` | string | The agent ID in format `langgraph/{agent_id}` |
+| `messages` | array | Chat messages in OpenAI format |
+| `stream` | boolean | Enable streaming responses |
+| `api_base` | string | LangGraph server URL |
+| `api_key` | string | Optional API key |
+
+
+## Setting Up a Local LangGraph Server
+
+Before using LiteLLM with LangGraph, you need a running LangGraph server.
+
+### Prerequisites
+
+- Python 3.11+
+- An LLM API key (OpenAI or Google Gemini)
+
+### 1. Install the LangGraph CLI
+
+```bash
+pip install "langgraph-cli[inmem]"
+```
+
+### 2. Create a new LangGraph project
+
+```bash
+langgraph new my-agent --template new-langgraph-project-python
+cd my-agent
+```
+
+### 3. Install dependencies
+
+```bash
+pip install -e .
+```
+
+### 4. Set your API key
+
+```bash
+echo "OPENAI_API_KEY=your_key_here" > .env
+```
+
+### 5. Start the server
+
+```bash
+langgraph dev
+```
+
+The server will start at `http://localhost:2024`.
+
+### Verify the server is running
+
+```bash
+curl -s --request POST \
+ --url "http://localhost:2024/runs/wait" \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "assistant_id": "agent",
+ "input": {
+ "messages": [{"role": "human", "content": "Hello!"}]
+ }
+ }'
+```
+
+
+
+## Further Reading
+
+- [LangGraph Platform Documentation](https://langchain-ai.github.io/langgraph/cloud/quick_start/)
+- [LangGraph GitHub](https://github.com/langchain-ai/langgraph)
+
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index 471d96f4092..76441ffb8b9 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -706,6 +706,7 @@ const sidebars = {
"providers/infinity",
"providers/jina_ai",
"providers/lambda_ai",
+ "providers/langgraph",
"providers/lemonade",
"providers/llamafile",
"providers/lm_studio",
diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py
index 677dac3d313..36508e021e7 100644
--- a/litellm/litellm_core_utils/get_llm_provider_logic.py
+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py
@@ -872,6 +872,14 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915
full_model, api_base, api_key, "ragflow"
)
model = full_model
+ elif custom_llm_provider == "langgraph":
+ # LangGraph is a custom provider, just need to set api_base
+ api_base = (
+ api_base
+ or get_secret_str("LANGGRAPH_API_BASE")
+ or "http://localhost:2024"
+ )
+ dynamic_api_key = api_key or get_secret_str("LANGGRAPH_API_KEY")
if api_base is not None and not isinstance(api_base, str):
raise Exception("api base needs to be a string. api_base={}".format(api_base))
diff --git a/litellm/llms/langgraph/__init__.py b/litellm/llms/langgraph/__init__.py
new file mode 100644
index 00000000000..aa075dc96c1
--- /dev/null
+++ b/litellm/llms/langgraph/__init__.py
@@ -0,0 +1,4 @@
+from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+__all__ = ["LangGraphConfig"]
+
diff --git a/litellm/llms/langgraph/chat/__init__.py b/litellm/llms/langgraph/chat/__init__.py
new file mode 100644
index 00000000000..aa075dc96c1
--- /dev/null
+++ b/litellm/llms/langgraph/chat/__init__.py
@@ -0,0 +1,4 @@
+from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+__all__ = ["LangGraphConfig"]
+
diff --git a/litellm/llms/langgraph/chat/sse_iterator.py b/litellm/llms/langgraph/chat/sse_iterator.py
new file mode 100644
index 00000000000..bdb32cc0fe5
--- /dev/null
+++ b/litellm/llms/langgraph/chat/sse_iterator.py
@@ -0,0 +1,235 @@
+"""
+SSE Stream Iterator for LangGraph.
+
+Handles Server-Sent Events (SSE) streaming responses from LangGraph.
+"""
+
+import json
+import uuid
+from typing import TYPE_CHECKING, Optional
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.types.utils import Delta, ModelResponse, StreamingChoices
+
+if TYPE_CHECKING:
+ pass
+
+
+class LangGraphSSEStreamIterator:
+ """
+ Iterator for LangGraph SSE streaming responses.
+ Supports both sync and async iteration.
+
+ LangGraph stream format with stream_mode="messages-tuple":
+ Each SSE event is a tuple: (event_type, data)
+ Common event types: "messages", "metadata"
+ """
+
+ def __init__(self, response: httpx.Response, model: str):
+ self.response = response
+ self.model = model
+ self.finished = False
+ self.line_iterator = None
+ self.async_line_iterator = None
+
+ def __iter__(self):
+ """Initialize sync iteration."""
+ self.line_iterator = self.response.iter_lines()
+ return self
+
+ def __aiter__(self):
+ """Initialize async iteration."""
+ self.async_line_iterator = self.response.aiter_lines()
+ return self
+
+ def _parse_sse_line(self, line: str) -> Optional[ModelResponse]:
+ """
+ Parse a single SSE line and return a ModelResponse chunk if applicable.
+
+ LangGraph SSE format can vary:
+ - data: [...] (tuple format)
+ - event: ...\ndata: ...
+ """
+ line = line.strip()
+ if not line:
+ return None
+
+ # Handle SSE data lines
+ if line.startswith("data:"):
+ json_str = line[5:].strip()
+ if not json_str:
+ return None
+
+ try:
+ data = json.loads(json_str)
+ return self._process_data(data)
+ except json.JSONDecodeError:
+ verbose_logger.debug(f"Skipping non-JSON SSE line: {line[:100]}")
+ return None
+
+ return None
+
+ def _process_data(self, data) -> Optional[ModelResponse]:
+ """
+ Process parsed data from SSE stream.
+
+ LangGraph uses tuple format: [event_type, payload]
+ """
+ # Handle tuple format: ["messages", ...]
+ if isinstance(data, list) and len(data) >= 2:
+ event_type = data[0]
+ payload = data[1]
+
+ if event_type == "messages":
+ return self._process_messages_event(payload)
+ elif event_type == "metadata":
+ # Metadata event, might contain usage info
+ return self._process_metadata_event(payload)
+
+ # Handle dict format (alternative response format)
+ elif isinstance(data, dict):
+ if "content" in data:
+ return self._create_content_chunk(data.get("content", ""))
+ elif "messages" in data:
+ messages = data.get("messages", [])
+ if messages:
+ last_msg = messages[-1]
+ if isinstance(last_msg, dict) and last_msg.get("type") == "ai":
+ return self._create_content_chunk(last_msg.get("content", ""))
+
+ return None
+
+ def _process_messages_event(self, payload) -> Optional[ModelResponse]:
+ """
+ Process a messages event from the stream.
+
+ payload format: [[message_object, metadata], ...]
+ """
+ if isinstance(payload, list):
+ for item in payload:
+ if isinstance(item, list) and len(item) >= 1:
+ msg = item[0]
+ if isinstance(msg, dict):
+ msg_type = msg.get("type", "")
+ content = msg.get("content", "")
+
+ # Only return AI messages with content
+ if msg_type == "ai" and content:
+ return self._create_content_chunk(content)
+ elif msg_type == "AIMessageChunk" and content:
+ return self._create_content_chunk(content)
+ elif isinstance(item, dict):
+ msg_type = item.get("type", "")
+ content = item.get("content", "")
+ if msg_type in ("ai", "AIMessageChunk") and content:
+ return self._create_content_chunk(content)
+
+ return None
+
+ def _process_metadata_event(self, payload) -> Optional[ModelResponse]:
+ """
+ Process a metadata event, which may signal the end of the stream.
+ """
+ if isinstance(payload, dict):
+ # Check if this is a final event
+ if "run_id" in payload:
+ self.finished = True
+ return self._create_final_chunk()
+ return None
+
+ def _create_content_chunk(self, text: str) -> ModelResponse:
+ """Create a ModelResponse chunk with content."""
+ chunk = ModelResponse(
+ id=f"chatcmpl-{uuid.uuid4()}",
+ created=0,
+ model=self.model,
+ object="chat.completion.chunk",
+ )
+
+ chunk.choices = [
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(content=text, role="assistant"),
+ )
+ ]
+
+ return chunk
+
+ def _create_final_chunk(self) -> ModelResponse:
+ """Create a final ModelResponse chunk with finish_reason."""
+ chunk = ModelResponse(
+ id=f"chatcmpl-{uuid.uuid4()}",
+ created=0,
+ model=self.model,
+ object="chat.completion.chunk",
+ )
+
+ chunk.choices = [
+ StreamingChoices(
+ finish_reason="stop",
+ index=0,
+ delta=Delta(),
+ )
+ ]
+
+ return chunk
+
+ def __next__(self) -> ModelResponse:
+ """Sync iteration - parse SSE events and yield ModelResponse chunks."""
+ try:
+ if self.line_iterator is None:
+ raise StopIteration
+
+ for line in self.line_iterator:
+ result = self._parse_sse_line(line)
+ if result is not None:
+ return result
+
+ # Stream ended naturally - send final chunk if not already finished
+ if not self.finished:
+ self.finished = True
+ return self._create_final_chunk()
+
+ raise StopIteration
+
+ except StopIteration:
+ raise
+ except httpx.StreamConsumed:
+ raise StopIteration
+ except httpx.StreamClosed:
+ raise StopIteration
+ except Exception as e:
+ verbose_logger.error(f"Error in LangGraph SSE stream: {str(e)}")
+ raise StopIteration
+
+ async def __anext__(self) -> ModelResponse:
+ """Async iteration - parse SSE events and yield ModelResponse chunks."""
+ try:
+ if self.async_line_iterator is None:
+ raise StopAsyncIteration
+
+ async for line in self.async_line_iterator:
+ result = self._parse_sse_line(line)
+ if result is not None:
+ return result
+
+ # Stream ended naturally - send final chunk if not already finished
+ if not self.finished:
+ self.finished = True
+ return self._create_final_chunk()
+
+ raise StopAsyncIteration
+
+ except StopAsyncIteration:
+ raise
+ except httpx.StreamConsumed:
+ raise StopAsyncIteration
+ except httpx.StreamClosed:
+ raise StopAsyncIteration
+ except Exception as e:
+ verbose_logger.error(f"Error in LangGraph SSE stream: {str(e)}")
+ raise StopAsyncIteration
+
diff --git a/litellm/llms/langgraph/chat/transformation.py b/litellm/llms/langgraph/chat/transformation.py
new file mode 100644
index 00000000000..d773b26bca6
--- /dev/null
+++ b/litellm/llms/langgraph/chat/transformation.py
@@ -0,0 +1,509 @@
+"""
+Transformation for LangGraph API.
+
+LangGraph provides streaming (/runs/stream) and non-streaming (/runs/wait) endpoints
+for running agents.
+
+Streaming endpoint: POST /runs/stream
+Non-streaming endpoint: POST /runs/wait
+"""
+
+import json
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.litellm_core_utils.prompt_templates.common_utils import (
+ convert_content_list_to_str,
+)
+from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException
+from litellm.llms.langgraph.chat.sse_iterator import LangGraphSSEStreamIterator
+from litellm.types.llms.openai import AllMessageValues
+from litellm.types.utils import Choices, Message, ModelResponse, Usage
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
+ from litellm.utils import CustomStreamWrapper
+
+ LiteLLMLoggingObj = _LiteLLMLoggingObj
+else:
+ LiteLLMLoggingObj = Any
+ HTTPHandler = Any
+ AsyncHTTPHandler = Any
+ CustomStreamWrapper = Any
+
+
+class LangGraphError(BaseLLMException):
+ """Exception class for LangGraph API errors."""
+
+ pass
+
+
+class LangGraphConfig(BaseConfig):
+ """
+ Configuration for LangGraph API.
+
+ LangGraph is a framework for building stateful, multi-actor applications with LLMs.
+ It provides a streaming and non-streaming API for running agents.
+ """
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def _get_openai_compatible_provider_info(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """
+ Get LangGraph API base and key from params or environment.
+
+ Returns:
+ Tuple of (api_base, api_key)
+ """
+ from litellm.secret_managers.main import get_secret_str
+
+ api_base = (
+ api_base
+ or get_secret_str("LANGGRAPH_API_BASE")
+ or "http://localhost:2024"
+ )
+
+ api_key = api_key or get_secret_str("LANGGRAPH_API_KEY")
+
+ return api_base, api_key
+
+ def get_supported_openai_params(self, model: str) -> List[str]:
+ """
+ LangGraph supports minimal OpenAI params since it's an agent runtime.
+ """
+ return ["stream"]
+
+ def map_openai_params(
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool,
+ ) -> dict:
+ """
+ Map OpenAI params to LangGraph params.
+ """
+ return optional_params
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: dict,
+ litellm_params: dict,
+ stream: Optional[bool] = None,
+ ) -> str:
+ """
+ Get the complete URL for the LangGraph request.
+
+ Streaming: /runs/stream
+ Non-streaming: /runs/wait
+ """
+ if api_base is None:
+ raise ValueError(
+ "api_base is required for LangGraph. Set it via LANGGRAPH_API_BASE env var or api_base parameter."
+ )
+
+ # Remove trailing slash if present
+ api_base = api_base.rstrip("/")
+
+ # Choose endpoint based on streaming mode
+ if stream:
+ return f"{api_base}/runs/stream"
+ else:
+ return f"{api_base}/runs/wait"
+
+ def _get_assistant_id(self, model: str, optional_params: dict) -> str:
+ """
+ Get the assistant ID from model or optional_params.
+
+ model format: "langgraph/assistant_id" or just "assistant_id"
+ """
+ assistant_id = optional_params.get("assistant_id")
+ if assistant_id:
+ return assistant_id
+
+ # Extract from model name
+ if "/" in model:
+ parts = model.split("/", 1)
+ if len(parts) == 2:
+ return parts[1]
+ return model
+
+ def _convert_messages_to_langgraph_format(
+ self, messages: List[AllMessageValues]
+ ) -> List[Dict[str, str]]:
+ """
+ Convert OpenAI-format messages to LangGraph format.
+
+ OpenAI format: {"role": "user", "content": "..."}
+ LangGraph format: {"role": "human", "content": "..."}
+ """
+ langgraph_messages = []
+ for msg in messages:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+
+ # Convert OpenAI roles to LangGraph roles
+ if role == "user":
+ langgraph_role = "human"
+ elif role == "assistant":
+ langgraph_role = "assistant"
+ elif role == "system":
+ langgraph_role = "system"
+ else:
+ langgraph_role = "human"
+
+ # Handle content that might be a list
+ if isinstance(content, list):
+ content = convert_content_list_to_str(msg)
+
+ langgraph_messages.append({"role": langgraph_role, "content": content})
+
+ return langgraph_messages
+
+ def transform_request(
+ self,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ headers: dict,
+ ) -> dict:
+ """
+ Transform the request to LangGraph format.
+
+ LangGraph request format:
+ {
+ "assistant_id": "agent",
+ "input": {
+ "messages": [{"role": "human", "content": "..."}]
+ },
+ "stream_mode": "messages-tuple" # for streaming
+ }
+ """
+ assistant_id = self._get_assistant_id(model, optional_params)
+ langgraph_messages = self._convert_messages_to_langgraph_format(messages)
+
+ payload: Dict[str, Any] = {
+ "assistant_id": assistant_id,
+ "input": {"messages": langgraph_messages},
+ }
+
+ # Add stream_mode for streaming requests
+ stream = litellm_params.get("stream", False)
+ if stream:
+ stream_mode = optional_params.get("stream_mode", "messages-tuple")
+ payload["stream_mode"] = stream_mode
+
+ # Add optional config if provided
+ if "config" in optional_params:
+ payload["config"] = optional_params["config"]
+
+ # Add optional metadata if provided
+ if "metadata" in optional_params:
+ payload["metadata"] = optional_params["metadata"]
+
+ # Add thread_id if provided (for stateful conversations)
+ if "thread_id" in optional_params:
+ payload["thread_id"] = optional_params["thread_id"]
+
+ verbose_logger.debug(f"LangGraph request payload: {payload}")
+ return payload
+
+ def _extract_content_from_response(self, response_json: dict) -> str:
+ """
+ Extract content from LangGraph non-streaming response.
+
+ Response format varies, but commonly:
+ {
+ "messages": [...], # or could be in different structure
+ "values": {...}
+ }
+ """
+ # Try to get the last AI message from the response
+ messages = response_json.get("messages", [])
+ if isinstance(messages, list) and messages:
+ # Find the last AI/assistant message
+ for msg in reversed(messages):
+ if isinstance(msg, dict):
+ msg_type = msg.get("type", "")
+ role = msg.get("role", "")
+ if msg_type == "ai" or role == "assistant":
+ return msg.get("content", "")
+
+ # Check values for output
+ values = response_json.get("values", {})
+ if isinstance(values, dict):
+ output_messages = values.get("messages", [])
+ if isinstance(output_messages, list) and output_messages:
+ for msg in reversed(output_messages):
+ if isinstance(msg, dict):
+ msg_type = msg.get("type", "")
+ if msg_type == "ai":
+ return msg.get("content", "")
+
+ # Fallback: try to serialize the whole response
+ verbose_logger.warning(
+ "Could not extract content from LangGraph response, returning raw"
+ )
+ return json.dumps(response_json)
+
+ def get_streaming_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ ) -> LangGraphSSEStreamIterator:
+ """
+ Return a streaming iterator for SSE responses.
+ """
+ return LangGraphSSEStreamIterator(response=raw_response, model=model)
+
+ def get_sync_custom_stream_wrapper(
+ self,
+ model: str,
+ custom_llm_provider: str,
+ logging_obj: LiteLLMLoggingObj,
+ api_base: str,
+ headers: dict,
+ data: dict,
+ messages: list,
+ client: Optional[Union[HTTPHandler, "AsyncHTTPHandler"]] = None,
+ json_mode: Optional[bool] = None,
+ signed_json_body: Optional[bytes] = None,
+ ) -> CustomStreamWrapper:
+ """
+ Get a CustomStreamWrapper for synchronous streaming.
+ """
+ from litellm.llms.custom_httpx.http_handler import (
+ HTTPHandler,
+ _get_httpx_client,
+ )
+ from litellm.utils import CustomStreamWrapper
+
+ if client is None or not isinstance(client, HTTPHandler):
+ client = _get_httpx_client(params={})
+
+ verbose_logger.debug(f"Making sync streaming request to: {api_base}")
+
+ # Make streaming request
+ response = client.post(
+ api_base,
+ headers=headers,
+ data=json.dumps(data),
+ stream=True,
+ logging_obj=logging_obj,
+ )
+
+ if response.status_code != 200:
+ raise LangGraphError(
+ status_code=response.status_code, message=str(response.read())
+ )
+
+ # Create iterator for SSE stream
+ completion_stream = self.get_streaming_response(
+ model=model, raw_response=response
+ )
+
+ streaming_response = CustomStreamWrapper(
+ completion_stream=completion_stream,
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ logging_obj=logging_obj,
+ )
+
+ # LOGGING
+ logging_obj.post_call(
+ input=messages,
+ api_key="",
+ original_response="first stream response received",
+ additional_args={"complete_input_dict": data},
+ )
+
+ return streaming_response
+
+ async def get_async_custom_stream_wrapper(
+ self,
+ model: str,
+ custom_llm_provider: str,
+ logging_obj: LiteLLMLoggingObj,
+ api_base: str,
+ headers: dict,
+ data: dict,
+ messages: list,
+ client: Optional["AsyncHTTPHandler"] = None,
+ json_mode: Optional[bool] = None,
+ signed_json_body: Optional[bytes] = None,
+ ) -> CustomStreamWrapper:
+ """
+ Get a CustomStreamWrapper for asynchronous streaming.
+ """
+ from litellm.llms.custom_httpx.http_handler import (
+ AsyncHTTPHandler,
+ get_async_httpx_client,
+ )
+ from litellm.utils import CustomStreamWrapper
+
+ if client is None or not isinstance(client, AsyncHTTPHandler):
+ client = get_async_httpx_client(
+ llm_provider=cast(Any, "langgraph"), params={}
+ )
+
+ verbose_logger.debug(f"Making async streaming request to: {api_base}")
+
+ # Make async streaming request
+ response = await client.post(
+ api_base,
+ headers=headers,
+ data=json.dumps(data),
+ stream=True,
+ logging_obj=logging_obj,
+ )
+
+ if response.status_code != 200:
+ raise LangGraphError(
+ status_code=response.status_code, message=str(await response.aread())
+ )
+
+ # Create iterator for SSE stream
+ completion_stream = self.get_streaming_response(
+ model=model, raw_response=response
+ )
+
+ streaming_response = CustomStreamWrapper(
+ completion_stream=completion_stream,
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ logging_obj=logging_obj,
+ )
+
+ # LOGGING
+ logging_obj.post_call(
+ input=messages,
+ api_key="",
+ original_response="first stream response received",
+ additional_args={"complete_input_dict": data},
+ )
+
+ return streaming_response
+
+ @property
+ def has_custom_stream_wrapper(self) -> bool:
+ """Indicates that this config has custom streaming support."""
+ return True
+
+ @property
+ def supports_stream_param_in_request_body(self) -> bool:
+ """
+ LangGraph does not use a stream param in request body.
+ Streaming is determined by the endpoint URL.
+ """
+ return False
+
+ def transform_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: ModelResponse,
+ logging_obj: LiteLLMLoggingObj,
+ request_data: dict,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ encoding: Any,
+ api_key: Optional[str] = None,
+ json_mode: Optional[bool] = None,
+ ) -> ModelResponse:
+ """
+ Transform the LangGraph response to LiteLLM ModelResponse format.
+ """
+ try:
+ response_json = raw_response.json()
+ verbose_logger.debug(f"LangGraph response: {response_json}")
+
+ content = self._extract_content_from_response(response_json)
+
+ # Create the message
+ message = Message(content=content, role="assistant")
+
+ # Create choices
+ choice = Choices(finish_reason="stop", index=0, message=message)
+
+ # Update model response
+ model_response.choices = [choice]
+ model_response.model = model
+
+ # LangGraph doesn't provide token usage, so we estimate it
+ try:
+ from litellm.utils import token_counter
+
+ prompt_tokens = token_counter(model="gpt-3.5-turbo", messages=messages)
+ completion_tokens = token_counter(
+ model="gpt-3.5-turbo", text=content, count_response_tokens=True
+ )
+ total_tokens = prompt_tokens + completion_tokens
+
+ usage = Usage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=total_tokens,
+ )
+ setattr(model_response, "usage", usage)
+ except Exception as e:
+ verbose_logger.warning(f"Failed to calculate token usage: {str(e)}")
+
+ return model_response
+
+ except Exception as e:
+ verbose_logger.error(f"Error processing LangGraph response: {str(e)}")
+ raise LangGraphError(
+ message=f"Error processing response: {str(e)}",
+ status_code=raw_response.status_code,
+ )
+
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ """
+ Validate and set up environment for LangGraph requests.
+ """
+ headers["Content-Type"] = "application/json"
+
+ # Add API key if provided
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ return headers
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ) -> BaseLLMException:
+ return LangGraphError(status_code=status_code, message=error_message)
+
+ def should_fake_stream(
+ self,
+ model: Optional[str],
+ stream: Optional[bool],
+ custom_llm_provider: Optional[str] = None,
+ ) -> bool:
+ """
+ LangGraph has native streaming support, so we don't need to fake stream.
+ """
+ return False
+
diff --git a/litellm/llms/sap/chat/handler.py b/litellm/llms/sap/chat/handler.py
index beabe255130..c24cf3d279f 100755
--- a/litellm/llms/sap/chat/handler.py
+++ b/litellm/llms/sap/chat/handler.py
@@ -2,21 +2,22 @@ from __future__ import annotations
import json
import time
-import httpx
+from typing import AsyncIterator, Iterator, Optional
-from typing import Iterator, Optional, AsyncIterator
+import httpx
-from litellm.llms.base_llm.chat.transformation import BaseConfig
+from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException
from litellm.types.llms.openai import OpenAIChatCompletionChunk
+
from ...custom_httpx.llm_http_handler import BaseLLMHTTPHandler
# -------------------------------
# Errors
# -------------------------------
-class GenAIHubOrchestrationError(Exception):
+class GenAIHubOrchestrationError(BaseLLMException):
def __init__(self, status_code: int, message: str):
- super().__init__(message)
+ super().__init__(status_code=status_code, message=message)
self.status_code = status_code
self.message = message
diff --git a/litellm/llms/sap/embed/transformation.py b/litellm/llms/sap/embed/transformation.py
index 93f32c00abd..0801a265f70 100644
--- a/litellm/llms/sap/embed/transformation.py
+++ b/litellm/llms/sap/embed/transformation.py
@@ -2,11 +2,11 @@
Translates from OpenAI's `/v1/embeddings` to IBM's `/text/embeddings` route.
"""
-from typing import Optional, List, Dict, Literal
-from pydantic import BaseModel, Field
from functools import cached_property
+from typing import Dict, List, Literal, Optional, Union
import httpx
+from pydantic import BaseModel, Field
from litellm.llms.base_llm.embedding.transformation import (
BaseEmbeddingConfig,
@@ -55,7 +55,7 @@ class EmbeddingsModules(BaseModel):
class EmbeddingInput(BaseModel):
- text: str | List[str]
+ text: Union[str, List[str]]
type: Literal["text", "document", "query"] = "text"
diff --git a/litellm/main.py b/litellm/main.py
index 20b2cbb7db8..831e0c88b18 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -176,7 +176,6 @@ from .llms.databricks.embed.handler import DatabricksEmbeddingHandler
from .llms.deprecated_providers import aleph_alpha, palm
from .llms.gemini.common_utils import get_api_key_from_env
from .llms.groq.chat.handler import GroqChatCompletion
-from .llms.sap.chat.handler import GenAIHubOrchestration
from .llms.heroku.chat.transformation import HerokuChatConfig
from .llms.huggingface.embedding.handler import HuggingFaceEmbedding
from .llms.lemonade.chat.transformation import LemonadeChatConfig
@@ -196,6 +195,7 @@ from .llms.predibase.chat.handler import PredibaseChatCompletion
from .llms.replicate.chat.handler import completion as replicate_chat_completion
from .llms.sagemaker.chat.handler import SagemakerChatHandler
from .llms.sagemaker.completion.handler import SagemakerLLM
+from .llms.sap.chat.handler import GenAIHubOrchestration
from .llms.vertex_ai import vertex_ai_non_gemini
from .llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexLLM
from .llms.vertex_ai.gemini_embeddings.batch_embed_content_handler import (
@@ -3963,6 +3963,39 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
)
+ elif custom_llm_provider == "langgraph":
+ # LangGraph - Agent Runtime Provider
+ from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+ (
+ api_base,
+ api_key,
+ ) = LangGraphConfig()._get_openai_compatible_provider_info(
+ api_base=api_base or litellm.api_base,
+ api_key=api_key or litellm.api_key,
+ )
+
+ headers = headers or litellm.headers
+
+ response = base_llm_http_handler.completion(
+ model=model,
+ stream=stream,
+ messages=messages,
+ acompletion=acompletion,
+ api_base=api_base,
+ model_response=model_response,
+ optional_params=optional_params,
+ litellm_params=litellm_params,
+ shared_session=shared_session,
+ custom_llm_provider=custom_llm_provider,
+ timeout=timeout,
+ headers=headers,
+ encoding=encoding,
+ api_key=api_key,
+ logging_obj=logging,
+ client=client,
+ )
+
else:
raise LiteLLMUnknownProvider(
model=model, custom_llm_provider=custom_llm_provider
diff --git a/litellm/types/llms/langgraph.py b/litellm/types/llms/langgraph.py
new file mode 100644
index 00000000000..cdf5d67b514
--- /dev/null
+++ b/litellm/types/llms/langgraph.py
@@ -0,0 +1,68 @@
+"""
+Type definitions for LangGraph API.
+
+LangGraph provides a streaming and non-streaming API for running agents.
+"""
+
+from typing import Any, Dict, List, Optional
+
+from typing_extensions import Literal, TypedDict
+
+
+# Request Types
+class LangGraphMessage(TypedDict, total=False):
+ """Message format for LangGraph input."""
+
+ role: Literal["human", "assistant", "system"]
+ content: str
+
+
+class LangGraphInput(TypedDict, total=False):
+ """Input structure for LangGraph request."""
+
+ messages: List[LangGraphMessage]
+
+
+class LangGraphRequest(TypedDict, total=False):
+ """Request structure for LangGraph API."""
+
+ assistant_id: str
+ input: LangGraphInput
+ stream_mode: Optional[str]
+ config: Optional[Dict[str, Any]]
+ metadata: Optional[Dict[str, Any]]
+
+
+# Response Types - Streaming
+class LangGraphStreamEvent(TypedDict, total=False):
+ """Single event in a LangGraph stream response."""
+
+ event: str
+ data: Any
+
+
+# Response Types - Non-streaming
+class LangGraphResponseMessage(TypedDict, total=False):
+ """Message in LangGraph response."""
+
+ type: str
+ content: str
+ id: Optional[str]
+ name: Optional[str]
+
+
+class LangGraphResponse(TypedDict, total=False):
+ """Non-streaming response structure from LangGraph."""
+
+ messages: List[LangGraphResponseMessage]
+ values: Dict[str, Any]
+
+
+# Parsed response for internal use
+class LangGraphParsedResponse(TypedDict):
+ """Parsed response from LangGraph."""
+
+ content: str
+ role: str
+ usage: Optional[Dict[str, int]]
+
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index d788f2840e4..9d4dd7e6601 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3008,6 +3008,7 @@ class LlmProviders(str, Enum):
LEMONADE = "lemonade"
AMAZON_NOVA = "amazon_nova"
A2A_AGENT = "a2a_agent"
+ LANGGRAPH = "langgraph"
# Create a set of all provider values for quick lookup
diff --git a/litellm/utils.py b/litellm/utils.py
index b92af35e70d..cf9e64721fa 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -97,6 +97,10 @@ from litellm.litellm_core_utils.core_helpers import (
)
from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
from litellm.litellm_core_utils.default_encoding import encoding
+from litellm.litellm_core_utils.dot_notation_indexing import (
+ delete_nested_value,
+ is_nested_path,
+)
from litellm.litellm_core_utils.exception_mapping_utils import (
_get_response_headers,
exception_type,
@@ -138,10 +142,6 @@ from litellm.litellm_core_utils.redact_messages import (
LiteLLMLoggingObject,
redact_message_input_output_from_logging,
)
-from litellm.litellm_core_utils.dot_notation_indexing import (
- delete_nested_value,
- is_nested_path,
-)
from litellm.litellm_core_utils.rules import Rules
from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper
from litellm.litellm_core_utils.token_counter import get_modified_max_tokens
@@ -7288,6 +7288,10 @@ class ProviderConfigManager:
return litellm.OVHCloudChatConfig()
elif litellm.LlmProviders.AMAZON_NOVA == provider:
return litellm.AmazonNovaChatConfig()
+ elif litellm.LlmProviders.LANGGRAPH == provider:
+ from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+ return LangGraphConfig()
return None
@staticmethod
diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json
index 3224ba2a06d..72eb9c9ada3 100644
--- a/provider_endpoints_support.json
+++ b/provider_endpoints_support.json
@@ -1910,6 +1910,23 @@
"rerank": false,
"a2a": true
}
+ },
+ "langgraph": {
+ "display_name": "LangGraph (`langgraph`)",
+ "url": "https://docs.litellm.ai/docs/providers/langgraph",
+ "endpoints": {
+ "chat_completions": true,
+ "messages": true,
+ "responses": true,
+ "embeddings": false,
+ "image_generations": false,
+ "audio_transcriptions": false,
+ "audio_speech": false,
+ "moderations": false,
+ "batches": false,
+ "rerank": false,
+ "a2a": true
+ }
}
}
}
\ No newline at end of file
diff --git a/tests/llm_translation/test_langgraph.py b/tests/llm_translation/test_langgraph.py
new file mode 100644
index 00000000000..2baae7b4326
--- /dev/null
+++ b/tests/llm_translation/test_langgraph.py
@@ -0,0 +1,173 @@
+"""
+Tests for LangGraph provider integration.
+
+These tests require a LangGraph server running locally on port 2024.
+To start a LangGraph server, follow the LangGraph documentation.
+
+Example test server curl commands:
+Streaming:
+ curl -s --request POST \
+ --url "http://localhost:2024/runs/stream" \
+ --header 'Content-Type: application/json' \
+ --data '{"assistant_id": "agent", "input": {"messages": [{"role": "human", "content": "What is 25 * 4?"}]}, "stream_mode": "messages-tuple"}'
+
+Non-streaming:
+ curl -s --request POST \
+ --url "http://localhost:2024/runs/wait" \
+ --header 'Content-Type: application/json' \
+ --data '{"assistant_id": "agent", "input": {"messages": [{"role": "human", "content": "What is 25 * 4?"}]}}'
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+import pytest
+
+import litellm
+
+
+async def test_langgraph_acompletion_non_streaming():
+ """
+ Test non-streaming acompletion call to LangGraph server.
+ Uses the /runs/wait endpoint for synchronous response.
+ """
+ api_base = os.environ.get("LANGGRAPH_API_BASE", "http://localhost:2024")
+
+ try:
+ response = await litellm.acompletion(
+ model="langgraph/agent",
+ messages=[{"role": "user", "content": "What is 25 * 4?"}],
+ api_base=api_base,
+ stream=False,
+ )
+
+ assert response is not None
+ assert response.choices is not None
+ assert len(response.choices) > 0
+ assert response.choices[0].message is not None
+ assert response.choices[0].message.content is not None
+ assert len(response.choices[0].message.content) > 0
+
+ except Exception as e:
+ pytest.skip(f"LangGraph server not available: {e}")
+
+
+async def test_langgraph_acompletion_streaming():
+ """
+ Test streaming acompletion call to LangGraph server.
+ Uses the /runs/stream endpoint with stream_mode="messages-tuple".
+ """
+ api_base = os.environ.get("LANGGRAPH_API_BASE", "http://localhost:2024")
+
+ try:
+ response = await litellm.acompletion(
+ model="langgraph/agent",
+ messages=[{"role": "user", "content": "What is the weather in Tokyo?"}],
+ api_base=api_base,
+ stream=True,
+ )
+
+ full_content = ""
+ chunk_count = 0
+
+ async for chunk in response:
+ chunk_count += 1
+ if (
+ chunk.choices
+ and chunk.choices[0].delta
+ and chunk.choices[0].delta.content
+ ):
+ full_content += chunk.choices[0].delta.content
+
+ assert chunk_count > 0, "Should receive at least one chunk"
+
+ except Exception as e:
+ pytest.skip(f"LangGraph server not available: {e}")
+
+
+def test_langgraph_config_get_complete_url():
+ """
+ Test that LangGraphConfig correctly generates URLs for streaming and non-streaming.
+ """
+ from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+ config = LangGraphConfig()
+
+ non_streaming_url = config.get_complete_url(
+ api_base="http://localhost:2024",
+ api_key=None,
+ model="agent",
+ optional_params={},
+ litellm_params={},
+ stream=False,
+ )
+ assert non_streaming_url == "http://localhost:2024/runs/wait"
+
+ streaming_url = config.get_complete_url(
+ api_base="http://localhost:2024",
+ api_key=None,
+ model="agent",
+ optional_params={},
+ litellm_params={},
+ stream=True,
+ )
+ assert streaming_url == "http://localhost:2024/runs/stream"
+
+
+def test_langgraph_config_transform_request():
+ """
+ Test that LangGraphConfig correctly transforms requests.
+ """
+ from litellm.llms.langgraph.chat.transformation import LangGraphConfig
+
+ config = LangGraphConfig()
+
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "What is 2 + 2?"},
+ ]
+
+ request = config.transform_request(
+ model="langgraph/agent",
+ messages=messages,
+ optional_params={},
+ litellm_params={"stream": False},
+ headers={},
+ )
+
+ assert request["assistant_id"] == "agent"
+ assert "input" in request
+ assert "messages" in request["input"]
+ assert len(request["input"]["messages"]) == 2
+ assert request["input"]["messages"][0]["role"] == "system"
+ assert request["input"]["messages"][1]["role"] == "human"
+
+ streaming_request = config.transform_request(
+ model="langgraph/agent",
+ messages=messages,
+ optional_params={},
+ litellm_params={"stream": True},
+ headers={},
+ )
+
+ assert streaming_request["stream_mode"] == "messages-tuple"
+
+
+def test_langgraph_provider_detection():
+ """
+ Test that the langgraph provider is correctly detected from model name.
+ """
+ from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
+
+ model, provider, api_key, api_base = get_llm_provider(
+ model="langgraph/agent",
+ api_base="http://localhost:2024",
+ )
+
+ assert provider == "langgraph"
+ assert model == "agent"
+