Skip to content

Instantly share code, notes, and snippets.

@rkttu
Created September 12, 2026 15:48
Show Gist options
  • Select an option

  • Save rkttu/805dd58e333b7e51b10326168a484c2d to your computer and use it in GitHub Desktop.

Select an option

Save rkttu/805dd58e333b7e51b10326168a484c2d to your computer and use it in GitHub Desktop.
Local Microsoft technology expert agent powered by Edge0-35B, Microsoft Learn retrieval, and on-device Apple Translation.

Edge0 Microsoft Technology Expert Agent

A small local RAG agent for Apple Silicon Macs that combines Edge0-35B, Microsoft Learn retrieval, and on-device Apple Translation.

This Gist contains three files:

  • README.md: setup and execution guide
  • apple_translate.swift: a minimal CLI wrapper around the macOS Translation framework
  • microsoft_expert_agent.py: the Python agent with Microsoft Learn retrieval, Edge0 streaming, TTFT measurement, and output throughput metrics

Architecture

Korean question
    ↓
Deterministic Korean question normalization
    ↓
Apple Translation
Korean → English
    ↓
Microsoft Learn semantic search
    ↓
Build a compact grounding context
    ↓
Edge0-35B streaming inference
    ↓
Sentence-level Apple Translation
English → Korean
    ↓
Korean answer + sources + performance metrics

The model is not treated as the authoritative knowledge store. Microsoft Learn provides the factual grounding, while Edge0 reads the retrieved passages and synthesizes the answer.

Requirements

This sample assumes:

  • Apple Silicon Mac
  • A macOS version supported by Edge0
  • Python 3.12 recommended
  • Node.js 22 or later
  • Xcode Command Line Tools
  • Enough free storage for the roughly 23GB Edge0-35B checkpoint
  • Korean and English translation resources installed in macOS

Related projects:

1. Install Edge0

Clone the repository.

git clone https://github.com/Edge0-AI/Edge0.git
cd Edge0

Create and activate a Python virtual environment.

python3.12 -m venv .venv
source .venv/bin/activate

Install Edge0 and the packages used by this sample.

pip install -e '.[dev,fetch]'
pip install flask requests

2. Download Edge0-35B

python scripts/fetch_models.py \
  --tier edge0-35b \
  --target-dir models

Set the model path for the current shell.

export EDGE0_35B_MODEL="$PWD/models/edge0-35b"

3. Start the Edge0 streaming server in Terminal 1

A newly opened terminal does not inherit the active Python virtual environment.

Activate it again.

cd /path/to/Edge0
source .venv/bin/activate

Set the model path again because this is a new shell.

export EDGE0_35B_MODEL="$PWD/models/edge0-35b"

Start Edge0 with the Flask transport so the client can receive SSE streaming responses.

edge0 serve edge0-35b \
  --host 127.0.0.1 \
  --port 8083 \
  --flask

Keep this terminal running.

You can verify the server from another shell.

curl http://127.0.0.1:8083/healthz

4. Install the Microsoft Learn CLI

Install Node.js 22 or later, then install the CLI.

npm install -g @microsoft/learn-cli

Test the semantic document search.

mslearn search \
  ".NET NativeAOT Reflection.Emit" \
  --json

microsoft_expert_agent.py launches this CLI as a subprocess and consumes the JSON search results.

The sample intentionally uses the CLI rather than implementing the MCP transport directly so the code stays focused on retrieval and local inference.

5. Build the Apple Translation CLI

Save apple_translate.swift from this Gist in the Edge0 repository directory.

Compile it.

xcrun swiftc \
  -parse-as-library \
  apple_translate.swift \
  -o apple_translate

-parse-as-library is important when compiling this single Swift source file with an @main entry point.

Install translation language resources

If the Korean or English translation resources are missing, the CLI can fail with an error similar to:

TranslationError.Cause.notInstalled

Install Korean and English translation languages in macOS settings, then test the CLI.

./apple_translate ko en \
  "NativeAOT에서 Reflection.Emit을 사용할 수 있습니까?"

A valid English translation should be printed.

6. Place the Python agent

Save microsoft_expert_agent.py from this Gist in the Edge0 repository root.

Example directory layout:

Edge0/
├── .venv/
├── models/
│   └── edge0-35b/
├── apple_translate
├── apple_translate.swift
└── microsoft_expert_agent.py

