初始化项目,由ModelHub XC社区提供模型

Model: QuantaSparkLabs/NYXIS-Pro
Source: Original Platform
This commit is contained in:
ModelHub XC
2026-06-30 22:08:44 +08:00
commit d704951188
30 changed files with 27343 additions and 0 deletions

38
.gitattributes vendored Normal file
View File

@@ -0,0 +1,38 @@
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
logoname.png filter=lfs diff=lfs merge=lfs -text
preview[[:space:]]imgagee.png filter=lfs diff=lfs merge=lfs -text
tokenizer.json filter=lfs diff=lfs merge=lfs -text

126
README.md Normal file
View File

@@ -0,0 +1,126 @@
---
license: apache-2.0
language:
- en
tags:
- rag
- retrieval-augmented-generation
- knowledge-base
- emotion-detection
- dual-stage-retrieval
- coding
- math
- science
- history
- nyxis
- quantasparklabs
pipeline_tag: text-generation
base_model:
- QuantaSparkLabs/NYXIS-1.1B
library_name: transformers
datasets:
- QuantaSparkLabs/NYXIS-AEGIS-Knowledge
---
<p align="center">
<img src="https://huggingface.co/QuantaSparkLabs/NYXIS-Pro/resolve/main/preview imgagee.png"
alt="NYXIS Logo"
width="160"
height="160"
style="border-radius: 50%; object-fit: cover;">
</p>
<p align="center">
<img src="https://huggingface.co/QuantaSparkLabs/NYXIS-Pro/resolve/main/logoname.png"
alt="NYXIS Name"
width="700"
style="border-radius: 18px;">
</p>
# NYXIS-PRO 🛡️
<p align="center">
<a href="https://huggingface.co/QuantaSparkLabs/NYXIS-1.1B"><img src="https://img.shields.io/badge/Base-NYXIS--1.1B-purple" alt="Base Model"></a>
<a href="https://huggingface.co/QuantaSparkLabs/NYXIS-AEGIS-KB"><img src="https://img.shields.io/badge/Knowledge-AEGIS-blue" alt="AEGIS KB"></a>
<a href="#"><img src="https://img.shields.io/badge/Retrieval-Dual%20Stage-green" alt="Dual Stage"></a>
<a href="#"><img src="https://img.shields.io/badge/Emotion-1--10%20Scale-orange" alt="Emotion Engine"></a>
<a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-yellow" alt="License"></a>
</p>
**The all-in-one reasoning engine with the AEGIS knowledge shield.**
NYXIS-PRO combines the NYXIS1.1B base model with a curated 5,000+ chunk knowledge base covering coding, math, science, history, and common knowledge. A dualstage retriever grounds every factual answer in verified data — **zero hallucination.**
## 🧠 What Makes It Different
| Feature | Description |
|---------|-------------|
| **AEGIS Knowledge Base** | 5,426 curated Wikipedia, Trivia QA, and ArXiv chunks |
| **DualStage Retriever** | Dense recall (bgesmall) + Crossencoder rerank (msmarcoMiniLM) |
| **Emotion Engine** | Detects user emotion on a 110 scale and matches tone |
| **4Tier Knowledge Cascade** | AEGIS → External Search → Model Brain → Honest Fallback |
| **Zero Hallucination** | If it doesn't know, it says so — no fabrication |
## 🚀 Quick Start
```python
from huggingface_hub import snapshot_download
import sys
model_dir = snapshot_download("QuantaSparkLabs/NYXIS-Pro")
sys.path.insert(0, model_dir)
from pipeline import NYXISPro
nyxis = NYXISPro(model_dir)
result = nyxis.generate("What is a binary search tree?")
print(result["response"])
```
> **Requirements:** `sentence-transformers`, `faiss-cpu`, `transformers`, `accelerate`, `bitsandbytes`
> **VRAM:** ~2.1GB (4bit) | **Hardware:** T4 or better
## 📦 What's Inside
| Component | Model | Purpose |
|-----------|-------|---------|
| **Base LLM** | NYXIS1.1B) | Text generation |
| **Dense Retriever** | bgesmallenv1.5 | Initial candidate recall |
| **CrossEncoder** | msmarcoMiniLML6v2 | Precision reranking |
| **FAISS Index** | 5,426 chunks | Knowledge storage |
| **Emotion Engine** | Custom keywordbased | Tone matching |
## 🤖 Emotion Intelligence
NYXIS-PRO detects your emotional state from text and adjusts its personality:
| Level | Emotion | Response Style |
|:---:|---------|----------------|
| 13 | Sad / Angry | Gentle, supportive, empathetic |
| 46 | Neutral | Balanced, warm, helpful |
| 79 | Happy / Excited | Energetic, playful |
| 10 | Overjoyed | Celebratory |
## 🛡️ Knowledge Cascade
When you ask a factual question, NYXIS-PRO follows a strict 4tier protocol:
1. **AEGIS** — Searches internal verified knowledge base
2. **External Search** — Falls back to web search (userprovided API)
3. **Model Brain** — Uses training data with honesty guard
4. **Honest Fallback** — Admits "I don't have enough information"
It **never fabricates** an answer.
## Limitations
- Knowledge base covers ~5,400 chunks — not infinite
- Emotion detection is keywordbased, not deep sentiment analysis
- External search requires userprovided API function
- Englishonly, 1.5B model size limits complex reasoning
## License
Apache2.0
---
*Built with 🛡️ by QuantaSparkLabs*

