Question Answering
sentence-transformers
Safetensors
GGUF
English
retrieval
cross-encoder
verification
citations
edge
cpu
offline
Eval Results (legacy)
Instructions to use RysoAI/tinyqa-1-moss with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use RysoAI/tinyqa-1-moss with sentence-transformers:
from sentence_transformers import CrossEncoder model = CrossEncoder("RysoAI/tinyqa-1-moss") query = "Which planet is known as the Red Planet?" passages = [ "Venus is often called Earth's twin because of its similar size and proximity.", "Mars, known for its reddish appearance, is often referred to as the Red Planet.", "Jupiter, the largest planet in our solar system, has a prominent red spot.", "Saturn, famous for its rings, is sometimes mistaken for the Red Planet." ] scores = model.predict([(query, passage) for passage in passages]) print(scores) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use RysoAI/tinyqa-1-moss with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf RysoAI/tinyqa-1-moss:Q8_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf RysoAI/tinyqa-1-moss:Q8_0
Use Docker
docker model run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Llama new
- LM Studio
- Jan
- Ollama
How to use RysoAI/tinyqa-1-moss with Ollama:
ollama run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Unsloth Desktop
- Docker Model Runner
How to use RysoAI/tinyqa-1-moss with Docker Model Runner:
docker model run hf.co/RysoAI/tinyqa-1-moss:Q8_0
- Lemonade
How to use RysoAI/tinyqa-1-moss with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull RysoAI/tinyqa-1-moss:Q8_0
Run and chat with the model
lemonade run user.tinyqa-1-moss-Q8_0
List all available models
lemonade list
- Atomic Chat
File size: 36,626 Bytes
da32fba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | import collections, json, os, random, re, string, sys, time
from concurrent.futures import ThreadPoolExecutor
HERE = os.path.dirname(os.path.abspath(__file__))
BK = os.environ.get('MOSS_HOME', os.path.dirname(os.path.dirname(HERE)))
DATA = os.environ.get('MOSS_DATA', os.path.join(BK, 'data'))
os.makedirs(DATA, exist_ok=True)
CACHE = os.environ.get('MOSS_WEBQA_CACHE', os.path.join(DATA, 'webqa_cache.json'))
def normalize(s):
s = s.lower()
s = ''.join((ch for ch in s if ch not in set(string.punctuation)))
s = re.sub('\\b(a|an|the)\\b', ' ', s)
return ' '.join(s.split())
def contains(text, answers):
t = normalize(text)
return any((normalize(a) and normalize(a) in t for a in answers))
CACHE_DDGS = os.path.join(DATA, 'webqa_cache.json')
CACHE_SERPER = os.path.join(DATA, 'webqa_cache_serper.json')
_caches = {'ddgs': json.load(open(CACHE_DDGS)) if os.path.exists(CACHE_DDGS) else {}, 'serper': json.load(open(CACHE_SERPER)) if os.path.exists(CACHE_SERPER) else {}}
def default_provider():
return os.environ.get('MOSS_SEARCH') or 'ddgs'
def _merge_save(path, mem):
import fcntl
with open(path, 'a+') as f:
fcntl.flock(f, fcntl.LOCK_EX)
f.seek(0)
try:
disk = json.load(f)
except Exception:
disk = {}
disk.update(mem)
mem.update(disk)
f.seek(0)
f.truncate()
json.dump(disk, f)
fcntl.flock(f, fcntl.LOCK_UN)
def save_caches():
_merge_save(CACHE_DDGS, _caches['ddgs'])
_merge_save(CACHE_SERPER, _caches['serper'])
if 'searxng' in _caches:
_merge_save(os.path.join(DATA, 'webqa_cache_searxng.json'), _caches['searxng'])
_caches['searxng'] = json.load(open(os.path.join(DATA, 'webqa_cache_searxng.json'))) if os.path.exists(os.path.join(DATA, 'webqa_cache_searxng.json')) else {}
_cache = _caches[default_provider()]
SERPER_LEDGER = os.path.join(DATA, 'serper_calls.json')
import threading
_LEDGER_LOCK = threading.Lock()
def _count_serper():
import fcntl
with _LEDGER_LOCK, open(SERPER_LEDGER, 'a+') as f:
fcntl.flock(f, fcntl.LOCK_EX)
f.seek(0)
try:
d = json.load(f)
except Exception:
d = {'calls': 0}
d['calls'] = d.get('calls', 0) + 1
d['last'] = time.strftime('%Y-%m-%d %H:%M')
f.seek(0)
f.truncate()
json.dump(d, f)
fcntl.flock(f, fcntl.LOCK_UN)
def search_serper(q, k=10):
import urllib.request
for attempt in range(3):
try:
return _search_serper_once(q, k)
except Exception as ex:
if '429' not in str(ex) or attempt == 2:
raise
time.sleep(3 + 4 * attempt)
def _search_serper_once(q, k=10):
import urllib.request
_count_serper()
req = urllib.request.Request('https://google.serper.dev/search', data=json.dumps({'q': q, 'num': k}).encode(), headers={'X-API-KEY': os.environ['SERPER_API_KEY'], 'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=20) as r:
d = json.load(r)
out = []
ab = d.get('answerBox') or {}
if ab.get('answer') or ab.get('snippet'):
out.append({'title': ab.get('title', 'Answer box'), 'body': ' '.join((x for x in (ab.get('answer'), ab.get('snippet')) if x)), 'href': ab.get('link', '')})
kg = d.get('knowledgeGraph') or {}
if kg.get('description'):
out.append({'title': kg.get('title', ''), 'body': f"{kg.get('title', '')} is {kg.get('type', '')}. {kg['description']}", 'href': kg.get('website', '') or kg.get('descriptionLink', '')})
for x in d.get('organic', [])[:k]:
out.append({'title': x.get('title', ''), 'body': x.get('snippet', ''), 'href': x.get('link', '')})
return out
def search_searxng(q, k=10):
import urllib.request, urllib.parse
url = os.environ['SEARXNG_URL'].rstrip('/') + '/search?' + urllib.parse.urlencode({'q': q, 'format': 'json', 'language': 'en', 'safesearch': 0})
with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'moss/0.1'}), timeout=25) as r:
d = json.load(r)
out = []
for a in d.get('answers', [])[:2]:
out.append({'title': 'Answer', 'body': a if isinstance(a, str) else str(a.get('answer', a)), 'href': ''})
for x in d.get('results', [])[:k]:
out.append({'title': x.get('title', ''), 'body': x.get('content', ''), 'href': x.get('url', '')})
return out
LOCAL_DB = os.environ.get('MOSS_CORPUS_DB', os.path.join(DATA, 'corpus.sqlite'))
def _passages(text, size=420):
for para in re.split('\\n\\s*\\n', text):
para = ' '.join(para.split())
if not para or para.startswith('#'):
continue
cur = ''
for sent in _SENT.split(para):
if cur and len(cur) + len(sent) > size:
yield cur
cur = ''
cur = (cur + ' ' + sent).strip()
if cur:
yield cur
def index_corpus(src, db=LOCAL_DB):
import sqlite3
os.makedirs(os.path.dirname(os.path.abspath(db)), exist_ok=True)
if os.path.exists(db):
os.remove(db)
con = sqlite3.connect(db)
con.execute("CREATE VIRTUAL TABLE p USING fts5(title, body, href UNINDEXED, tokenize='porter unicode61')")
def docs():
if os.path.isfile(src) and src.endswith('.jsonl'):
for i, line in enumerate(open(src, encoding='utf-8', errors='ignore')):
d = json.loads(line)
yield (d.get('title') or f'document {i + 1}', d.get('text', ''), d.get('url') or f'{os.path.basename(src)}#{i + 1}')
return
for root, _, files in os.walk(src):
for fn in sorted(files):
if not fn.lower().endswith(('.txt', '.md', '.markdown')):
continue
path = os.path.join(root, fn)
text = open(path, encoding='utf-8', errors='ignore').read()
m = re.search('^#\\s+(.+)$', text, re.M)
title = m.group(1).strip() if m else os.path.splitext(fn)[0].replace('_', ' ').replace('-', ' ')
yield (title, text, 'file://' + os.path.abspath(path))
n = 0
for title, text, href in docs():
rows = [(title, ps, href) for ps in _passages(text)]
con.executemany('INSERT INTO p VALUES (?, ?, ?)', rows)
n += len(rows)
con.commit()
con.close()
return n
def search_local(q, k=10, db=LOCAL_DB):
import sqlite3
if not os.path.exists(db):
return []
terms = [t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QSTOP and len(t) > 1]
if not terms:
return []
con = sqlite3.connect(db)
try:
rows = con.execute('SELECT title, body, href FROM p WHERE p MATCH ? ORDER BY bm25(p, 2.0, 1.0) LIMIT ?', (' OR '.join((f'"{t}"' for t in terms)), k)).fetchall()
finally:
con.close()
return [{'title': t, 'body': b, 'href': h} for t, b, h in rows]
def search(q, k=10, provider=None):
provider = provider or default_provider()
if provider == 'local':
return search_local(q, k)
if provider == 'serper' and (not os.environ.get('SERPER_API_KEY')):
provider = 'ddgs'
if provider == 'searxng' and (not os.environ.get('SEARXNG_URL')):
provider = 'ddgs'
c = _caches[provider]
if provider == 'searxng':
if q in c:
return c[q]
try:
r = search_searxng(q, k)
res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r]
if res:
c[q] = res
return res
except Exception as ex:
print(f'[webqa] searxng failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True)
c = _caches['ddgs']
if q in c:
return c[q]
if q in c:
return c[q]
if provider == 'serper':
try:
r = search_serper(q, k)
res = [{'title': clean_title(x['title']), 'body': clean_body(x['body']), 'href': x['href']} for x in r]
if res:
c[q] = res
return res
except Exception as ex:
print(f'[webqa] serper failed ({type(ex).__name__}); falling back to DuckDuckGo', flush=True)
c = _caches['ddgs']
if q in c:
return c[q]
from ddgs import DDGS
r = []
for attempt, backend in enumerate(('auto', 'google', 'bing', 'auto')):
try:
r = DDGS().text(q, max_results=k, backend=backend) or []
if r:
break
except Exception as ex:
r = []
time.sleep(1.5 + 2 * attempt)
res = [{'title': clean_title(x.get('title', '')), 'body': clean_body(x.get('body', '')), 'href': x.get('href', '')} for x in r]
if res:
c[q] = res
return res
_SENT = re.compile('(?<=[.!?])\\s+(?=[A-Z0-9\\"\'(])')
_DATE = re.compile('^(?:[A-Z][a-z]{2} \\d{1,2}, \\d{4}|\\d{1,2} [A-Z][a-z]{2} \\d{4})\\s*[·•-]\\s*')
def clean_title(t):
t = re.sub('([a-z]{4,})([A-Z][a-z]{2,})', '\\1 | \\2', t.strip())
t = re.split('\\s+\\|\\s+', t.strip())[0]
return t[:110].rstrip()
def clean_body(b):
return _DATE.sub('', b.strip())
STRICT = os.environ.get('MOSS_STRICT') == '1'
BLOCK = [d for d in os.environ.get('MOSS_BLOCK_DOMAINS', 'huggingface.co,kaggle.com,github.com,paperswithcode.com,simple-evals,simpleqa,freshqa,popqa').split(',') if d]
PAGES = int(os.environ.get('MOSS_PAGES', '0'))
PAGE_DIR = os.path.join(DATA, 'pages')
os.makedirs(PAGE_DIR, exist_ok=True)
_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36'
def fetch_text(url, timeout=12):
import hashlib, urllib.request, socket
socket.setdefaulttimeout(timeout)
p = os.path.join(PAGE_DIR, hashlib.sha1(url.encode()).hexdigest() + '.txt')
if os.path.exists(p):
return open(p).read()
txt = ''
try:
import trafilatura
req = urllib.request.Request(url, headers={'User-Agent': _UA, 'Accept-Language': 'en'})
html = urllib.request.urlopen(req, timeout=timeout).read(2000000).decode('utf-8', 'ignore')
txt = trafilatura.extract(html, include_comments=False, include_tables=True) or ''
except Exception:
txt = ''
open(p, 'w').write(txt)
return txt
def page_candidates(q, results, n_pages, cap=150):
qt = {t for t in re.findall('[a-z0-9]+', q.lower()) if t not in QWORDS and len(t) > 2}
out = []
for r in results[:n_pages]:
if not r.get('href') or any((b in r['href'].lower() for b in BLOCK)):
continue
txt = fetch_text(r['href'])
for s in _SENT.split(' '.join(txt.split())):
s = s.strip()
if 25 <= len(s) <= 400 and len(qt & set(re.findall('[a-z0-9]+', s.lower()))) >= max(1, min(2, len(qt) // 3)):
out.append({'sent': s, 'title': r['title'], 'url': r['href'], 'body': s, 'from_page': True})
if len(out) > cap:
out.sort(key=lambda c: -len(qt & set(re.findall('[a-z0-9]+', c['sent'].lower()))))
out = out[:cap]
return out
PROSE = os.environ.get('MOSS_PROSE', '1') == '1'
SOURCE_PENALTY = os.environ.get('MOSS_SOURCE_PENALTY', '0') == '1'
QUOTABLE = os.environ.get('MOSS_QUOTABLE', '0') == '1'
SOCIAL = ('reddit.com', 'quora.com', 'facebook.com', 'instagram.com', 'tiktok.com', 'pinterest.', 'youtube.com', 'answers.com', 'brainly.', 'quizlet', 'x.com/', 'twitter.com')
_ROW = re.compile('^\\s*\\d+[.,)]\\s')
def is_prose(s):
if len(re.findall('[A-Za-z]{3,}', s)) < 4 or _ROW.match(s) or '|' in s or (s.count('·') >= 2):
return False
if ';' in s and len(s.split()) < 10:
return False
words = s.split()
if s.count(' – ') + s.count(' — ') >= 4:
return False
if len(words) > 45 and (s.count(' – ') + s.count(' — ') >= 2 or sum((w[:1].isupper() for w in words)) / len(words) > 0.5):
return False
return sum((1 for ch in s if ch.isdigit() or ch in ',;·|')) / max(1, len(s)) <= 0.25
CUTS = os.environ.get('MOSS_CUTS', '1') == '1'
_GLUE = re.compile('(?<=[a-z0-9][.!?])(?=[A-Z][a-z])|\\s*(?:\\.\\.\\.|…)\\s*')
def cuts(s):
parts = [p.strip(' ,;:') for p in _GLUE.split(s)]
parts = [p for p in parts if len(p) > 15]
return parts if len(parts) > 1 else []
_BOILER = re.compile('^(?:See full list on \\S+\\s*)?(?:[A-Z][a-z]{2}\\.? \\d{1,2}, \\d{4}\\s*[·—–-]\\s*)?(?:\\d{1,2} [A-Z][a-z]{2,8} \\d{4}\\s*[·—–-]\\s*)?')
def candidates(results, q=None):
out = []
if PAGES and q:
out += page_candidates(q, results, PAGES)
for r in results:
if any((b in (r.get('href', '') + ' ' + r.get('title', '')).lower() for b in BLOCK)):
continue
for s in _SENT.split(re.sub('\\s*\\[\\d{1,3}\\]', '', r['body']).strip()):
s = _BOILER.sub('', s.strip()).strip()
for t in [s] + (cuts(s) if CUTS else []):
if len(t) > 15 and (not PROSE or is_prose(t)):
out.append({'sent': t, 'title': clean_title(r['title']), 'url': r['href'], 'body': r['body']})
return out
def _cap(t):
return t[:1].upper() + t[1:]
_PAST = {'end': 'ended', 'begin': 'began', 'start': 'started', 'happen': 'happened', 'die': 'died', 'occur': 'occurred', 'open': 'opened', 'close': 'closed', 'finish': 'finished', 'take place': 'took place'}
def lead(q, span):
s = re.sub('\\s+', ' ', q.strip().rstrip('?').strip())
b = f'**{span}**'
prep = '' if re.match('^(?:between|from|in|on|at|during|around|about|circa|since|after|before)\\b', span, re.I) else 'in '
m = re.match('^who (was|is|were|are) (.+)$', s, re.I)
if m:
return f'{_cap(m.group(2))} {m.group(1).lower()} {b}.'
m = re.match('^who (founded|created|invented|wrote|directed|discovered|built|designed|painted|composed|developed|produced|started|established|won|scored) (.+)$', s, re.I)
if m:
return f'{_cap(m.group(2))} was {m.group(1).lower()} by {b}.'
m = re.match('^(what|which) (is|was|are|were) (.+)$', s, re.I)
if m:
return f'{_cap(m.group(3))} {m.group(2).lower()} {b}.'
m = re.match('^where (is|was|are|were) (.+?)(?: located| based| situated)?$', s, re.I)
if m:
return f'{_cap(m.group(2))} {m.group(1).lower()} {prep}{b}.'
m = re.match('^when (was|were|is) (.+?) (born|founded|released|built|established|created|published|launched|invented|discovered|completed|opened|formed|made|written|elected|crowned|signed)$', s, re.I)
if m:
return f'{_cap(m.group(2))} {m.group(1).lower()} {m.group(3).lower()} {prep}{b}.'
m = re.match('^when did (.+?) (end|begin|start|happen|die|occur|open|close|take place|finish)$', s, re.I)
if m:
return f'{_cap(m.group(1))} {_PAST[m.group(2).lower()]} {prep}{b}.'
return None
QSTOP = {'who', 'what', 'when', 'where', 'which', 'was', 'is', 'are', 'were', 'the', 'did', 'does', 'for', 'of', 'in', 'on', 'at', 'to', 'and', 'how', 'many', 'much', 'a', 'an', 'by', 'from', 'with', 'do', 'has', 'have', 'had', 'that', 'this'}
VERBALIZE = os.environ.get('MOSS_VERBALIZE', 'template')
DECODER_URL = os.environ.get('MOSS_DECODER', 'http://127.0.0.1:8089')
PLANNER_URL = os.environ.get('MOSS_PLANNER', 'http://127.0.0.1:8093')
VERBALISER_URL = os.environ.get('MOSS_VERBALISER', '')
VERB_TAU = float(os.environ.get('MOSS_VERB_TAU', '0.0'))
VERB_SPAN = os.environ.get('MOSS_VERB_SPAN', '0') == '1'
_FUNC = {'the', 'a', 'an', 'is', 'was', 'are', 'were', 'of', 'in', 'on', 'at', 'to', 'for', 'by', 'and', 'or', 'with', 'from', 'as', 'its', 'it', 'that', 'this', 'which', 'who', 'what', 'when', 'where', 'how', 'did', 'does', 'do', 'has', 'have', 'had', 'been', 'be', 'named', 'called', 's'}
def _wordsl(t):
return re.findall('[a-z0-9]+', t.lower())
def _post_json(url, body, timeout=20):
import urllib.request
req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def _tidy_lead(t):
t = re.sub('\\s+', ' ', t).strip().rstrip('.').strip()
return t[:1].upper() + t[1:] + '.' if t else t
def own_lead(q, span, cited, title, natural=True, vscore=None, info=None, q_user=None):
import collections
qc = collections.Counter(_wordsl(q))
sw = set(_wordsl(span))
ew = set(_wordsl(cited)) | set(_wordsl(title)) if natural else set()
for w, n in collections.Counter(_wordsl(q_user or '')).items():
qc[w] = max(qc[w], n)
def content_free(text):
cc = collections.Counter((w for w in _wordsl(text) if w not in _FUNC and w not in sw))
return all((w in qc and cc[w] <= qc[w] or w in ew for w in cc))
if VERBALISER_URL and natural:
try:
vp = f'<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n' + (f'<|span|> {span.strip()}\n' if VERB_SPAN else '') + '<|answer|>'
d = _post_json(f'{VERBALISER_URL}/completion', {'prompt': vp, 'n_predict': 64, 'temperature': 0.0, 'stop': ['<|end|>'], 'cache_prompt': False}, timeout=10)
t = re.sub('\\s+', ' ', d.get('content', '').split('<|end|>')[0]).strip()
v = None
ok = t and t != '<abstain>' and (3 <= len(t.split()) <= 45) and (normalize(span) in normalize(t)) and content_free(t)
if ok and vscore is not None:
v = float(vscore(t))
ok = v >= VERB_TAU
if info is not None:
info.update({'verbaliser': t or None, 'verbaliser_v': None if v is None else round(v, 2)})
if ok:
i = t.lower().find(span.lower())
t = t[:i] + f'**{t[i:i + len(span)]}**' + t[i + len(span):] if i >= 0 else t
return (_tidy_lead(t), 'verbaliser')
except Exception:
pass
try:
g = gbnf(1, allowed=[1]).replace('root ::= "<abstain>" | answer', 'root ::= answer')
d = _post_json(f'{DECODER_URL}/completion', {'prompt': f'<|evidence|>\n[E1] ({title}) {cited}\n<|question|> {q.strip()}\n<|answer|>', 'n_predict': 40, 'temperature': 0.0, 'stop': ['<|end|>'], 'grammar': g, 'cache_prompt': False}, timeout=10)
parts, abst = parse_answer(d.get('content', ''))
if not abst and sum((1 for k, _ in parts if k == 'ref')) == 1:
glue = ' '.join((v for k, v in parts if k == 'glue'))
inserted = normalize(span) not in normalize(glue)
if not inserted:
t = ''.join(('' if k == 'ref' else v for k, v in parts))
i = t.find(span)
t = t[:i] + f'**{span}**' + t[i + len(span):] if i >= 0 else t
else:
t = ''.join((f'**{span}**' if k == 'ref' else v for k, v in parts))
dup = bool((set(_wordsl(glue)) & sw) - (set(qc) if natural else set())) and (inserted or not natural)
if content_free(glue) and (not dup) and (3 <= len(t.split()) <= 30):
return (_tidy_lead(t), 'decoder')
except Exception:
pass
try:
d = _post_json(f'{PLANNER_URL}/completion', {'prompt': f'<|question|> {q.strip()}\n<|plan|>', 'n_predict': 200, 'temperature': 0.0, 'stop': ['<|end|>'], 'cache_prompt': False}, timeout=15)
m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', d.get('content', ''))
hyp = json.loads('"' + m.group(1) + '"') if m else ''
if hyp.count('____') == 1 and content_free(hyp.replace('____', ' ')) and (3 <= len(hyp.split()) <= 30):
return (_tidy_lead(hyp.replace('____', f'**{span}**')), 'planner')
except Exception:
pass
return (None, None)
def quote_clean(q, sent, span):
if not sent or len(sent) > 230 or sent.rstrip()[-1:] not in '.!?' or ('...' in sent) or ('…' in sent):
return False
if span and normalize(span) not in normalize(sent):
return False
cw = [w for w in re.findall('[a-z0-9]+', q.lower()) if w not in QSTOP and len(w) > 2]
ns = normalize(sent)
return sum((1 for w in cw if w in ns)) >= max(1, len(cw) // 2)
FALLBACK = os.environ.get('MOSS_FALLBACK', '0') == '1'
RETRY_TAU = float(os.environ.get('MOSS_RETRY_TAU', '5.5'))
PLANNER_RETRY = os.environ.get('MOSS_PLANNER_RETRY', '0') == '1'
RETRY_PROVIDER = os.environ.get('MOSS_RETRY_PROVIDER', 'serper')
AGREE = int(os.environ.get('MOSS_AGREE', '3'))
SIEVE_RETRY = os.environ.get('MOSS_SIEVE_RETRY', '0') == '1'
_NAMES = re.compile("\\b[A-Z][\\w'’.-]+(?:\\s+(?:(?:de|da|van|von|of|the|du|del|di|la|le|&)\\s+)?[A-Z][\\w'’.-]+){0,3}")
_QCAP = {'The', 'This', 'That', 'What', 'When', 'Where', 'Which', 'Who', 'How', 'Why', 'In', 'On', 'At', 'For', 'From', 'With', 'Name', 'Is', 'Was', 'Are', 'Were', 'Did', 'Does', 'Do'}
_FORUMS = '-site:reddit.com -site:quora.com -site:facebook.com -site:pinterest.com -site:youtube.com -site:answers.com'
def retry_queries(q):
out = [('noforum', f"{q.rstrip('?')} {_FORUMS}")]
ns = [m.strip() for m in _NAMES.findall(q) if m.split()[0] not in _QCAP and len(m) > 2]
if ns:
rest = q
for n in ns:
rest = rest.replace(n, '')
rest = re.sub('^\\s*(who|what|which|when|where|how)\\s+(was|is|were|are|did|does|do)\\s+', '', rest.strip().rstrip('?'), flags=re.I)
out.append(('names', ' '.join((f'"{n}"' for n in ns)) + ' ' + re.sub('\\s+', ' ', rest).strip()))
l = lead(q, '')
if l:
l = l.replace(' ****.', '').replace('****.', '').strip().rstrip('.')
if 3 <= len(l.split()) <= 12:
out.append(('stub', f'"{l}"'))
if PLANNER_RETRY:
try:
d = _post_json(f'{PLANNER_URL}/completion', {'prompt': f'<|question|> {q.strip()}\n<|plan|>', 'n_predict': 240, 'temperature': 0.0, 'stop': ['<|end|>'], 'cache_prompt': False}, timeout=15)
txt = d.get('content', '')
m = re.search('"hypothetical"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"', txt)
hyp = json.loads('"' + m.group(1) + '"') if m else ''
terms = re.findall('"([^"]{2,40})"', txt.split('"search_terms"')[1].split(']')[0]) if '"search_terms"' in txt else []
ents = re.findall('"([^"]{2,40})"', txt.split('"entities"')[1].split(']')[0]) if '"entities"' in txt else []
tq = ' '.join(dict.fromkeys(ents + terms))
if len(tq.split()) >= 2:
out.append(('plan_terms', tq[:160]))
h = re.sub('\\s+', ' ', hyp.replace('____', ' ')).strip(' .')
import collections as _c
qc = _c.Counter(_wordsl(q))
hc = _c.Counter((w for w in _wordsl(h) if w not in _FUNC))
if 3 <= len(h.split()) <= 14 and all((hc[w] <= qc.get(w, 0) + (0 if w in qc else 1) for w in hc)):
out.append(('plan_stub', f'"{h}"'))
except Exception:
pass
return out
SPELL = os.environ.get('MOSS_SPELL', '1') == '1'
TAU_V = float(os.environ.get('MOSS_TAU_V', '3.0'))
def _lev(a, b):
if abs(len(a) - len(b)) > 3:
return 9
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
d[i][0] = i
for j in range(len(b) + 1):
d[0][j] = j
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
c = a[i - 1] != b[j - 1]
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c)
if i > 1 and j > 1 and (a[i - 1] == b[j - 2]) and (a[i - 2] == b[j - 1]):
d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
return d[-1][-1]
def corpus_spelling(q, results):
import collections
vocab = collections.Counter()
for r in results:
for w in set(re.findall('[a-z]{4,}', (r.get('title', '') + ' ' + r.get('body', '')).lower())):
vocab[w] += 1
fixes = {}
for w in re.findall('\\b[a-z]{5,}\\b', q):
if w in vocab or w in QSTOP or w in _FUNC:
continue
best = min(((_lev(w, v), -n, v) for v, n in vocab.items() if n >= 2 and abs(len(v) - len(w)) <= 3), default=None)
if best and 0 < best[0] <= (3 if len(w) >= 8 else 2):
fixes[w] = best[2]
out = q
for w, v in fixes.items():
out = re.sub('\\b' + re.escape(w) + '\\b', v, out)
return (out, fixes)
QWORDS = set('a an the of in on at to for by with and or is are was were be been being who what when where which how why did does do that this these those it its as from into than then there their his her he she they them many much can could should would will i you my me your have has had not no about tell explain give list name wont dont cant whats isnt doesnt didnt im ive'.split())
MAX_EVIDENCE = 16
REF_TOKENS = [f'<q E{i}>' for i in range(1, MAX_EVIDENCE + 1)]
ABSTAIN = '<abstain>'
BOS_EVIDENCE, BOS_QUESTION, BOS_ANSWER, EOS_ANSWER = ('<|evidence|>', '<|question|>', '<|answer|>', '<|end|>')
def gbnf(n_evidence: int, max_glue_tokens: int=40, allowed: list[int] | None=None) -> str:
ids = allowed or list(range(1, n_evidence + 1))
refs = ' | '.join((f'"<q E{i}>"' for i in ids))
return f'root ::= "{ABSTAIN}" | answer\nanswer ::= segment+ glue?\nsegment ::= glue? ref\nref ::= {refs}\nglue ::= [^<]{{1,{max_glue_tokens * 5}}}\n'
REF_RE = re.compile('<q E(\\d+)>')
def parse_answer(text: str) -> tuple[list[tuple[str, str]], bool]:
text = text.split(EOS_ANSWER)[0].strip()
if text.startswith(ABSTAIN):
return ([], True)
parts: list[tuple[str, str]] = []
pos = 0
for m in REF_RE.finditer(text):
glue = text[pos:m.start()]
if glue.strip():
parts.append(('glue', glue))
parts.append(('ref', f'E{m.group(1)}'))
pos = m.end()
tail = text[pos:]
if tail.strip():
parts.append(('glue', tail))
return (parts, False)
class Stack:
def __init__(self):
from sentence_transformers import CrossEncoder
dev = os.environ.get('MOSS_DEVICE', 'cpu')
self.rank = CrossEncoder(os.environ.get('MOSS_RANKER') or os.path.join(BK, 'models', 'ranker'), max_length=256, device=dev)
self.verify = CrossEncoder(os.environ.get('MOSS_VERIFIER') or os.path.join(BK, 'models', 'verifier'), max_length=256, device=dev)
from .extract import extract as _extract
self.extract = _extract
self.hhem = None
if os.environ.get('MOSS_HHEM') == '1':
try:
from transformers import AutoModelForSequenceClassification
self.hhem = AutoModelForSequenceClassification.from_pretrained('vectara/hallucination_evaluation_model', trust_remote_code=True)
except Exception as ex:
print(f'[webqa] HHEM unavailable: {type(ex).__name__}: {str(ex)[:120]}', flush=True)
def _sieve(self):
if not hasattr(self, '_sv'):
from .sieve import Sieve
sv = Sieve.__new__(Sieve)
sv.verify = self.verify
self._sv = sv
return self._sv
def answer_iter(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
if tau_v is None:
tau_v = TAU_V
t0 = time.time()
res = search(q, provider=provider)
t1 = time.time()
q_user = q
fixes = {}
if SPELL and res:
q, fixes = corpus_spelling(q, res)
yield {'stage': 'search', 'ms': round(1000 * (t1 - t0)), 'n': len(res), 'cached': t1 - t0 < 0.05, 'provider': provider or default_provider(), 'spelled': fixes or None}
cands = candidates(res, q)
if not cands:
yield {'stage': 'done', 'tier': 3, 'why': 'no results', 'ms_search': round(1000 * (t1 - t0)), 'ms_models': 0, 'results': res}
return
ta = time.time()
s1 = self.rank.predict([(q, f"{c['title']}. {c['sent']}") for c in cands], batch_size=32, show_progress_bar=False)
order = sorted(range(len(cands)), key=lambda i: -float(s1[i]))[:8]
tb = time.time()
yield {'stage': 'rank', 'ms': round(1000 * (tb - ta)), 'n': len(cands), 'top': [cands[i]['sent'][:90] for i in order[:3]]}
s2 = self.verify.predict([(q, f"{cands[i]['title']}. {cands[i]['sent']}") for i in order], batch_size=32, show_progress_bar=False)
pen = (lambda c: 2.5 if any((f in c['url'].lower() for f in SOCIAL)) else 0.0) if SOURCE_PENALTY else lambda c: 0.0
def quotable(c):
if not QUOTABLE:
return 0.0
t = c['sent']
return (0.3 if t[-1:] in '.!?' else 0.0) + (0.3 if len(t) <= 220 else 0.0) + (0.2 if t[:1].isupper() else 0.0) - (0.5 if '...' in t or '…' in t else 0.0)
ver = [j for j in range(len(order)) if float(s2[j]) >= tau_v]
best = max(ver, key=lambda j: float(s2[j]) - pen(cands[order[j]]) + quotable(cands[order[j]])) if ver else max(range(len(order)), key=lambda j: float(s2[j]))
c = cands[order[best]]
score2 = float(s2[best])
tc = time.time()
tier = 1 if score2 >= tau_v else 2 if score2 >= tau_lo else 3
yield {'stage': 'verify', 'ms': round(1000 * (tc - tb)), 'score': round(score2, 2), 'tier': tier}
retry = None
if FALLBACK and tier != 1:
rprov = RETRY_PROVIDER if RETRY_PROVIDER == 'serper' and os.environ.get('SERPER_API_KEY') else provider
for name, rq in retry_queries(q):
tr = time.time()
more = [x for x in candidates(search(rq, provider=rprov), q) if x['sent'] not in {cc['sent'] for cc in cands}]
if not more:
continue
r1 = self.rank.predict([(q, f"{x['title']}. {x['sent']}") for x in more], batch_size=32, show_progress_bar=False)
ro = sorted(range(len(more)), key=lambda i: -float(r1[i]))[:8]
r2 = self.verify.predict([(q, f"{more[i]['title']}. {more[i]['sent']}") for i in ro], batch_size=32, show_progress_bar=False)
rb = max(range(len(ro)), key=lambda j: float(r2[j]) - pen(more[ro[j]]) + quotable(more[ro[j]]))
rv = float(r2[rb])
yield {'stage': 'retry', 'ms': round(1000 * (time.time() - tr)), 'query': rq, 'name': name, 'score': round(rv, 2), 'n': len(more), 'taken': rv >= RETRY_TAU}
if rv >= RETRY_TAU:
c = more[ro[rb]]
score2 = rv
tier = 1
retry = name
res = res + search(rq, provider=rprov)
break
tc = time.time()
span = self.extract(q, [(f"{c['title'].split(' | ')[0].strip()}. {c['body']}", 'E1')], answer_type=None)
if span:
span['answer'] = re.sub('\\b(\\w+)\\1\\b', '\\1', span['answer']).strip()
span['answer'] = re.sub('\\b(\\w+(?:\\s\\w+)?)\\s+\\1\\b', '\\1', span['answer']).strip()
if not span and re.match('^(?:who|which)\\b', q.strip(), re.I):
head = re.split('\\s+[-|—–:]\\s+', c['title'])[0].strip()
if 2 <= len(head.split()) <= 5 and head[:1].isupper():
span = {'answer': head, 'score': 0.0, 'kind': 'title'}
spans = {}
for j, i in enumerate(order if os.environ.get('MOSS_CONSENSUS') == '1' else []):
cj = cands[i]
sp = self.extract(q, [(f"{cj['title'].split(' | ')[0].strip()}. {cj['body']}", 'E1')], answer_type=None)
if not sp:
continue
key = normalize(re.sub('\\b(\\w+)\\1\\b', '\\1', sp['answer']))
if not key or len(key) > 80:
continue
e = spans.setdefault(key, {'answer': sp['answer'], 'sources': set(), 'best_v': -99.0, 'cand': None})
e['best_v'] = max(e['best_v'], float(s2[j]))
e['cand'] = e['cand'] or cj
for key, e in spans.items():
e['sources'] = {r['href'] for r in res if key in normalize(r['title'] + ' ' + r['body'])}
cons = max(spans.values(), key=lambda e: (len(e['sources']), e['best_v'])) if spans else None
pkey = normalize(span['answer']) if span else ''
support = len({r.get('href') or r['body'] for r in res if pkey and pkey in normalize(r['title'] + ' ' + r['body'])}) if span else 0
if STRICT and tier == 1 and (support < 2):
tier = 2
verified_by = 'verifier' if tier == 1 else None
if AGREE and tier != 1 and span and (support >= AGREE) and (score2 >= 0.0):
tier = 1
verified_by = 'agreement'
sieve_ev = None
if SIEVE_RETRY and tier != 1 and re.match('^(?:which|who)\\b', q.strip(), re.I) and (not span or support <= 1):
try:
ts = time.time()
sv = self._sieve()
out = sv.run(q, provider=rprov if FALLBACK else provider, k_ent=8) or {}
ent = out.get('sieve')
ok = ent and out.get('of') and (out['covered'] >= max(2, out['of'] - 1)) and (out.get('runner_up') is None or out['covered'] > (out.get('runner_covered') or 0))
sieve_ev = {'stage': 'sieve', 'ms': round(1000 * (time.time() - ts)), 'entity': ent, 'covered': out.get('covered'), 'of': out.get('of'), 'runner': out.get('runner_up'), 'taken': bool(ok)}
if ok:
span = {'answer': ent, 'score': 0.0, 'kind': 'sieve'}
pkey = normalize(ent)
if out.get('sent'):
c = {'sent': out['sent'], 'title': out.get('title') or '', 'url': out.get('url') or '', 'body': out['sent']}
score2 = float(out.get('v') or -99.0)
support = len({r.get('href') or r['body'] for r in res if pkey in normalize(r['title'] + ' ' + r['body'])}) + 1
tier = 1 if score2 >= tau_v else 2
retry = 'sieve'
verified_by = 'verifier' if tier == 1 else None
except Exception as ex:
sieve_ev = {'stage': 'sieve', 'ms': 0, 'error': type(ex).__name__}
if sieve_ev:
yield sieve_ev
td = time.time()
yield {'stage': 'extract', 'ms': round(1000 * (td - tc)), 'span': span['answer'] if span else None, 'support': support, 'consensus': cons['answer'] if cons else None, 'consensus_support': len(cons['sources']) if cons else 0}
hh = None
if self.hhem is not None and span:
try:
hh = float(self.hhem.predict([(c['body'], f"The answer to the question '{q}' is {span['answer']}.")])[0])
except Exception:
hh = None
ld, ld_by = (None, None)
vmode = verbalize or VERBALIZE
linfo = {}
if span and tier == 1 and (vmode != 'none'):
if vmode in ('own', 'own-strict'):
ttl = c['title'].split(' | ')[0].split(' - ')[0].strip()
ld, ld_by = own_lead(q, span['answer'], c['sent'], ttl, natural=vmode == 'own', info=linfo, q_user=q_user, vscore=lambda t, _q=q, _t=ttl: float(self.verify.predict([(_q, f'{_t}. {t}')], batch_size=8, show_progress_bar=False)[0]))
if not ld:
ld, ld_by = (lead(q, span['answer']), 'template' if lead(q, span['answer']) else None)
te = time.time()
yield {'stage': 'check', 'ms': round(1000 * (te - td)), 'hhem': None if hh is None else round(hh, 3), 'lead_by': ld_by, **linfo}
yield {'stage': 'done', 'tier': tier, 'score2': round(score2, 2), 'top_rank': round(float(s1[order[0]]), 2), 'cited': c['sent'], 'title': c['title'], 'url': c['url'], 'span': span['answer'] if span else None, 'span_score': round(span['score'], 2) if span else None, 'hhem': None if hh is None else round(hh, 3), 'support': support, 'lead': ld, 'lead_by': ld_by, 'lead_info': linfo or None, 'quote_clean': quote_clean(q, c['sent'], span['answer'] if span else None), 'retry': retry, 'verified_by': verified_by, 'consensus': cons['answer'] if cons else None, 'consensus_support': len(cons['sources']) if cons else 0, 'consensus_cited': cons['cand']['sent'] if cons else None, 'consensus_title': cons['cand']['title'] if cons else None, 'consensus_url': cons['cand']['url'] if cons else None, 'consensus_v': round(cons['best_v'], 2) if cons else None, 'ms_search': round(1000 * (t1 - t0)), 'ms_models': round(1000 * (te - t1)), 'results': res, 'spelled': fixes or None, 'q': q_user}
def answer(self, q, tau_v=None, tau_lo=-4.0, provider=None, verbalize=None):
for ev in self.answer_iter(q, tau_v, tau_lo, provider, verbalize):
if ev['stage'] == 'done':
return {k: v for k, v in ev.items() if k != 'stage'}
|