|
| 1 | +import asyncio |
| 2 | +from typing import Union, AsyncGenerator, Any |
| 3 | + |
| 4 | +import aiohttp |
| 5 | +import bittensor as bt |
| 6 | +from aiohttp import ServerTimeoutError, ClientConnectorError, ClientConnectionError |
| 7 | +from bittensor import dendrite |
| 8 | +import traceback |
| 9 | +import time |
| 10 | +from typing import Optional, List |
| 11 | + |
| 12 | +from .protocol import StreamPrompting |
| 13 | + |
| 14 | + |
| 15 | +class CortexDendrite(dendrite): |
| 16 | + task_id = 0 |
| 17 | + miner_to_session = {} |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, wallet: Optional[Union[bt.wallet, bt.Keypair]] = None |
| 21 | + ): |
| 22 | + super().__init__(wallet) |
| 23 | + |
| 24 | + async def call_stream( |
| 25 | + self, |
| 26 | + target_axon: Union[bt.AxonInfo, bt.axon], |
| 27 | + synapse: bt.StreamingSynapse = bt.Synapse(), # type: ignore |
| 28 | + timeout: float = 12.0, |
| 29 | + deserialize: bool = True, |
| 30 | + organic: bool = True |
| 31 | + ) -> AsyncGenerator[Any, Any]: |
| 32 | + start_time = time.time() |
| 33 | + target_axon = ( |
| 34 | + target_axon.info() |
| 35 | + if isinstance(target_axon, bt.axon) |
| 36 | + else target_axon |
| 37 | + ) |
| 38 | + |
| 39 | + # Build request endpoint from the synapse class |
| 40 | + request_name = synapse.__class__.__name__ |
| 41 | + endpoint = ( |
| 42 | + f"0.0.0.0:{str(target_axon.port)}" |
| 43 | + if target_axon.ip == str(self.external_ip) |
| 44 | + else f"{target_axon.ip}:{str(target_axon.port)}" |
| 45 | + ) |
| 46 | + url = f"http://{endpoint}/{request_name}" |
| 47 | + |
| 48 | + # Preprocess synapse for making a request |
| 49 | + synapse: StreamPrompting = self.preprocess_synapse_for_request(target_axon, synapse, timeout) # type: ignore |
| 50 | + max_try = 0 |
| 51 | + timeout = aiohttp.ClientTimeout(total=100, connect=timeout, sock_connect=timeout, sock_read=timeout) |
| 52 | + connector = aiohttp.TCPConnector(limit=200) |
| 53 | + session = aiohttp.ClientSession(timeout=timeout, connector=connector) |
| 54 | + try: |
| 55 | + while max_try < 2: |
| 56 | + async with session.post( |
| 57 | + url, |
| 58 | + headers=synapse.to_headers(), |
| 59 | + json=synapse.dict(), |
| 60 | + ) as response: |
| 61 | + # Use synapse subclass' process_streaming_response method to yield the response chunks |
| 62 | + try: |
| 63 | + async for chunk in synapse.process_streaming_response(response, organic): # type: ignore |
| 64 | + yield chunk # Yield each chunk as it's processed |
| 65 | + except aiohttp.client_exceptions.ClientPayloadError: |
| 66 | + pass |
| 67 | + except ConnectionRefusedError as err: |
| 68 | + bt.logging.error(f"can not connect to miner for now. connection failed") |
| 69 | + max_try += 1 |
| 70 | + continue |
| 71 | + except ClientConnectorError as err: |
| 72 | + bt.logging.error(f"can not connect to miner for now. retrying") |
| 73 | + max_try += 1 |
| 74 | + continue |
| 75 | + except ClientConnectionError as err: |
| 76 | + bt.logging.error(f"can not connect to miner for now. retrying") |
| 77 | + max_try += 1 |
| 78 | + continue |
| 79 | + except ServerTimeoutError as err: |
| 80 | + bt.logging.error(f"timeout error happens. max_try is {max_try}") |
| 81 | + max_try += 1 |
| 82 | + continue |
| 83 | + except Exception as err: |
| 84 | + bt.logging.error(f"{err} issue from miner {synapse.uid} {synapse.provider} {synapse.model}") |
| 85 | + finally: |
| 86 | + pass |
| 87 | + break |
| 88 | + |
| 89 | + except Exception as e: |
| 90 | + bt.logging.error(f"{e} {traceback.format_exc()}") |
| 91 | + finally: |
| 92 | + synapse.dendrite.process_time = str(time.time() - start_time) |
| 93 | + await session.close() |
| 94 | + |
| 95 | + async def call_stream_in_batch( |
| 96 | + self, |
| 97 | + target_axons: List[Union[bt.AxonInfo, bt.axon]], |
| 98 | + synapses: List[bt.StreamingSynapse] = bt.Synapse(), # type: ignore |
| 99 | + timeout: float = 12.0, |
| 100 | + deserialize: bool = True, |
| 101 | + ) -> AsyncGenerator[Any, Any]: |
| 102 | + pass |
0 commit comments