|
| 1 | +# Function |
| 2 | +import logging |
| 3 | +from llama_cpp import Llama |
| 4 | +import json |
| 5 | + |
| 6 | +def new(): |
| 7 | + """ New is the only method that must be implemented by a Function. |
| 8 | + The instance returned can be of any name. |
| 9 | + """ |
| 10 | + return Function() |
| 11 | + |
| 12 | +class Function: |
| 13 | + def __init__(self): |
| 14 | + """ The init method is an optional method where initialization can be |
| 15 | + performed. See the start method for a startup hook which includes |
| 16 | + configuration. |
| 17 | + """ |
| 18 | + |
| 19 | + async def sender(self,send,obj): |
| 20 | + # echo the obj to the calling client |
| 21 | + await send({ |
| 22 | + 'type': 'http.response.start', |
| 23 | + 'status': 200, |
| 24 | + 'headers': [ |
| 25 | + [b'content-type', b'text/plain'], |
| 26 | + ], |
| 27 | + }) |
| 28 | + await send({ |
| 29 | + 'type': 'http.response.body', |
| 30 | + 'body': obj.encode(), |
| 31 | + }) |
| 32 | + |
| 33 | + async def handle(self, scope, receive, send): |
| 34 | + """ |
| 35 | + accepts data in form of JSON with the key "input" which should |
| 36 | + contain the input string for the LLM |
| 37 | + { |
| 38 | + "input": "this is passed to the LLM" |
| 39 | + } |
| 40 | + ex: curl localhost:8080 -d '{"input":"The largest mountain in the world is"}' |
| 41 | + """ |
| 42 | + if scope["method"] == "GET": |
| 43 | + await self.sender(send,"OK") |
| 44 | + return |
| 45 | + |
| 46 | + input = "" |
| 47 | + |
| 48 | + # fetch all of the body from request |
| 49 | + body = b'' |
| 50 | + more_body = True |
| 51 | + while more_body: |
| 52 | + message = await receive() |
| 53 | + body += message.get('body', b'') |
| 54 | + more_body = message.get('more_body', False) |
| 55 | + # decode json |
| 56 | + try: |
| 57 | + data = json.loads(body.decode('utf-8')) |
| 58 | + input = data['input'] |
| 59 | + except json.JSONDecodeError: |
| 60 | + ret = "Invalid Json" |
| 61 | + except KeyError: |
| 62 | + ret = "invalid key, expected 'input'" |
| 63 | + |
| 64 | + if input == "": |
| 65 | + self.sender(send,"OK") |
| 66 | + |
| 67 | + # Pull model from Hugging Face Hub |
| 68 | + llm = Llama.from_pretrained( |
| 69 | + repo_id="ibm-granite/granite-3b-code-base-2k-GGUF", |
| 70 | + filename="granite-3b-code-base.Q4_K_M.gguf", |
| 71 | + n_ctx=1024, |
| 72 | + ) |
| 73 | + |
| 74 | + ## Use a local image instead |
| 75 | + #llm = Llama ( |
| 76 | + # model_path = "/granite-7b-lab-Q4_K_M.gguf/snapshots/sha256-6adeaad8c048b35ea54562c55e454cc32c63118a32c7b8152cf706b290611487/granite-7b-lab-Q4_K_M.gguf", |
| 77 | + # n_ctx = 1024, |
| 78 | + # ) |
| 79 | + |
| 80 | + output = llm( |
| 81 | + input, |
| 82 | + max_tokens=32, |
| 83 | + ## Stop generating just before "Q:"; doesnt work well with small models |
| 84 | + ## some models are more tuned to the Q: ... A: ... "chat" |
| 85 | + ## You would literally type that in your input as: f' Q: {input}. A:' |
| 86 | + #stop=["Q:","\n"], |
| 87 | + echo=False, |
| 88 | + ) |
| 89 | + #logging.info("------------") |
| 90 | + #logging.info(output['choices'][0]['text']) |
| 91 | + await self.sender(send,output['choices'][0]['text']) |
| 92 | + |
| 93 | + def start(self, cfg): |
| 94 | + """ start is an optional method which is called when a new Function |
| 95 | + instance is started, such as when scaling up or during an update. |
| 96 | + Provided is a dictionary containing all environmental configuration. |
| 97 | + Args: |
| 98 | + cfg (Dict[str, str]): A dictionary containing environmental config. |
| 99 | + In most cases this will be a copy of os.environ, but it is |
| 100 | + best practice to use this cfg dict instead of os.environ. |
| 101 | + """ |
| 102 | + logging.info("Function starting") |
| 103 | + |
| 104 | + def stop(self): |
| 105 | + """ stop is an optional method which is called when a function is |
| 106 | + stopped, such as when scaled down, updated, or manually canceled. Stop |
| 107 | + can block while performing function shutdown/cleanup operations. The |
| 108 | + process will eventually be killed if this method blocks beyond the |
| 109 | + platform's configured maximum studown timeout. |
| 110 | + """ |
| 111 | + logging.info("Function stopping") |
| 112 | + |
| 113 | + def alive(self): |
| 114 | + """ alive is an optional method for performing a deep check on your |
| 115 | + Function's liveness. If removed, the system will assume the function |
| 116 | + is ready if the process is running. This is exposed by default at the |
| 117 | + path /health/liveness. The optional string return is a message. |
| 118 | + """ |
| 119 | + return True, "Alive" |
| 120 | + |
| 121 | + def ready(self): |
| 122 | + """ ready is an optional method for performing a deep check on your |
| 123 | + Function's readiness. If removed, the system will assume the function |
| 124 | + is ready if the process is running. This is exposed by default at the |
| 125 | + path /health/rediness. |
| 126 | + """ |
| 127 | + return True, "Ready" |
0 commit comments