23327
aegis_chunks.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
{
"embedding_dimension": 384,
"pooling_mode": "cls",
"include_prompt": true
}

3074
aegis_embedder/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,35 @@
{
"add_cross_attention": false,
"architectures": [
"BertModel"
],
"attention_probs_dropout_prob": 0.1,
"bos_token_id": null,
"classifier_dropout": null,
"dtype": "float32",
"eos_token_id": null,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 384,
"id2label": {
"0": "LABEL_0"
},
"initializer_range": 0.02,
"intermediate_size": 1536,
"is_decoder": false,
"label2id": {
"LABEL_0": 0
},
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"pad_token_id": 0,
"position_embedding_type": "absolute",
"tie_word_embeddings": true,
"transformers_version": "5.0.0",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 30522
}

View File

@@ -0,0 +1,14 @@
{
"__version__": {
"pytorch": "2.10.0+cu128",
"sentence_transformers": "5.4.1",
"transformers": "5.0.0"
},
"default_prompt_name": null,
"model_type": "SentenceTransformer",
"prompts": {
"document": "",
"query": ""
},
"similarity_fn_name": "cosine"
}

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:ba3eeb8008783b2a8e9aeb9415a511d9aa3bdfec2dbbdfe8e4bbf5bdde283c6b
size 133462104

View File

@@ -0,0 +1,20 @@
[
{
"idx": 0,
"name": "0",
"path": "",
"type": "sentence_transformers.base.modules.transformer.Transformer"
},
{
"idx": 1,
"name": "1",
"path": "1_Pooling",
"type": "sentence_transformers.sentence_transformer.modules.pooling.Pooling"
},
{
"idx": 2,
"name": "2",
"path": "2_Normalize",
"type": "sentence_transformers.sentence_transformer.modules.normalize.Normalize"
}
]

View File

@@ -0,0 +1,10 @@
{
"transformer_task": "feature-extraction",
"modality_config": {
"text": {
"method": "forward",
"method_output_name": "last_hidden_state"
}
},
"module_output_name": "token_embeddings"
}

