Text Generation
Transformers
English
qwen2
code-generation
python
fine-tuning
Qwen
tools
agent-framework
multi-agent
conversational
Eval Results (legacy)
Instructions to use my-ai-stack/Stack-2-9-finetuned with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use my-ai-stack/Stack-2-9-finetuned with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="my-ai-stack/Stack-2-9-finetuned") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("my-ai-stack/Stack-2-9-finetuned") model = AutoModelForCausalLM.from_pretrained("my-ai-stack/Stack-2-9-finetuned") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=40) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps
- vLLM
How to use my-ai-stack/Stack-2-9-finetuned with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "my-ai-stack/Stack-2-9-finetuned" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "my-ai-stack/Stack-2-9-finetuned", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/my-ai-stack/Stack-2-9-finetuned
- SGLang
How to use my-ai-stack/Stack-2-9-finetuned 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 "my-ai-stack/Stack-2-9-finetuned" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "my-ai-stack/Stack-2-9-finetuned", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "my-ai-stack/Stack-2-9-finetuned" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "my-ai-stack/Stack-2-9-finetuned", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use my-ai-stack/Stack-2-9-finetuned with Docker Model Runner:
docker model run hf.co/my-ai-stack/Stack-2-9-finetuned
File size: 9,119 Bytes
8f05ad1 | 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 | """
Feedback Collection System
Collects user feedback for continuous improvement.
"""
from typing import Dict, List, Optional, Any
from datetime import datetime
import json
from pathlib import Path
import uuid
class FeedbackEntry:
"""Represents a single feedback entry."""
def __init__(
self,
feedback_type: str,
user_id: Optional[str],
message: str,
response: str,
rating: Optional[int] = None,
metadata: Optional[Dict[str, Any]] = None,
):
self.id = str(uuid.uuid4())
self.feedback_type = feedback_type # "thumbs_up", "thumbs_down", "correction", "suggestion"
self.user_id = user_id
self.message = message
self.response = response
self.rating = rating # 1-5 scale
self.metadata = metadata or {}
self.created_at = datetime.now()
self.processed = False
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"id": self.id,
"feedback_type": self.feedback_type,
"user_id": self.user_id,
"message": self.message,
"response": self.response,
"rating": self.rating,
"metadata": self.metadata,
"created_at": self.created_at.isoformat(),
"processed": self.processed,
}
class FeedbackCollector:
"""Collects and manages user feedback."""
def __init__(
self,
storage_path: str = "data/feedback",
auto_save: bool = True,
):
"""
Initialize the feedback collector.
Args:
storage_path: Path to store feedback data
auto_save: Automatically save feedback to disk
"""
self.storage_path = Path(storage_path)
self.auto_save = auto_save
self.feedback_list: List[FeedbackEntry] = []
# Create storage directory if it doesn't exist
if auto_save:
self.storage_path.mkdir(parents=True, exist_ok=True)
def add_feedback(
self,
feedback_type: str,
message: str,
response: str,
user_id: Optional[str] = None,
rating: Optional[int] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> str:
"""
Add a feedback entry.
Args:
feedback_type: Type of feedback
message: User's message
response: AI's response
user_id: Optional user ID
rating: Optional rating (1-5)
metadata: Additional metadata
Returns:
Feedback ID
"""
entry = FeedbackEntry(
feedback_type=feedback_type,
user_id=user_id,
message=message,
response=response,
rating=rating,
metadata=metadata,
)
self.feedback_list.append(entry)
if self.auto_save:
self._save_feedback(entry)
return entry.id
def add_thumbs_up(
self,
message: str,
response: str,
user_id: Optional[str] = None,
) -> str:
"""Add positive feedback."""
return self.add_feedback(
feedback_type="thumbs_up",
message=message,
response=response,
user_id=user_id,
rating=5,
)
def add_thumbs_down(
self,
message: str,
response: str,
user_id: Optional[str] = None,
reason: Optional[str] = None,
) -> str:
"""Add negative feedback."""
return self.add_feedback(
feedback_type="thumbs_down",
message=message,
response=response,
user_id=user_id,
rating=1,
metadata={"reason": reason} if reason else {},
)
def add_correction(
self,
message: str,
original_response: str,
corrected_response: str,
user_id: Optional[str] = None,
) -> str:
"""Add a correction."""
return self.add_feedback(
feedback_type="correction",
message=message,
response=original_response,
user_id=user_id,
metadata={"corrected_response": corrected_response},
)
def add_suggestion(
self,
message: str,
response: str,
suggestion: str,
user_id: Optional[str] = None,
) -> str:
"""Add a suggestion."""
return self.add_feedback(
feedback_type="suggestion",
message=message,
response=response,
user_id=user_id,
metadata={"suggestion": suggestion},
)
def get_feedback(
self,
feedback_id: str,
) -> Optional[FeedbackEntry]:
"""Get feedback by ID."""
for entry in self.feedback_list:
if entry.id == feedback_id:
return entry
return None
def get_all_feedback(
self,
feedback_type: Optional[str] = None,
unprocessed_only: bool = False,
) -> List[FeedbackEntry]:
"""Get all feedback entries."""
results = self.feedback_list
if feedback_type:
results = [f for f in results if f.feedback_type == feedback_type]
if unprocessed_only:
results = [f for f in results if not f.processed]
return results
def mark_processed(self, feedback_id: str) -> bool:
"""Mark feedback as processed."""
entry = self.get_feedback(feedback_id)
if entry:
entry.processed = True
return True
return False
def get_statistics(self) -> Dict[str, Any]:
"""Get feedback statistics."""
total = len(self.feedback_list)
if total == 0:
return {
"total": 0,
"by_type": {},
"average_rating": 0,
"processed_count": 0,
}
by_type: Dict[str, int] = {}
ratings = []
for entry in self.feedback_list:
by_type[entry.feedback_type] = by_type.get(entry.feedback_type, 0) + 1
if entry.rating is not None:
ratings.append(entry.rating)
avg_rating = sum(ratings) / len(ratings) if ratings else 0
processed = sum(1 for e in self.feedback_list if e.processed)
return {
"total": total,
"by_type": by_type,
"average_rating": avg_rating,
"processed_count": processed,
"unprocessed_count": total - processed,
}
def get_corrections_for_finetuning(self) -> List[Dict[str, Any]]:
"""Get corrections formatted for fine-tuning."""
corrections = self.get_all_feedback(feedback_type="correction")
return [
{
"instruction": entry.message,
"output": entry.metadata.get("corrected_response", entry.response),
}
for entry in corrections
]
def export_finetuning_data(
self,
filepath: str,
) -> None:
"""Export feedback as fine-tuning data."""
corrections = self.get_corrections_for_finetuning()
Path(filepath).write_text(json.dumps(corrections, indent=2))
def _save_feedback(self, entry: FeedbackEntry) -> None:
"""Save feedback to file."""
filepath = self.storage_path / f"{entry.id}.json"
filepath.write_text(json.dumps(entry.to_dict(), indent=2))
def load_feedback(self) -> None:
"""Load feedback from storage directory."""
if not self.storage_path.exists():
return
for filepath in self.storage_path.glob("*.json"):
try:
data = json.loads(filepath.read_text())
entry = FeedbackEntry(
feedback_type=data["feedback_type"],
user_id=data.get("user_id"),
message=data["message"],
response=data["response"],
rating=data.get("rating"),
metadata=data.get("metadata", {}),
)
entry.id = data["id"]
entry.processed = data.get("processed", False)
entry.created_at = datetime.fromisoformat(data["created_at"])
self.feedback_list.append(entry)
except Exception as e:
print(f"Error loading feedback from {filepath}: {e}")
def clear_old_feedback(self, days: int = 30) -> int:
"""Clear feedback older than specified days."""
cutoff = datetime.now() - timedelta(days=days)
original_count = len(self.feedback_list)
self.feedback_list = [
f for f in self.feedback_list
if f.created_at > cutoff
]
return original_count - len(self.feedback_list)
def __repr__(self) -> str:
stats = self.get_statistics()
return f"FeedbackCollector(total={stats['total']}, unprocessed={stats['unprocessed_count']})"
# Add missing import
from datetime import timedelta |