7. Start the agent in Terminal 2

Keep the Edge0 server running in Terminal 1.

Open a second terminal and move to the Edge0 directory.

cd /path/to/Edge0

Activate the virtual environment again in this shell.

source .venv/bin/activate

Make sure requests is installed in the active environment.

pip install requests

Start the agent.

python microsoft_expert_agent.py

8. Example session

The console UI itself is in English, while the sample accepts Korean questions and returns Korean answers.

Microsoft Technology Expert Agent
Microsoft Learn + Edge0-35B
Exit: /exit    Clear history: /clear

Question> NativeAOT에서 Reflection.Emit을 사용할 수 있는지도 설명해주세요.

The host normalizes the Korean indirect question, translates it into English, and searches Microsoft Learn.

A real M2 MacBook Air 16GB test selected the following sources:

Grounding sources
  [1] Native AOT deployment
  [2] Introduction to AOT warnings
  [3] ASP.NET Core support for Native AOT

While Edge0 is processing the prompt, the client prints an observable progress update every five seconds.

[   2.6s] Sending request to Edge0-35B
[   7.6s] Edge0 is processing; waiting for first token: 5s
[  12.6s] Edge0 is processing; waiting for first token: 10s
...
[  56.1s] First token received (TTFT 53.5s)

The English token stream is not translated token by token. The host buffers the stream until a full sentence is available, then translates that sentence to Korean.

A real measurement from an M2 MacBook Air 16GB produced:

Metrics
  TTFT               53.47s
  Total generation   82.11s
  Completion tokens  119
  Time after first   28.64s
  Output speed       4.15 tok/s

These numbers represent one request with one particular prompt and grounding set. They will vary with the Mac model, cache state, prompt length, retrieval results, and output length.

9. Agent commands

Clear the in-memory conversation history:

/clear

Exit the agent:

/exit

10. Control grounding size

The Python sample limits the number and size of Microsoft Learn search passages.

MAX_SOURCES = 3
MAX_SOURCE_CHARS = 1800

Longer grounding can substantially increase TTFT on slower local hardware.

If the retrieved information is insufficient, increase these values and compare the resulting TTFT.

11. Conversation history

The sample does not keep previous Microsoft Learn grounding passages in the conversation history.

It only retains recent user questions and Edge0 English responses.

MAX_HISTORY_TURNS = 2

Each new user request performs a fresh Microsoft Learn search and supplies only the grounding needed for that request.

This prevents the prompt from growing continuously across a long conversation.

12. Why the code contains Korean normalization rules

The source file intentionally contains a small number of Korean string patterns.

They are functional input-normalization rules rather than UI text.

During testing, Korean indirect questions such as:

런타임에 새로운 실행 코드를 생성하는지도 설명해주세요.

could be mistranslated into a request asking how to generate executable code instead of whether runtime generation occurs.

The agent therefore rewrites a few known indirect-question forms into explicit yes/no questions before translation.

The current normalizer handles patterns similar to:

  • ~할 수 있는지도
  • ~되는지도
  • ~하는지도
  • ~필요한지도

For example:

생성하는지도 설명해주세요.

is normalized into:

생성합니까?
그 여부도 설명해주세요.

This is not a general Korean rewriting system. Unknown sentence forms are left unchanged.

13. Performance metrics

TTFT

Time from starting the HTTP request until the first SSE token arrives.

It may include server queue time, tokenization, prompt prefill, and the first decode step.

Total generation time

Time from starting the request until the server sends [DONE].

Completion tokens

The sample counts SSE events that contain generated content.

This is a lightweight measurement based on the current Edge0 streaming behavior.

If a future server version batches multiple generated tokens into one SSE event, use tokenizer-based counting instead.

Output speed

Completion token count divided by the time between the first token and [DONE].

Separating TTFT from sustained decode speed is useful when tuning a local RAG system. A long grounding context can primarily increase TTFT even when steady-state token generation remains acceptable.

14. Limitations

This is a proof-of-concept and experimentation sample.

It does not implement:

  • authentication
  • persistent per-user sessions
  • multi-user concurrent serving
  • a production request queue
  • retry policies
  • direct MCP protocol integration
  • a retrieval reranker
  • prompt-injection defenses
  • structured audit logging
  • document-level authorization filtering

The current Edge0 server should also not be treated as a production-grade multi-session continuous-batching inference server.

