Skip to content

Commit

Permalink
Add pydantic v2 support (#181)
Browse files Browse the repository at this point in the history
This PR adds pydantic v2 support to LangServe.

With pydantic v2 all endpoints will work, but openapi docs will not be
generated for these endpoints. (At least at the moment.)

---------

Co-authored-by: jakerachleff <[email protected]>
  • Loading branch information
eyurtsev and jakerachleff authored Nov 8, 2023
1 parent 2f8d046 commit 0dd55c8
Show file tree
Hide file tree
Showing 7 changed files with 272 additions and 160 deletions.
8 changes: 7 additions & 1 deletion .github/workflows/langserve_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ jobs:
working-directory: .
secrets: inherit

pydantic-compatibility:
uses:
./.github/workflows/_pydantic_compatibility.yml
with:
working-directory: .
secrets: inherit
test:
runs-on: ubuntu-latest
defaults:
Expand All @@ -51,7 +57,7 @@ jobs:
- "3.9"
- "3.10"
- "3.11"
name: Python ${{ matrix.python-version }} extended tests
name: Python ${{ matrix.python-version }} tests
steps:
- uses: actions/checkout@v3

Expand Down
10 changes: 10 additions & 0 deletions langserve/pydantic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import pydantic


def _get_pydantic_version() -> int:
"""Get the pydantic major version."""
return int(pydantic.__version__.split(".")[0])


# Code is written to support both version 1 and 2
PYDANTIC_MAJOR_VERSION = _get_pydantic_version()
15 changes: 9 additions & 6 deletions langserve/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
from typing import Dict, List, Optional, Union
from uuid import UUID

try:
from pydantic.v1 import BaseModel
except ImportError:
from pydantic import BaseModel
from langserve.pydantic import PYDANTIC_MAJOR_VERSION

if PYDANTIC_MAJOR_VERSION == 2:
from pydantic.v1 import BaseModel as BaseModelV1
else:
from pydantic import BaseModel as BaseModelV1
from pydantic import BaseModel

class CustomUserType(BaseModel):

class CustomUserType(BaseModelV1):
"""Inherit from this class to create a custom user type.
Use a custom user type if you want the data to de-serialize
Expand All @@ -27,7 +30,7 @@ class CustomUserType(BaseModel):
"""


class SharedResponseMetadata(BaseModel):
class SharedResponseMetadata(BaseModelV1):
"""
Any response metadata should inherit from this class. Response metadata
represents non-output data that may be useful to some clients, but
Expand Down
Loading

0 comments on commit 0dd55c8

Please sign in to comment.