Text Generation
Transformers
Safetensors
English
speech
duplex
voice-assistant
streaming
tool-calling
qwen
text-to-speech
Instructions to use sadmN/aiden-duplex with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use sadmN/aiden-duplex with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="sadmN/aiden-duplex")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("sadmN/aiden-duplex", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use sadmN/aiden-duplex with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "sadmN/aiden-duplex" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/sadmN/aiden-duplex
- SGLang
How to use sadmN/aiden-duplex with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "sadmN/aiden-duplex" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "sadmN/aiden-duplex" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "sadmN/aiden-duplex", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use sadmN/aiden-duplex with Docker Model Runner:
docker model run hf.co/sadmN/aiden-duplex
Tool routing, follow-up reuse, history budget, tab takeover, auto-reconnect
Browse files35 unmodified lines36373839404123 unmodified lines6566676869701 unmodified line7273747576777823 unmodified lines10210310410510610717 unmodified lines1251261271281291304 unmodified lines13513613713813914016 unmodified lines157158159160161162163164165183 unmodified lines34935035135235335435555 unmodified lines4114124134144154164174 unmodified lines4224234244254264273 unmodified lines431432433434435436393 unmodified lines83083183283383483583683718 unmodified lines85685785885986035 unmodified lines<label>Access code <input type="password" name="code" required autofocus></label><button>Open demo</button></form></body></html>'''PLAYBACK_TAIL = .45ACK_WORD = r'(?:ok(?:ay)?|(?:m+\s*h+m+|m{2,})|uh\s*huh|yeah|yep|yup|right|sure|thanks|thank you|got it|I see)'BACKCHANNEL = re.compile(rf'{ACK_WORD}(?:\s+{ACK_WORD})*', re.I)STOP_REQUEST = re.compile(r'(?:stop|wait|hold on|one second|just a second)', re.I)23 unmodified linesSEARCH_META = re.compile(r'^\s*(?:results?|history|bar|box|engine|settings?|terms?)\b', re.I)SEARCH_FILLER = re.compile(r'^\s*(?:(?:up|around|for|about|on|at|of|the|a|an|'r'web|net|internet|online|please)\s+)+', re.I)# Leading conversational scaffolding stripped from a query before it reaches Tavily.QUERY_LEAD = re.compile(r'^(?:(?:ok(?:ay)?|now|so|and|hey|please|um+|uh+|well)[,.]?\s+|'1 unmodified liner'(?:do|can|could|would|will)\s+you\s+(?:tell|know|find)\s+|'r'i\s+(?:want|need)\s+to\s+know\s+(?:about\s+)?)+', re.I)FRESH_EXTRA = re.compile(r'\b(?:stock|share)\s+prices?\b|\bstocks?\b|\bshare\s+prices?\b|'r'\bexchange\s+rates?\b|\bworld\s+cup\b|\bprice\s+of\b|'r'\belections?\b|\bbreaking\s+news\b|\bcurrent\s+(?:price|value)\b|'r'\b(?:dow\s+jones|nasdaq|s&p\s*500)\b', re.I)FRESH_INFO = re.compile(r'\b(?:latest (?:news|updates?|price|version)|current (?:price|exchange rate|weather)|'23 unmodified linesreturn len(content.split()) >= 2 and content.split()[-1] not in ('but', 'and', 'so')def split_lead(text, max_words=8):"""Short first clause: TTS cost scales with audio length, so a ~1 s lead-ingets the avatar moving while the rest of the sentence synthesises."""17 unmodified linesreturn query[:limit].strip()def requested_search(text, history=()):"""Return a query for explicit searches and narrowly recognized fresh facts.4 unmodified lines"""if NO_WEB.search(text):return Noneverb = SEARCH_VERB.search(text)if verb and SEARCH_NOUN.search(text[verb.end():]):tail = text[verb.end():]16 unmodified lines# URL-shaped query, so it still needs the pronoun/topic resolution below.query = clean_query(text)else:match = WEB_PREFIX.match(text)if not match:return Nonequery = clean_query(text[match.end():].strip(' :?.'))if REFERENCE.search(query) and len(query.split()) <= 8:# Use only the immediately preceding user topic, never the whole history.183 unmodified linesclass Connection:def __init__(self, demo, ws):self.demo, self.ws = demo, wsself.history = deque(maxlen=6)self.epoch, self.reply = 0, Noneself.pre = deque(maxlen=6)self.pcm, self.quiet, self.voiced = bytearray(), 0, 055 unmodified linesr.task = self.spawn(self.generate(r, events or [{'text': text}]))def history_messages(self):return [m for turn in self.history for m in turn]async def generate(self, r, events):loop = asyncio.get_running_loop()4 unmodified linesaudio = self.spawn(self.speak(r))public = []seen = set()history = self.history_messages()available = tools_for_turn(self.demo.brain.tools, r.text, history)3 unmodified linescall = {'type': 'function', 'function': {'name': 'web_search','arguments': {'query': search_query}}}ack = 'I’ll check the web.'public.append(ack)r.speech.put_nowait(ack)results = await self.resolve_tools(r, [call])393 unmodified linesasync def ws(self, request):if not self.authorized(request) or not self.valid_origin(request):raise web.HTTPForbidden()if self.connection:raise web.HTTPServiceUnavailable(text='Aiden already has an active demo session.')ws = web.WebSocketResponse(heartbeat=20, max_msg_size=16384)conn = self.connection = Connection(self, ws)try:18 unmodified linesfor task in pending:task.cancel()await asyncio.gather(*pending, return_exceptions=True)self.connection = Nonereturn ws35 unmodified lines363738394041424323 unmodified lines67686970717273747576777879808182838485868788899091929394959697981 unmodified line10010110210310410510610723 unmodified lines13113213313413513613713813914017 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292304 unmodified lines23523623723823924024124224324424524624724816 unmodified lines265266267268269270271272273274275276277183 unmodified lines46146246346446546646755 unmodified lines5235245255265275285295305315325335345355365375385395405414 unmodified lines5465475485495505515523 unmodified lines556557558559560561562393 unmodified lines95695795895996096196296396496596696796896997097197297397497597618 unmodified lines995996997998999100035 unmodified lines<label>Access code <input type="password" name="code" required autofocus></label><button>Open demo</button></form></body></html>'''PLAYBACK_TAIL = .45HISTORY_TURNS = 24 # how many exchanges may be keptHISTORY_CHARS = 24000 # ~6k tokens; the 4B window is far larger than thisACK_WORD = r'(?:ok(?:ay)?|(?:m+\s*h+m+|m{2,})|uh\s*huh|yeah|yep|yup|right|sure|thanks|thank you|got it|I see)'BACKCHANNEL = re.compile(rf'{ACK_WORD}(?:\s+{ACK_WORD})*', re.I)STOP_REQUEST = re.compile(r'(?:stop|wait|hold on|one second|just a second)', re.I)23 unmodified linesSEARCH_META = re.compile(r'^\s*(?:results?|history|bar|box|engine|settings?|terms?)\b', re.I)SEARCH_FILLER = re.compile(r'^\s*(?:(?:up|around|for|about|on|at|of|the|a|an|'r'web|net|internet|online|please)\s+)+', re.I)# "and ethereum?" names a new subject and still needs a fresh lookup; without this# the model reuses the previous turn's number and calls it the new subject.FOLLOWUP = re.compile(r'^\s*(?:and|what\s+about|how\s+about|also|plus)\b', re.I)# Questions about the conversation itself must never spend a search.META_TALK = re.compile(r'\b(?:what\s+did\s+i\s+(?:ask|say)|what\s+am\s+i\s+asking|'r'my\s+(?:first|last|previous|original)\s+(?:question|request)|'r'you\s+(?:said|told|mentioned))\b', re.I)# A question about a value that changes (score, race, price) needs the web even# when the user does not say "search" or name a fresh-fact noun.LIVE_QUESTION = re.compile(r'^\s*(?:(?:ok(?:ay)?|so|and|but|now|hey)[,.]?\s+)*'r'(?:who|what|when|where|which|how|is|are|was|were|did|does|do|'r'will|would|can|could|should)\b', re.I)TIME_DEICTIC = re.compile(r'\b(?:today|tonight|tomorrow|yesterday|'r'last\s+(?:night|week|weekend|month|season)|'r'this\s+(?:week|weekend|month|year|season)|latest|newest|'r'current(?:ly)?|right\s+now|at\s+the\s+moment|'r'recent(?:ly)?|upcoming|so\s+far)\b', re.I)# Words that make a 1-3 word utterance a reaction, not a subject to look up.FILLER_WORDS = frozenset('''that this it its is was are were be the a an great good nicecool ok okay right yes no thanks thank you wow amazing interesting really sure ha hahahmm mm oh ah'''.split())# Words that carry no subject of their own: "just say what the current price is" is the# previous question again, and searching the literal sentence returns dictionary pages.ELLIPTICAL = frozenset('''just please now ok okay so and but say tell me us give show what is arewas were the a an current currently exactly actually again number figure amount price costvalue rate it its that this there about more'''.split())# Leading conversational scaffolding stripped from a query before it reaches Tavily.QUERY_LEAD = re.compile(r'^(?:(?:ok(?:ay)?|now|so|and|hey|please|um+|uh+|well)[,.]?\s+|'1 unmodified liner'(?:do|can|could|would|will)\s+you\s+(?:tell|know|find)\s+|'r'i\s+(?:want|need)\s+to\s+know\s+(?:about\s+)?)+', re.I)FRESH_EXTRA = re.compile(r'\b(?:stock|share)\s+prices?\b|\bstocks?\b|\bshare\s+prices?\b|'r'\bexchange\s+rates?\b|\bworld\s+cup\b|'r'\bprices?\s+(?:of|for)\b|\bhow\s+much\s+is\b|'r'\belections?\b|\bbreaking\s+news\b|\bcurrent\s+(?:price|value)\b|'r'\b(?:dow\s+jones|nasdaq|s&p\s*500)\b', re.I)FRESH_INFO = re.compile(r'\b(?:latest (?:news|updates?|price|version)|current (?:price|exchange rate|weather)|'23 unmodified linesreturn len(content.split()) >= 2 and content.split()[-1] not in ('but', 'and', 'so')def _norm_words(text):return ' '.join(re.findall(r"[a-z0-9']+", text.lower()))def split_lead(text, max_words=8):"""Short first clause: TTS cost scales with audio length, so a ~1 s lead-ingets the avatar moving while the rest of the sentence synthesises."""17 unmodified linesreturn query[:limit].strip()def _previous_turn_used_tool(history):"""True when the most recent turn already ran a tool."""for m in reversed(history):if m.get('role') == 'tool':return Trueif m.get('role') == 'user':return Falsereturn Falsedef _previous_query(history):"""The query string of the last search, so a pronoun can be resolved against it."""for m in reversed(history):if m.get('role') == 'tool':try:data = json.loads(m.get('content') or '{}')except ValueError:continuequery = data.get('query')if isinstance(query, str) and query:return query[:115]return ''def _topic_query(text, history):query = clean_query(text)if not query:return ''if REFERENCE.search(query):topic = _previous_query(history)if topic and topic.lower() not in query.lower():return f'{query} — topic: {topic}'[:256]return query[:256]def _subject_words(text):return [w for w in (x.strip('.,!?;:').lower() for x in text.split())if w and w not in ELLIPTICAL]def followup_search(text, history):"""A short follow-up inherits the previous lookup instead of reusing its numbers."the price of bitcoin" then "and ethereum?" must search ethereum. Otherwise themodel answers with bitcoin's price and presents it as ethereum."""if not history or not _previous_turn_used_tool(history):return Noneif WEATHER.search(text) or META_TALK.search(text) or NO_WEB.search(text):return Noneif not _subject_words(text):# No subject of its own: repeat the previous lookup instead of searching# "what is the current price" and answering from dictionary pages.previous = _previous_query(history)return previous[:256] if previous else Nonewords = text.split()if not (FOLLOWUP.match(text) or len(words) <= 3or (REFERENCE.search(text) and len(words) <= 8)):return Noneif len(words) <= 3 and all(w.strip('.,!?;:').lower() in FILLER_WORDS for w in words):return Nonequery = _topic_query(text, history)if not query or SEARCH_META.match(query):return Nonereturn querydef requested_search(text, history=()):"""Return a query for explicit searches and narrowly recognized fresh facts.4 unmodified lines"""if NO_WEB.search(text):return None# Before any keyword rule: an utterance with no subject of its own ("just say what# the current price is") is the previous question again, and must reuse its query# instead of sending the literal sentence to the search engine.if (history and _previous_turn_used_tool(history) and not _subject_words(text)and not WEATHER.search(text) and not META_TALK.search(text)):previous = _previous_query(history)if previous:return previous[:256]verb = SEARCH_VERB.search(text)if verb and SEARCH_NOUN.search(text[verb.end():]):tail = text[verb.end():]16 unmodified lines# URL-shaped query, so it still needs the pronoun/topic resolution below.query = clean_query(text)else:if (LIVE_QUESTION.match(text) and TIME_DEICTIC.search(text)and not META_TALK.search(text) and not WEATHER.search(text)):# "What's the latest NBA score?" must search, not produce a plausible number.return _topic_query(text, history) or Nonematch = WEB_PREFIX.match(text)if not match:return followup_search(text, history)query = clean_query(text[match.end():].strip(' :?.'))if REFERENCE.search(query) and len(query.split()) <= 8:# Use only the immediately preceding user topic, never the whole history.183 unmodified linesclass Connection:def __init__(self, demo, ws):self.demo, self.ws = demo, wsself.history = deque()self.epoch, self.reply = 0, Noneself.pre = deque(maxlen=6)self.pcm, self.quiet, self.voiced = bytearray(), 0, 055 unmodified linesr.task = self.spawn(self.generate(r, events or [{'text': text}]))def history_messages(self):"""Most recent turns that fit the budget, oldest dropped first.A fixed 6-turn deque made the model forget the start of any realconversation. The window is large; this cap is what should bound it."""turns, size = [], 0for turn in reversed(self.history):tsize = sum(len(m.get('content') or '') for m in turn)if turns and (len(turns) >= HISTORY_TURNS or size + tsize > HISTORY_CHARS):breakturns.append(turn)size += tsizereturn [m for turn in reversed(turns) for m in turn]async def generate(self, r, events):loop = asyncio.get_running_loop()4 unmodified linesaudio = self.spawn(self.speak(r))public = []ack_norm = ''seen = set()history = self.history_messages()available = tools_for_turn(self.demo.brain.tools, r.text, history)3 unmodified linescall = {'type': 'function', 'function': {'name': 'web_search','arguments': {'query': search_query}}}ack = 'I’ll check the web.'ack_norm = _norm_words(ack)public.append(ack)r.speech.put_nowait(ack)results = await self.resolve_tools(r, [call])393 unmodified linesasync def ws(self, request):if not self.authorized(request) or not self.valid_origin(request):raise web.HTTPForbidden()previous = self.connectionif previous is not None:# One live session, but the newest tab wins. A stale or abandoned session# used to lock everyone else out with a 503, which the UI shows as# "disconnected" with no audio.self.connection = NoneLOG.info('replacing an existing demo session')try:await previous.cancel('replaced by a newer session')except Exception:LOG.exception('old session cancel failed')try:await previous.ws.close()except Exception:passws = web.WebSocketResponse(heartbeat=20, max_msg_size=16384)conn = self.connection = Connection(self, ws)try:18 unmodified linesfor task in pending:task.cancel()await asyncio.gather(*pending, return_exceptions=True)if self.connection is conn:self.connection = None # never clear a newer tab's sessionreturn ws
code/duplex/live_session.py+147-7