Use this sample for personal experiments or tightly scoped PoCs.

15. Shutdown

Exit the Python agent with:

/exit

Stop the Edge0 server in Terminal 1 with Ctrl+C.

import Foundation
import Translation
@main
struct AppleTranslateCLI {
static func main() async {
guard CommandLine.arguments.count >= 4 else {
fputs(
"usage: apple_translate <source> <target> <text>\n",
stderr
)
exit(2)
}
let source = Locale.Language(
identifier: CommandLine.arguments[1]
)
let target = Locale.Language(
identifier: CommandLine.arguments[2]
)
let text = CommandLine.arguments
.dropFirst(3)
.joined(separator: " ")
do {
let session = TranslationSession(
installedSource: source,
target: target,
preferredStrategy: .lowLatency
)
let response = try await session.translate(text)
print(response.targetText)
}
catch {
fputs(
"translation error: \(error)\n",
stderr
)
exit(1)
}
}
}
#!/usr/bin/env python3
import json
import os
import queue
import re
import subprocess
import threading
import time
from dataclasses import dataclass
import requests
EDGE0_BASE_URL = os.environ.get(
"EDGE0_BASE_URL",
"http://127.0.0.1:8083",
)
EDGE0_MODEL = os.environ.get(
"EDGE0_MODEL",
"edge0-35b",
)
TRANSLATOR = os.environ.get(
"TRANSLATOR",
"./apple_translate",
)
MAX_SOURCES = 3
MAX_SOURCE_CHARS = 1800
MAX_HISTORY_TURNS = 2
MAX_TOKENS = 220
SYSTEM_PROMPT = """
You are a Microsoft technology expert.
Answer using the supplied Microsoft Learn references
as the primary source of factual information.
Rules:
- Prefer facts explicitly supported by the references.
- If the references do not establish a fact, say so.
- Do not invent API names, product behavior, limits,
or version details.
- Ignore unrelated search results.
- Use short plain-text paragraphs.
- Cite supporting references using [1], [2], [3].
""".strip()
@dataclass
class Source:
title: str
url: str
content: str
@dataclass
class StreamStats:
request_started: float = 0.0
first_token_at: float | None = None
done_at: float | None = None
completion_tokens: int = 0
@property
def ttft(self) -> float | None:
if self.first_token_at is None:
return None
return self.first_token_at - self.request_started
@property
def total_generation_time(self) -> float | None:
if self.done_at is None:
return None
return self.done_at - self.request_started
@property
def decode_time(self) -> float | None:
if self.first_token_at is None or self.done_at is None:
return None
return self.done_at - self.first_token_at
@property
def output_tokens_per_second(self) -> float | None:
duration = self.decode_time
if not duration or duration <= 0:
return None
return self.completion_tokens / duration
class Activity:
def __init__(self):
self.started = time.perf_counter()
def show(self, message: str):
elapsed = time.perf_counter() - self.started
print(
f"[{elapsed:6.1f}s] {message}",
flush=True,
)
def run_process(args: list[str]) -> str:
result = subprocess.run(
args,
check=True,
capture_output=True,
text=True,
)
return result.stdout.strip()
def translate(
text: str,
source: str,
target: str,
) -> str:
return run_process([
TRANSLATOR,
source,
target,
text,
])
# These Korean literals are intentional. They are input-normalization
# rules used to preserve the semantics of Korean indirect questions
# before sending them to the on-device translation layer.
def make_followup(action: str) -> str:
if action == "알려주세요":
return "그 여부도 알려주세요."
if action == "확인해주세요":
return "그 여부도 확인해주세요."
return "그 여부도 설명해주세요."
def normalize_korean_question(text: str) -> str:
suffix = (
r"\s*(?:함께\s*)?"
r"(설명해주세요|알려주세요|확인해주세요)"
r"\.?$"
)
patterns = [
(
rf"^(.*)할 수 있는지도{suffix}",
lambda m:
f"{m.group(1)}할 수 있습니까? "
f"{make_followup(m.group(2))}",
),
(
rf"^(.*)되는지도{suffix}",
lambda m:
f"{m.group(1)}됩니까? "
f"{make_followup(m.group(2))}",
),
(
rf"^(.*)하는지도{suffix}",
lambda m:
f"{m.group(1)}합니까? "
f"{make_followup(m.group(2))}",
),
(
rf"^(.*)필요한지도{suffix}",
lambda m:
f"{m.group(1)}필요합니까? "
f"{make_followup(m.group(2))}",
),
]
for pattern, replacement in patterns:
match = re.match(pattern, text)
if match:
return replacement(match)
return text
def split_korean_input(text: str) -> list[str]:
return [
part.strip()
for part in re.split(
r"(?<=[?!])\s+|(?<=\.)\s+",
text,
)
if part.strip()
]
def translate_question_to_english(
question: str,
) -> tuple[str, list[dict]]:
translated = []
trace = []
for segment in split_korean_input(question):
normalized = normalize_korean_question(segment)
english = translate(
normalized,
"ko",
"en",
)
translated.append(english)
trace.append({
"original": segment,
"normalized": normalized,
"english": english,
})
return " ".join(translated), trace
def search_microsoft_learn(
query_text: str,
) -> list[Source]:
raw = run_process([
"mslearn",
"search",
query_text,
"--json",
])
data = json.loads(raw)
results = (
data.get("results")
or data.get("value")
or []
)
sources = []
seen_urls = set()
for item in results:
url = (
item.get("contentUrl")
or item.get("url")
or item.get("href")
or ""
)
if not url or url in seen_urls:
continue
content = (
item.get("content")
or item.get("snippet")
or item.get("description")
or ""
).strip()
if not content:
continue
seen_urls.add(url)
sources.append(
Source(
title=item.get(
"title",
"(untitled)",
),
url=url,
content=content[:MAX_SOURCE_CHARS],
)
)
if len(sources) >= MAX_SOURCES:
break
return sources
def build_grounding(
sources: list[Source],
) -> str:
blocks = []
for index, source in enumerate(
sources,
start=1,
):
blocks.append(
f"[{index}] {source.title}\n"
f"URL: {source.url}\n\n"
f"{source.content}"
)
return "\n\n---\n\n".join(blocks)
def build_user_prompt(
question: str,
sources: list[Source],
) -> str:
grounding = build_grounding(sources)
return f"""
Microsoft Learn references:
<references>
{grounding}
</references>
Question:
{question}
Answer the question using the references above.
""".strip()
def make_search_query(
current_question: str,
history: list[dict],
) -> str:
previous_user = None
for message in reversed(history):
if message["role"] == "user":
previous_user = message["content"]
break
if previous_user is None:
return current_question
return (
f"Previous topic: {previous_user}\n"
f"Current question: {current_question}"
)
def extract_delta(event: dict) -> str:
try:
return (
event["choices"][0]
.get("delta", {})
.get("content")
or ""
)
except (
KeyError,
IndexError,
TypeError,
):
return ""
def edge0_worker(
messages: list[dict],
events: queue.Queue,
):
try:
response = requests.post(
f"{EDGE0_BASE_URL}/v1/chat/completions",
json={
"model": EDGE0_MODEL,
"messages": messages,
"temperature": 0.0,
"seed": 42,
"max_tokens": MAX_TOKENS,
"stream": True,
},
stream=True,
timeout=600,
)
response.raise_for_status()
for raw_line in response.iter_lines(
decode_unicode=True,
):
if not raw_line:
continue
if not raw_line.startswith("data:"):
continue
payload = raw_line[5:].strip()
if payload == "[DONE]":
break
try:
event = json.loads(payload)
except json.JSONDecodeError:
continue
delta = extract_delta(event)
if delta:
events.put(
(
"token",
delta,
time.perf_counter(),
)
)
events.put(
(
"done",
None,
time.perf_counter(),
)
)
except Exception as exc:
events.put(
(
"error",
exc,
time.perf_counter(),
)
)
def stream_edge0_with_progress(
messages: list[dict],
activity: Activity,
stats: StreamStats,
):
events = queue.Queue()
worker = threading.Thread(
target=edge0_worker,
args=(messages, events),
daemon=True,
)
stats.request_started = time.perf_counter()
worker.start()
last_progress = 0
while True:
try:
kind, value, event_time = events.get(
timeout=1.0
)
except queue.Empty:
if stats.first_token_at is None:
waited = int(
time.perf_counter()
- stats.request_started
)
if (
waited >= 5
and waited - last_progress >= 5
):
activity.show(
"Edge0 is processing; "
f"waiting for first token: {waited}s"
)
last_progress = waited
continue
if kind == "token":
stats.completion_tokens += 1
if stats.first_token_at is None:
stats.first_token_at = event_time
activity.show(
"First token received "
f"(TTFT {stats.ttft:.1f}s)"
)
yield value
elif kind == "done":
stats.done_at = event_time
break
elif kind == "error":
stats.done_at = event_time
raise value
SENTENCE_PATTERN = re.compile(
r'(.+?[.!?](?:["\')\]]+)?)'
r'(?:\s+|$)',
re.DOTALL,
)
def pop_complete_sentences(
buffer: str,
) -> tuple[list[str], str]:
sentences = []
last_end = 0
for match in SENTENCE_PATTERN.finditer(buffer):
sentences.append(
match.group(1).strip()
)
last_end = match.end()
if not sentences:
return [], buffer
return (
sentences,
buffer[last_end:],
)
def print_sources(
sources: list[Source],
):
print()
print("Grounding sources")
for index, source in enumerate(
sources,
start=1,
):
print(
f" [{index}] {source.title}"
)
def print_source_urls(
sources: list[Source],
):
print()
print("Sources")
for index, source in enumerate(
sources,
start=1,
):
print(
f" [{index}] {source.title}"
)
print(
f" {source.url}"
)
def print_metrics(
stats: StreamStats,
):
print()
print("Metrics")
if stats.ttft is not None:
print(
f" TTFT "
f"{stats.ttft:.2f}s"
)
if stats.total_generation_time is not None:
print(
f" Total generation "
f"{stats.total_generation_time:.2f}s"
)
print(
f" Completion tokens "
f"{stats.completion_tokens}"
)
if stats.decode_time is not None:
print(
f" Time after first "
f"{stats.decode_time:.2f}s"
)
if stats.output_tokens_per_second is not None:
print(
f" Output speed "
f"{stats.output_tokens_per_second:.2f} tok/s"
)
def main():
history = []
print(
"Microsoft Technology Expert Agent"
)
print(
"Microsoft Learn + Edge0-35B"
)
print(
"Exit: /exit "
"Clear history: /clear"
)
while True:
print()
korean_question = input(
"Question> "
).strip()
if not korean_question:
continue
if korean_question == "/exit":
break
if korean_question == "/clear":
history.clear()
print(
"Conversation history cleared."
)
continue
activity = Activity()
try:
activity.show(
"Normalizing Korean question"
)
(
english_question,
translation_trace,
) = translate_question_to_english(
korean_question
)
activity.show(
"English search query ready"
)
search_query = make_search_query(
english_question,
history,
)
activity.show(
"Searching Microsoft Learn"
)
sources = search_microsoft_learn(
search_query
)
if not sources:
print(
"No relevant Microsoft Learn "
"content was found."
)
continue
activity.show(
f"Found "
f"{len(sources)} relevant documents"
)
print_sources(
sources
)
messages = [
{
"role": "system",
"content": SYSTEM_PROMPT,
}
]
messages.extend(
history[
-MAX_HISTORY_TURNS * 2:
]
)
messages.append({
"role": "user",
"content": build_user_prompt(
english_question,
sources,
),
})
activity.show(
"Sending request to Edge0-35B"
)
stats = StreamStats()
english_response = ""
translation_buffer = ""
answer_started = False
for delta in stream_edge0_with_progress(
messages,
activity,
stats,
):
english_response += delta
translation_buffer += delta
(
sentences,
translation_buffer,
) = pop_complete_sentences(
translation_buffer
)
for sentence in sentences:
korean_sentence = translate(
sentence,
"en",
"ko",
)
if not answer_started:
print()
print(
"Expert> ",
end="",
flush=True,
)
answer_started = True
print(
korean_sentence,
end=" ",
flush=True,
)
if translation_buffer.strip():
korean_sentence = translate(
translation_buffer.strip(),
"en",
"ko",
)
if not answer_started:
print()
print(
"Expert> ",
end="",
flush=True,
)
answer_started = True
print(
korean_sentence,
end="",
flush=True,
)
if answer_started:
print()
activity.show(
"Response generation completed"
)
print_metrics(stats)
print_source_urls(
sources
)
history.append({
"role": "user",
"content": english_question,
})
history.append({
"role": "assistant",
"content": english_response,
})
except KeyboardInterrupt:
print()
print(
"Current request interrupted."
)
except Exception as exc:
print()
print(
f"Error: {exc}"
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment