File size: 1,833 Bytes
91c1aad
 
 
 
bce9423
91c1aad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bce9423
91c1aad
 
 
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
# handler.py
import json
from typing import List, Dict, Any
from transformers import pipeline

# ---- LOAD MODEL ON STARTUP ----
pipe = pipeline(
    "text-generation",
    model="Ephraimmm/PIDGIN_gemma-3",
    device_map="auto"
)


# ---- UTIL: convert OpenAI-like body into prompt ----
def build_prompt(messages: List[Dict[str, str]]) -> str:
    out = []
    for m in messages:
        role = m["role"]
        content = m["content"]
        if role == "system":
            out.append(f"<<SYS>> {content}\n")
        elif role == "user":
            out.append(f"User: {content}")
        elif role == "assistant":
            out.append(f"Assistant: {content}")
    out.append("Assistant:")
    return "\n".join(out)


# ---- MAIN HANDLER ENTRYPOINT ----
def handle(event, context=None):
    """AWS/SageMaker/HF style single entry."""
    if isinstance(event, str):  # if raw body
        event = json.loads(event)

    # Expect OpenAI style body
    messages = event["messages"]
    max_tokens = event.get("max_tokens", 256)
    temperature = event.get("temperature", 0.7)
    top_p = event.get("top_p", 0.95)

    prompt = build_prompt(messages)

    out = pipe(
        prompt,
        max_new_tokens=max_tokens,
        do_sample=True,
        temperature=temperature,
        top_p=top_p,
        eos_token_id=pipe.tokenizer.eos_token_id,
    )[0]["generated_text"]

    # extract only the assistant continuation
    completion = out.replace(prompt, "").strip()

    # ---- RETURN IN OPENAI CHAT FORMAT ----
    resp = {
        "id": "chatcmpl-local-1",
        "object": "chat.completion",
        "choices": [{
            "index": 0,
            "finish_reason": "stop",
            "message": {
                "role": "assistant",
                "content": completion
            }
        }],
    }
    return resp