|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""A Microsoft Agent Framework agent doing REAL, fully offline inference. |
| 3 | +
|
| 4 | +The agent is a real `agent_framework` Agent, backed by a custom ChatClient that |
| 5 | +runs a small GGUF model with llama-cpp-python. The model is baked into the |
| 6 | +image, so inference happens entirely inside the Hyperlight micro-VM — no network |
| 7 | +access and no API keys. |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import sys |
| 13 | +import types |
| 14 | +import warnings |
| 15 | + |
| 16 | +# Keep the demo output clean. |
| 17 | +warnings.filterwarnings("ignore") |
| 18 | +logging.getLogger("agent_framework").setLevel(logging.ERROR) |
| 19 | + |
| 20 | +# The trimmed python-base omits a few stdlib modules that llama-cpp-python imports |
| 21 | +# transitively (multiprocessing via llama.py, sqlite3 via diskcache). This example |
| 22 | +# never uses either — inference is single-process and we don't use the disk cache — |
| 23 | +# so we register minimal stubs so the imports succeed. |
| 24 | +_mp = types.ModuleType("multiprocessing") |
| 25 | +_mp.cpu_count = lambda: os.cpu_count() or 1 |
| 26 | +sys.modules.setdefault("multiprocessing", _mp) |
| 27 | + |
| 28 | +_sq = types.ModuleType("sqlite3") |
| 29 | +_sq.Binary = memoryview |
| 30 | + |
| 31 | + |
| 32 | +class _SqliteError(Exception): |
| 33 | + pass |
| 34 | + |
| 35 | + |
| 36 | +_sq.Error = _sq.OperationalError = _sq.DatabaseError = _SqliteError |
| 37 | +_sq.IntegrityError = _sq.ProgrammingError = _SqliteError |
| 38 | +_sq.connect = lambda *a, **k: None |
| 39 | +_sq.register_adapter = _sq.register_converter = lambda *a, **k: None |
| 40 | +_sq.PARSE_DECLTYPES = 1 |
| 41 | +_sq.PARSE_COLNAMES = 2 |
| 42 | +_sq.Row = object |
| 43 | +_sq.sqlite_version = _sq.version = "0" |
| 44 | +sys.modules.setdefault("sqlite3", _sq) |
| 45 | + |
| 46 | +from collections.abc import Awaitable, Coroutine, Mapping, Sequence # noqa: E402 |
| 47 | +from typing import Any # noqa: E402 |
| 48 | + |
| 49 | +from agent_framework import ( # noqa: E402 |
| 50 | + Agent, |
| 51 | + BaseChatClient, |
| 52 | + ChatResponse, |
| 53 | + Message, |
| 54 | +) |
| 55 | +from llama_cpp import Llama # noqa: E402 |
| 56 | + |
| 57 | +MODEL_PATH = "/model.gguf" |
| 58 | + |
| 59 | + |
| 60 | +class LlamaCppChatClient(BaseChatClient): |
| 61 | + """Chat client backed by a local llama.cpp GGUF model.""" |
| 62 | + |
| 63 | + def __init__(self, model_path: str = MODEL_PATH, **kwargs: Any) -> None: |
| 64 | + super().__init__(**kwargs) |
| 65 | + self._llm = Llama( |
| 66 | + model_path=model_path, |
| 67 | + n_ctx=512, |
| 68 | + n_batch=64, # small compute buffers to fit the identity-mapped guest |
| 69 | + n_threads=max(1, os.cpu_count() or 1), |
| 70 | + use_mmap=False, # the guest ramfs doesn't support file-backed mmap |
| 71 | + verbose=False, |
| 72 | + ) |
| 73 | + |
| 74 | + def _inner_get_response( |
| 75 | + self, |
| 76 | + *, |
| 77 | + messages: Sequence[Message], |
| 78 | + stream: bool = False, |
| 79 | + options: Mapping[str, Any], |
| 80 | + **kwargs: Any, |
| 81 | + ) -> Awaitable[ChatResponse]: |
| 82 | + chat = [ |
| 83 | + {"role": m.role, "content": m.text} |
| 84 | + for m in messages |
| 85 | + if m.text |
| 86 | + ] |
| 87 | + completion = self._llm.create_chat_completion( |
| 88 | + messages=chat, |
| 89 | + max_tokens=64, |
| 90 | + temperature=0.7, |
| 91 | + ) |
| 92 | + reply = completion["choices"][0]["message"]["content"].strip() |
| 93 | + response = ChatResponse( |
| 94 | + messages=[Message(role="assistant", contents=[reply])], |
| 95 | + model=os.path.basename(MODEL_PATH), |
| 96 | + ) |
| 97 | + |
| 98 | + async def _get() -> ChatResponse: |
| 99 | + return response |
| 100 | + |
| 101 | + return _get() |
| 102 | + |
| 103 | + |
| 104 | +def run_sync(coro: Coroutine[Any, Any, Any]) -> Any: |
| 105 | + """Run a coroutine that performs no real async I/O, without an event loop. |
| 106 | +
|
| 107 | + `asyncio.run()` can't be used here: it builds a Unix selector event loop |
| 108 | + whose wake-up self-pipe needs `socket.socketpair()`, which this unikernel |
| 109 | + doesn't implement (ENOSYS). The client's inference call is synchronous and |
| 110 | + never suspends, so we can just step the coroutine to completion. |
| 111 | + """ |
| 112 | + try: |
| 113 | + while True: |
| 114 | + pending = coro.send(None) |
| 115 | + if pending is not None: |
| 116 | + raise RuntimeError(f"coroutine requires an event loop (awaited {pending!r})") |
| 117 | + except StopIteration as exc: |
| 118 | + return exc.value |
| 119 | + |
| 120 | + |
| 121 | +async def main() -> None: |
| 122 | + agent = Agent( |
| 123 | + client=LlamaCppChatClient(), |
| 124 | + name="LocalHyperlightAgent", |
| 125 | + instructions="You are a concise assistant. Answer in one short sentence.", |
| 126 | + ) |
| 127 | + query = "In one sentence, what is a vm?" |
| 128 | + print(f"User: {query}") |
| 129 | + result = await agent.run(query) |
| 130 | + print(f"Agent: {result.messages[0].text}") |
| 131 | + |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + run_sync(main()) |
0 commit comments