BIN
aegis_embedder/tokenizer.json (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,17 @@
{
"backend": "tokenizers",
"clean_up_tokenization_spaces": true,
"cls_token": "[CLS]",
"do_basic_tokenize": true,
"do_lower_case": true,
"is_local": false,
"mask_token": "[MASK]",
"model_max_length": 512,
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"strip_accents": null,
"tokenize_chinese_chars": true,
"tokenizer_class": "BertTokenizer",
"unk_token": "[UNK]"
}

3
aegis_index.faiss Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:dcf18b088fb09d53873e9e069dca8ad8634839370a4854d7c6be5050cc1fde86
size 8334381

147
aegis_reranker/README.md Normal file
View File

@@ -0,0 +1,147 @@
---
tags:
- sentence-transformers
- cross-encoder
- reranker
base_model: cross-encoder/ms-marco-MiniLM-L6-v2
pipeline_tag: text-ranking
library_name: sentence-transformers
---
# CrossEncoder based on cross-encoder/ms-marco-MiniLM-L6-v2
This is a [Cross Encoder](https://www.sbert.net/docs/cross_encoder/usage/usage.html) model finetuned from [cross-encoder/ms-marco-MiniLM-L6-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L6-v2) using the [sentence-transformers](https://www.SBERT.net) library. It computes scores for pairs of texts, which can be used for text reranking and semantic search.
## Model Details
### Model Description
- **Model Type:** Cross Encoder
- **Base model:** [cross-encoder/ms-marco-MiniLM-L6-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L6-v2) <!-- at revision c5ee24cb16019beea0893ab7796b1df96625c6b8 -->
- **Maximum Sequence Length:** 512 tokens
- **Number of Output Labels:** 1 label
- **Supported Modality:** Text
<!-- - **Training Dataset:** Unknown -->
<!-- - **Language:** Unknown -->
<!-- - **License:** Unknown -->
### Model Sources
- **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
- **Documentation:** [Cross Encoder Documentation](https://www.sbert.net/docs/cross_encoder/usage/usage.html)
- **Repository:** [Sentence Transformers on GitHub](https://github.com/huggingface/sentence-transformers)
- **Hugging Face:** [Cross Encoders on Hugging Face](https://huggingface.co/models?library=sentence-transformers&other=cross-encoder)
### Full Model Architecture
```
CrossEncoder(
(0): Transformer({'transformer_task': 'sequence-classification', 'modality_config': {'text': {'method': 'forward', 'method_output_name': 'logits'}}, 'module_output_name': 'scores', 'architecture': 'BertForSequenceClassification'})
)
```
## Usage
### Direct Usage (Sentence Transformers)
First install the Sentence Transformers library:
```bash
pip install -U sentence-transformers
```
Then you can load this model and run inference.
```python
from sentence_transformers import CrossEncoder
# Download from the 🤗 Hub
model = CrossEncoder("cross_encoder_model_id")
# Get scores for pairs of inputs
pairs = [
['How many calories in an egg', 'There are on average between 55 and 80 calories in an egg depending on its size.'],
['How many calories in an egg', 'Egg whites are very low in calories, have no fat, no cholesterol, and are loaded with protein.'],
['How many calories in an egg', 'Most of the calories in an egg come from the yellow yolk in the center.'],
]
scores = model.predict(pairs)
print(scores)
# [ 9.9541 -2.0108 0.9186]
# Or rank different texts based on similarity to a single text
ranks = model.rank(
'How many calories in an egg',
[
'There are on average between 55 and 80 calories in an egg depending on its size.',
'Egg whites are very low in calories, have no fat, no cholesterol, and are loaded with protein.',
'Most of the calories in an egg come from the yellow yolk in the center.',
]
)
# [{'corpus_id': ..., 'score': ...}, {'corpus_id': ..., 'score': ...}, ...]
```
<!--
### Direct Usage (Transformers)
<details><summary>Click to see the direct usage in Transformers</summary>
</details>
-->
<!--
### Downstream Usage (Sentence Transformers)
You can finetune this model on your own dataset.
<details><summary>Click to expand</summary>
</details>
-->
<!--
### Out-of-Scope Use
*List how the model may foreseeably be misused and address what users ought not to do with the model.*
-->
<!--
## Bias, Risks and Limitations
*What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
-->
<!--
### Recommendations
*What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
-->
## Training Details
### Framework Versions
- Python: 3.12.13
- Sentence Transformers: 5.4.1
- Transformers: 5.0.0
- PyTorch: 2.10.0+cu128
- Accelerate: 1.13.0
- Datasets: 4.0.0
- Tokenizers: 0.22.2
## Citation
### BibTeX
<!--
## Glossary
*Clearly define terms in order to be accessible across audiences.*
-->
<!--
## Model Card Authors
*Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
-->
<!--
## Model Card Contact
*Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
-->

View File

@@ -0,0 +1,36 @@
{
"add_cross_attention": false,
"architectures": [
"BertForSequenceClassification"
],
"attention_probs_dropout_prob": 0.1,
"bos_token_id": null,
"classifier_dropout": null,
"dtype": "float32",
"eos_token_id": null,
"gradient_checkpointing": false,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 384,
"id2label": {
"0": "LABEL_0"
},
"initializer_range": 0.02,
"intermediate_size": 1536,
"is_decoder": false,
"label2id": {
"LABEL_0": 0
},
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 6,
"pad_token_id": 0,
"position_embedding_type": "absolute",
"tie_word_embeddings": true,
"transformers_version": "5.0.0",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 30522
}

View File

@@ -0,0 +1,11 @@
{
"__version__": {
"pytorch": "2.10.0+cu128",
"sentence_transformers": "5.4.1",
"transformers": "5.0.0"
},
"activation_fn": "torch.nn.modules.linear.Identity",
"default_prompt_name": null,
"model_type": "CrossEncoder",
"prompts": {}
}

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5d5a1f2650eeb40eea5f06ddf0802b0ace0f102a28bddaa3a2cfbe65d54459ba
size 90866404

View File

@@ -0,0 +1,8 @@
[
{
"idx": 0,
"name": "0",
"path": "",
"type": "sentence_transformers.base.modules.transformer.Transformer"
}
]

View File

@@ -0,0 +1,10 @@
{
"transformer_task": "sequence-classification",
"modality_config": {
"text": {
"method": "forward",
"method_output_name": "logits"
}
},
"module_output_name": "scores"
}

BIN
aegis_reranker/tokenizer.json (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -0,0 +1,18 @@
{
"backend": "tokenizers",
"clean_up_tokenization_spaces": true,
"cls_token": "[CLS]",
"do_basic_tokenize": true,
"do_lower_case": true,
"is_local": false,
"mask_token": "[MASK]",
"model_max_length": 512,
"model_specific_special_tokens": {},
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"strip_accents": null,
"tokenize_chinese_chars": true,
"tokenizer_class": "BertTokenizer",
"unk_token": "[UNK]"
}

54
chat_template.jinja Normal file
View File

@@ -0,0 +1,54 @@
{%- if tools %}
{{- '<|im_start|>system\n' }}
{%- if messages[0]['role'] == 'system' %}
{{- messages[0]['content'] }}
{%- else %}
{{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}
{%- endif %}
{{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
{%- else %}
{%- if messages[0]['role'] == 'system' %}
{{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
{%- else %}
{{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- for message in messages %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{{- '<|im_start|>' + message.role }}
{%- if message.content %}
{{- '\n' + message.content }}
{%- endif %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '\n<tool_call>\n{"name": "' }}
{{- tool_call.name }}
{{- '", "arguments": ' }}
{{- tool_call.arguments | tojson }}
{{- '}\n</tool_call>' }}
{%- endfor %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- message.content }}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- endif %}

62
config.json Normal file
View File

@@ -0,0 +1,62 @@
{
"architectures": [
"Qwen2ForCausalLM"
],
"attention_dropout": 0.0,
"bos_token_id": null,
"torch_dtype": "float16",
"eos_token_id": 151645,
"hidden_act": "silu",
"hidden_size": 1536,
"initializer_range": 0.02,
"intermediate_size": 8960,
"layer_types": [
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention"
],
"max_position_embeddings": 32768,
"max_window_layers": 21,
"model_type": "qwen2",
"num_attention_heads": 12,
"num_hidden_layers": 28,
"num_key_value_heads": 2,
"pad_token_id": 151665,
"rms_norm_eps": 1e-06,
"rope_parameters": {
"rope_theta": 1000000.0,
"rope_type": "default"
},
"sliding_window": null,
"tie_word_embeddings": true,
"unsloth_fixed": true,
"unsloth_version": "2026.5.2",
"use_cache": false,
"use_sliding_window": false,
"vocab_size": 151936
}

8
generation_config.json Normal file
View File

@@ -0,0 +1,8 @@
{
"max_new_tokens": 512,
"temperature": 0.7,
"do_sample": true,
"top_p": 0.95,
"pad_token_id": 151643,
"eos_token_id": 151645
}

3
logoname.png Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:512ce2e088c1c4d86622bd667d6a842e37fbd0bf847f410242bce87445f64876
size 605773

3
model.safetensors Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1faa857d8a8c6e1c59fe124a258799cd1de4cc285b67f8112835ba5156b1e1b9
size 3087467144

94
pipeline.py Normal file
View File

@@ -0,0 +1,94 @@
import faiss, numpy as np, torch, os, re
from sentence_transformers import SentenceTransformer, CrossEncoder
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
class NYXISPro:
def __init__(self, model_dir="."):
self.embedder = SentenceTransformer(f"{model_dir}/aegis_embedder")
self.reranker = CrossEncoder(f"{model_dir}/aegis_reranker")
self.index = faiss.read_index(f"{model_dir}/aegis_index.faiss")
with open(f"{model_dir}/aegis_chunks.txt", "r") as f:
self.chunks = [c.strip() for c in f.read().split("<|CHUNK_END|>") if c.strip()]
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
self.model = AutoModelForCausalLM.from_pretrained(model_dir,
quantization_config=bnb, device_map="auto", trust_remote_code=True)
self.identity = "You are NYXIS, a sharp, warm, and endlessly curious mind. You speak like a clever friend — casual, direct, and human. You notice how people feel and match their energy."
self.last_emotion = 5
def detect_emotion(self, text):
t = text.lower()
joy = sum(1 for w in ["happy","excited","great","awesome","love","wonderful","joy","thrilled","good","nice"] if w in t)
sadness = sum(1 for w in ["sad","depressed","upset","crying","lonely","hurt","broken","bad","awful"] if w in t)
anger = sum(1 for w in ["angry","furious","mad","rage","annoyed","frustrated","pissed","stupid","hate"] if w in t)
if joy: return min(10, self.last_emotion + joy)
if sadness: return max(1, self.last_emotion - sadness)
if anger: return max(1, self.last_emotion - anger)
return self.last_emotion
def rag_lookup(self, query, top_k=5):
q_emb = self.embedder.encode([query], normalize_embeddings=True).astype('float32')
_, indices = self.index.search(q_emb, 20)
texts = [self.chunks[idx] for idx in indices[0] if idx < len(self.chunks)]
if not texts: return None
pairs = [(query, t[:500]) for t in texts]
scores = self.reranker.predict(pairs)
ranked = sorted(zip(scores, texts), reverse=True)[:top_k]
results = [t[:600] for s, t in ranked if s > -4.0]
return "\n\n".join(results) if results else None
def _generate(self, system, user, max_tokens=256):
prompt = f"<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
with torch.no_grad():
outputs = self.model.generate(**inputs, max_new_tokens=max_tokens, temperature=0.8,
do_sample=True, top_p=0.92, repetition_penalty=1.1,
pad_token_id=self.tokenizer.eos_token_id,
eos_token_id=self.tokenizer.encode("<|im_end|>", add_special_tokens=False)[0])
raw = self.tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True).strip()
raw = re.sub(r'\n*assistant\s*$', '', raw, flags=re.IGNORECASE).strip()
return raw
def generate(self, user_message, external_search_fn=None):
self.last_emotion = self.detect_emotion(user_message)
msg = user_message.lower().strip()
casual_starts = ["hi","hey","hello","yo","sup","good morning","good evening","how are you","what's up","good job","thanks","bye","okay","huh"]
casual_patterns = ["good job","well done","nice one","thank","lol","haha","bro","dude","mate","nigga","chill","relax","talk","chat","joke","story","what do you think","opinion","favorite","you stupid","you dumb","be free","normal","boring","lifeless","your name","who are you","what are you","tell me about yourself","how old are you","what is your name","who made you"]
is_casual = any(msg.startswith(s) for s in casual_starts) or any(p in msg for p in casual_patterns)
factual_starts = ["what","who","when","where","why","how","explain","define","list","compare","describe","find","search","calculate","solve"]
math_patterns = re.search(r'\d+[\+\-\*\/\=]\d+', msg)
is_factual = any(msg.startswith(s) for s in factual_starts) or bool(math_patterns) or len(msg) > 50
if is_casual and not is_factual:
system = f"{self.identity}\nThe user's vibe is {self.last_emotion}/10. Match it.\nYou're having a casual conversation. Be warm, brief, and real."
response = self._generate(system, user_message)
return {"response": response, "emotion_level": self.last_emotion, "knowledge_source": "chat"}
if is_factual:
aegis = self.rag_lookup(user_message)
if aegis:
system = f"{self.identity}\nVibe: {self.last_emotion}/10.\nUse ONLY this verified context to answer:\n\n{aegis}"
response = self._generate(system, user_message)
return {"response": response, "emotion_level": self.last_emotion, "knowledge_source": "AEGIS"}
if external_search_fn:
try:
ext = external_search_fn(user_message)
if ext and len(ext) > 50:
system = f"{self.identity}\nVibe: {self.last_emotion}/10.\nUse this web-sourced context:\n\n{ext}"
response = self._generate(system, user_message)
return {"response": response, "emotion_level": self.last_emotion, "knowledge_source": "external"}
except: pass
system = f"{self.identity}\nVibe: {self.last_emotion}/10.\nAEGIS and web failed. Answer from your own knowledge IF confident.\nIf you don't truly know, say exactly: 'I'd need to look that up.'"
response = self._generate(system, user_message)
source = "model" if "look that up" not in response.lower() else "none"
return {"response": response, "emotion_level": self.last_emotion, "knowledge_source": source}
aegis = self.rag_lookup(user_message)
if aegis:
system = f"{self.identity}\nVibe: {self.last_emotion}/10.\nUse this relevant context if helpful, but stay conversational:\n\n{aegis}"
else:
system = f"{self.identity}\nVibe: {self.last_emotion}/10.\nStay conversational."
response = self._generate(system, user_message)
return {"response": response, "emotion_level": self.last_emotion, "knowledge_source": "hybrid"}

3
preview imgagee.png Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:57ffe1cd65b4c235d413c9cb2cbaf7d71c092f8a74b9554f28c44c2cd3206094
size 967975

3
tokenizer.json Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:bd5948af71b4f56cf697f7580814c7ce8b80595ef985544efcacf716126a2e31
size 11422356

202
tokenizer_config.json Normal file
View File

@@ -0,0 +1,202 @@
{
"add_prefix_space": false,
"backend": "tokenizers",
"bos_token": null,
"clean_up_tokenization_spaces": false,
"eos_token": "<|im_end|>",
"errors": "replace",
"is_local": false,
"model_max_length": 32768,
"pad_token": "<|PAD_TOKEN|>",
"padding_side": "left",
"split_special_tokens": false,
"tokenizer_class": "Qwen2Tokenizer",
"unk_token": null,
"added_tokens_decoder": {
"151643": {
"content": "<|endoftext|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151644": {
"content": "<|im_start|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151645": {
"content": "<|im_end|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151646": {
"content": "<|object_ref_start|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151647": {
"content": "<|object_ref_end|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151648": {
"content": "<|box_start|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151649": {
"content": "<|box_end|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151650": {
"content": "<|quad_start|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151651": {
"content": "<|quad_end|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151652": {
"content": "<|vision_start|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151653": {
"content": "<|vision_end|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151654": {
"content": "<|vision_pad|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151655": {
"content": "<|image_pad|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151656": {
"content": "<|video_pad|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
},
"151657": {
"content": "<tool_call>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151658": {
"content": "</tool_call>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151659": {
"content": "<|fim_prefix|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151660": {
"content": "<|fim_middle|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151661": {
"content": "<|fim_suffix|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151662": {
"content": "<|fim_pad|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151663": {
"content": "<|repo_name|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151664": {
"content": "<|file_sep|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": false
},
"151665": {
"content": "<|PAD_TOKEN|>",
"single_word": false,
"lstrip": false,
"rstrip": false,
"normalized": false,
"special": true
}
},
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n"
}