Skip to content

Commit

Permalink
Merge pull request #1889 from opentensor/feature/opendansor/PydanticV…
Browse files Browse the repository at this point in the history
…2Update

Update: Pydantic V2
  • Loading branch information
opendansor committed May 21, 2024
2 parents 4ecdfaf + 010cd0e commit bfef073
Show file tree
Hide file tree
Showing 10 changed files with 183 additions and 154 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ Synapse: Responsible for defining the protocol definition between axon servers a
```python
class Topk( bittensor.Synapse ):
topk: int = 2 # Number of "top" elements to select
input: bittensor.Tensor = pydantic.Field(..., allow_mutation=False) # Ensure that input cannot be set on the server side.
input: bittensor.Tensor = pydantic.Field(..., frozen=True) # Ensure that input cannot be set on the server side.
v: bittensor.Tensor = None
i: bittensor.Tensor = None
Expand Down
32 changes: 16 additions & 16 deletions bittensor/axon.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,29 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import os
import uuid
import argparse
import asyncio
import contextlib
import copy
import inspect
import json
import os
import threading
import time
import asyncio
import inspect
import uvicorn
import argparse
import traceback
import threading
import bittensor
import contextlib

import uuid
from inspect import signature, Signature, Parameter
from typing import List, Optional, Tuple, Callable, Any, Dict

import uvicorn
from fastapi import FastAPI, APIRouter, Depends
from fastapi.responses import JSONResponse
from substrateinterface import Keypair
from fastapi import FastAPI, APIRouter, Request, Response, Depends
from starlette.responses import Response
from starlette.requests import Request
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from typing import List, Optional, Tuple, Callable, Any, Dict
from starlette.requests import Request
from starlette.responses import Response
from substrateinterface import Keypair

import bittensor
from bittensor.errors import (
InvalidRequestNameError,
SynapseDendriteNoneException,
Expand Down Expand Up @@ -567,7 +567,7 @@ def verify_custom(synapse: MyCustomSynapse):
self.forward_fns[request_name] = forward_fn

# Parse required hash fields from the forward function protocol defaults
required_hash_fields = request_class.__dict__["__fields__"][
required_hash_fields = request_class.__dict__["model_fields"][
"required_hash_fields"
].default
self.required_hash_fields[request_name] = required_hash_fields
Expand Down
20 changes: 10 additions & 10 deletions bittensor/dendrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,15 +446,15 @@ async def single_axon_response(
# If in streaming mode, return the async_generator
return self.call_stream(
target_axon=target_axon,
synapse=synapse.copy(), # type: ignore
synapse=synapse.model_copy(), # type: ignore
timeout=timeout,
deserialize=deserialize,
)
else:
# If not in streaming mode, simply call the axon and get the response.
return await self.call(
target_axon=target_axon,
synapse=synapse.copy(), # type: ignore
synapse=synapse.model_copy(), # type: ignore
timeout=timeout,
deserialize=deserialize,
)
Expand Down Expand Up @@ -521,7 +521,7 @@ async def call(
async with (await self.session).post(
url,
headers=synapse.to_headers(),
json=synapse.dict(),
json=synapse.model_dump(),
timeout=timeout,
) as response:
# Extract the JSON response from the server
Expand Down Expand Up @@ -603,7 +603,7 @@ async def call_stream(
async with (await self.session).post(
url,
headers=synapse.to_headers(),
json=synapse.dict(),
json=synapse.model_dump(),
timeout=timeout,
) as response:
# Use synapse subclass' process_streaming_response method to yield the response chunks
Expand Down Expand Up @@ -700,9 +700,9 @@ def process_server_response(
if server_response.status == 200:
# If the response is successful, overwrite local synapse state with
# server's state only if the protocol allows mutation. To prevent overwrites,
# the protocol must set allow_mutation = False
# the protocol must set Frozen = True
server_synapse = local_synapse.__class__(**json_response)
for key in local_synapse.dict().keys():
for key in local_synapse.model_dump().keys():
try:
# Set the attribute in the local synapse from the corresponding
# attribute in the server synapse
Expand All @@ -717,16 +717,16 @@ def process_server_response(
# Merge dendrite headers
local_synapse.dendrite.__dict__.update(
{
**local_synapse.dendrite.dict(exclude_none=True), # type: ignore
**server_headers.dendrite.dict(exclude_none=True), # type: ignore
**local_synapse.dendrite.model_dump(exclude_none=True), # type: ignore
**server_headers.dendrite.model_dump(exclude_none=True), # type: ignore
}
)

# Merge axon headers
local_synapse.axon.__dict__.update(
{
**local_synapse.axon.dict(exclude_none=True), # type: ignore
**server_headers.axon.dict(exclude_none=True), # type: ignore
**local_synapse.axon.model_dump(exclude_none=True), # type: ignore
**server_headers.axon.model_dump(exclude_none=True), # type: ignore
}
)

Expand Down
5 changes: 2 additions & 3 deletions bittensor/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from starlette.responses import StreamingResponse as _StreamingResponse
from starlette.types import Send, Receive, Scope
from typing import Callable, Awaitable
from pydantic import BaseModel
from pydantic import ConfigDict, BaseModel
from abc import ABC, abstractmethod


Expand Down Expand Up @@ -36,8 +36,7 @@ class StreamingSynapse(bittensor.Synapse, ABC):
and extract JSON data. It also includes a method to create a streaming response object.
"""

class Config:
validate_assignment = True
model_config = ConfigDict(validate_assignment=True)

class BTStreamingResponse(_StreamingResponse):
"""
Expand Down
Loading

0 comments on commit bfef073

Please sign in to comment.