gh-inference 0.6.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ from .batch import BatchJob, ComparisonJob
2
+ from .client import GitHubAIRunner
3
+ from .core import ai_call
4
+ from .job import AIJob
5
+ from .limits import Limits
6
+ from .models import (
7
+ DEFAULT_CONTEXT,
8
+ MAX_TEMPERATURE,
9
+ MAX_TOKENS_LIMIT,
10
+ MIN_TEMPERATURE,
11
+ MODELS,
12
+ model_resources,
13
+ )
14
+ from .types import (
15
+ AgentTimings,
16
+ InferenceRequest,
17
+ InferenceResult,
18
+ IntegrityError,
19
+ IntegrityInfo,
20
+ JobCancelledError,
21
+ JobFailedError,
22
+ JobRecord,
23
+ JobStatus,
24
+ ProviderConfig,
25
+ ResourceUsage,
26
+ RetryPolicy,
27
+ TokenUsage,
28
+ )
29
+
30
+ __version__ = "0.6.2"
31
+ __all__ = [
32
+ "Limits",
33
+ "DEFAULT_CONTEXT",
34
+ "MAX_TEMPERATURE",
35
+ "MAX_TOKENS_LIMIT",
36
+ "MIN_TEMPERATURE",
37
+ "MODELS",
38
+ "AIJob",
39
+ "Agent",
40
+ "AgentResult",
41
+ "AgentTimings",
42
+ "BatchJob",
43
+ "ComparisonJob",
44
+ "GitHubAIRunner",
45
+ "InferenceRequest",
46
+ "InferenceResult",
47
+ "IntegrityError",
48
+ "IntegrityInfo",
49
+ "JobCancelledError",
50
+ "JobFailedError",
51
+ "JobRecord",
52
+ "JobStatus",
53
+ "ProviderConfig",
54
+ "RefinementInfo",
55
+ "ResourceUsage",
56
+ "RetryPolicy",
57
+ "TokenUsage",
58
+ "ai_call",
59
+ "model_resources",
60
+ ]
61
+ from .agent import Agent
62
+ from .agent_types import AgentResult, RefinementInfo
63
+ from .hub import search_models, list_quantizations, resolve_model, clear_model_cache, add_model
64
+
65
+ __all__ += ["search_models", "list_quantizations", "resolve_model", "clear_model_cache", "add_model"]
66
+
67
+ from .stress import stress_test
68
+
69
+ __all__ += ["stress_test"]
70
+
71
+ from .resident import ResidentSession
72
+ __all__ += ["ResidentSession"]
gh_ai_runner/agent.py ADDED
@@ -0,0 +1,216 @@
1
+ """Text in, text out. All model work happens on GitHub Actions."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import os
6
+ import threading
7
+ import time
8
+
9
+ from .agent_types import AgentResult, RefinementInfo
10
+ from .client import GitHubAIRunner
11
+ from .models import MODELS
12
+ from .hub import resolve_model
13
+ from .limits import Limits, validate_options
14
+ from .types import AgentTimings, TokenUsage
15
+ from .pipeline import normalize_pipeline
16
+
17
+
18
+ class Agent:
19
+ """A reusable GitHub connection with optional conversation and timing.
20
+
21
+ Set GH_AI_TOKEN once, then use Agent().run("your prompt"). run_many() keeps
22
+ the model loaded for all prompts within one GitHub job.
23
+ """
24
+
25
+ def __init__(self, github_token=None, *, model="qwen0.5b",
26
+ instructions="You are a helpful assistant.", track_time=False,
27
+ refine_prompt=False, remember=True, max_history_turns=6, trim_history=True,
28
+ n_ctx=None, max_tokens=512, temperature=.7,
29
+ limits=None, cache=True, model_options=None, generation_options=None,
30
+ repo_name="ai-inference-runner", runner=None,
31
+ quantization=None, filename=None, revision="main"):
32
+ model = resolve_model(model, quantization, filename=filename, revision=revision)
33
+ if not isinstance(instructions, str):
34
+ raise TypeError("instructions must be a string")
35
+ for name, value in (("track_time", track_time), ("refine_prompt", refine_prompt),
36
+ ("remember", remember), ("trim_history", trim_history), ("cache", cache)):
37
+ if type(value) is not bool:
38
+ raise TypeError(f"{name} must be a bool")
39
+ if max_history_turns is not None and (type(max_history_turns) is not int or max_history_turns < 1):
40
+ raise ValueError("max_history_turns must be a positive integer or None")
41
+ if limits is not None and not isinstance(limits, Limits):
42
+ raise TypeError("limits must be a Limits instance")
43
+ self.limits = limits if limits is not None else (runner.limits if isinstance(runner, GitHubAIRunner) else Limits())
44
+ validate_options(model_options, generation_options)
45
+ self.model_options, self.generation_options = dict(model_options or {}), dict(generation_options or {})
46
+ self.cache = cache
47
+ self.model, self.instructions = model, instructions
48
+ self.track_time, self.refine_prompt, self.remember = track_time, refine_prompt, remember
49
+ self.max_history_turns = max_history_turns
50
+ self.trim_history = trim_history
51
+ self.n_ctx, self.max_tokens, self.temperature = n_ctx, max_tokens, temperature
52
+ self.last_result = None
53
+ self.last_results = []
54
+ self.last_job = None
55
+ self._history = []
56
+ self._lock = threading.RLock()
57
+ if runner is None:
58
+ token = github_token or os.environ.get("GH_AI_TOKEN")
59
+ if not token:
60
+ raise ValueError("Set GH_AI_TOKEN once, or pass Agent(github_token=...). Models run only on GitHub.")
61
+ runner = GitHubAIRunner(token, repo_name=repo_name, metadata_path=None, limits=self.limits)
62
+ self.runner = runner
63
+
64
+ @classmethod
65
+ def experimental(cls, **kwargs):
66
+ """Remove project ceilings and history trimming; external limits still apply."""
67
+ options = {"limits": Limits.unrestricted(), "trim_history": False,
68
+ "max_history_turns": None}
69
+ options.update(kwargs)
70
+ return cls(**options)
71
+
72
+ def connect(self):
73
+ """Optional: prepare the repository now. run() also does this automatically."""
74
+ self.runner.prepare()
75
+ return self
76
+
77
+ def reset(self):
78
+ """Forget this conversation without changing the runner repository."""
79
+ with self._lock:
80
+ self._history = []
81
+
82
+ def __call__(self, prompt, **kwargs):
83
+ return self.run(prompt, **kwargs)
84
+
85
+ def run(self, prompt, *, timeout=None, track_time=None):
86
+ """Return plain text. Inspect last_result for optional diagnostics."""
87
+ return self.run_many([prompt], timeout=timeout, track_time=track_time)[0]
88
+
89
+ def run_many(self, prompts, *, timeout=None, track_time=None):
90
+ """Return text answers from one GitHub job; load the model only once."""
91
+ return self._run_many(prompts, timeout=timeout, track_time=track_time)
92
+
93
+ def discuss(self, prompt, *, agents=4, rounds=3, peer_chars=240,
94
+ topology="all", timeout=None, track_time=None):
95
+ """Return rounds of replies from one resident model on one GitHub worker.
96
+
97
+ Logical agents take turns sequentially. Each sees only the previous round,
98
+ not this Agent's conversation. Set Limits.max_prompts >= agents * rounds.
99
+ Ring topology sends only the previous neighbor's reply to each agent.
100
+ """
101
+ for name, value in (("agents", agents), ("rounds", rounds), ("peer_chars", peer_chars)):
102
+ if type(value) is not int or value < 1:
103
+ raise ValueError(f"{name} must be a positive integer")
104
+ if topology not in ("all", "ring"):
105
+ raise ValueError("topology must be all or ring")
106
+ if self.limits.max_prompts is not None and agents * rounds > self.limits.max_prompts:
107
+ raise ValueError("Discussion exceeds Limits.max_prompts; raise it to agents * rounds")
108
+ interaction = dict(agents=agents, rounds=rounds, peer_chars=peer_chars, topology=topology)
109
+ outputs = self._run_many([prompt], timeout=timeout, track_time=track_time,
110
+ discussion=interaction)
111
+ return [outputs[i:i + agents] for i in range(0, len(outputs), agents)]
112
+
113
+ def pipeline(self, prompt, steps, *, timeout=None, track_time=None):
114
+ """Run routed steps in one job, returning outputs in step order.
115
+
116
+ Steps name an agent, an instruction, and earlier output indices in inputs.
117
+ Omitted inputs default to the preceding step. Only explicitly selected
118
+ outputs are provided; no implicit per-agent conversation is accumulated.
119
+ """
120
+ plan = normalize_pipeline(steps, self.limits.max_prompts)
121
+ return self._run_many([prompt], timeout=timeout, track_time=track_time, pipeline=plan)
122
+
123
+ def review(self, prompt, *, revisions=1, timeout=None, track_time=None):
124
+ """Draft -> review -> revise without restarting the worker or model."""
125
+ if type(revisions) is not int or revisions < 1:
126
+ raise ValueError("revisions must be a positive integer")
127
+ if self.limits.max_prompts is not None and 1 + 2 * revisions > self.limits.max_prompts:
128
+ raise ValueError("Review exceeds configured max_prompts")
129
+ steps = [{"agent": "writer", "instruction": "Complete the shared task.", "inputs": []}]
130
+ for _ in range(revisions):
131
+ draft = len(steps) - 1
132
+ steps.append({"agent": "reviewer", "instruction":
133
+ "Check the draft against the shared task. Give specific, actionable corrections.",
134
+ "inputs": [draft]})
135
+ steps.append({"agent": "writer", "instruction":
136
+ "Revise the draft using the review. Return the complete corrected answer.",
137
+ "inputs": [draft, draft + 1]})
138
+ return self.pipeline(prompt, steps, timeout=timeout, track_time=track_time)[-1]
139
+
140
+ def _run_many(self, prompts, *, timeout=None, track_time=None, discussion=None, pipeline=None):
141
+ if not isinstance(prompts, (list, tuple)) or not prompts:
142
+ raise ValueError("prompts must be a nonempty list or tuple")
143
+ if self.limits.max_prompts is not None and len(prompts) > self.limits.max_prompts:
144
+ raise ValueError(f"prompts exceeds configured max_prompts={self.limits.max_prompts}")
145
+ if any(not isinstance(prompt, str) or not prompt.strip() for prompt in prompts):
146
+ raise ValueError("Every prompt must be a nonempty string")
147
+ if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
148
+ or not math.isfinite(timeout) or timeout <= 0):
149
+ raise ValueError("timeout must be finite and positive")
150
+ if track_time is not None and type(track_time) is not bool:
151
+ raise TypeError("track_time must be a bool")
152
+ enabled = self.track_time if track_time is None else track_time
153
+ with self._lock:
154
+ started = time.monotonic()
155
+ config = {
156
+ "tasks": list(prompts[1:]), "refine_prompt": self.refine_prompt,
157
+ "track_time": enabled, "remember": self.remember,
158
+ "max_history_turns": self.max_history_turns,
159
+ "trim_history": self.trim_history,
160
+ "history": self._history if self.remember else [],
161
+ }
162
+ if discussion is not None:
163
+ config.update(discussion=discussion, remember=False, history=[])
164
+ if pipeline is not None:
165
+ config.update(pipeline=pipeline, remember=False, history=[])
166
+ transport_dropped = 0
167
+ while True:
168
+ try:
169
+ job = self.runner.submit(
170
+ prompts[0], model=self.model, system=self.instructions,
171
+ n_ctx=self.n_ctx, max_tokens=self.max_tokens, temperature=self.temperature,
172
+ cache=self.cache, limits=self.limits,
173
+ model_options=self.model_options, generation_options=self.generation_options,
174
+ agent_config=config,
175
+ )
176
+ break
177
+ except ValueError as error:
178
+ if (not self.trim_history or "Combined workflow inputs exceed" not in str(error)
179
+ or not config["history"]):
180
+ raise
181
+ config["history"] = config["history"][2:]
182
+ transport_dropped += 1
183
+ except Exception as error:
184
+ if getattr(error, "job", None) is not None:
185
+ self.last_job = error.job
186
+ raise
187
+ self.last_job = job
188
+ remote = job.result(timeout=timeout)
189
+ elapsed = time.monotonic() - started
190
+ payload = remote.raw.get("agent")
191
+ expected = (len(pipeline) if pipeline is not None else
192
+ discussion["agents"] * discussion["rounds"] if discussion else len(prompts))
193
+ if not isinstance(payload, dict) or len(payload.get("results", [])) != expected:
194
+ raise RuntimeError("GitHub worker returned an incomplete agent result")
195
+ results = []
196
+ for item in payload["results"]:
197
+ refinement = dict(item.get("refinement", {}))
198
+ refinement["usage"] = TokenUsage(**refinement.get("usage", {}))
199
+ timings = AgentTimings(**item["timings"]) if enabled else None
200
+ if timings is not None:
201
+ timings.remote_seconds = elapsed
202
+ results.append(AgentResult(
203
+ output=item["output"], model=self.model, resources=remote.resources,
204
+ usage=TokenUsage(**item.get("usage", {})), timings=timings,
205
+ refinement=RefinementInfo(**refinement), model_reused=item.get("model_reused", False),
206
+ weights_cached=item.get("weights_cached", False),
207
+ dropped_history_turns=item.get("dropped_history_turns", 0) + transport_dropped,
208
+ finish_reason=item.get("finish_reason", "stop"),
209
+ agent_id=item.get("agent_id", ""), step_index=item.get("step_index"),
210
+ input_steps=item.get("input_steps", []),
211
+ handoff_chars=item.get("handoff_chars", 0), handoff_bytes=item.get("handoff_bytes", 0),
212
+ ))
213
+ if self.remember and discussion is None and pipeline is None:
214
+ self._history = payload.get("history", [])
215
+ self.last_results, self.last_result = results, results[-1]
216
+ return [result.output for result in results]
@@ -0,0 +1,43 @@
1
+ """Optional diagnostics; Agent.run() itself returns plain text."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Optional
6
+
7
+ from .types import AgentTimings, TokenUsage, ResourceUsage
8
+
9
+
10
+ @dataclass
11
+ class RefinementInfo:
12
+ attempted: bool = False
13
+ applied: bool = False
14
+ original_tokens: int = 0
15
+ refined_tokens: int = 0
16
+ reason: str = "disabled"
17
+ usage: TokenUsage = field(default_factory=TokenUsage)
18
+
19
+ @property
20
+ def tokens_saved(self):
21
+ return max(0, self.original_tokens - self.refined_tokens) if self.applied else 0
22
+
23
+
24
+ @dataclass
25
+ class AgentResult:
26
+ output: str
27
+ model: str
28
+ backend: str = "github"
29
+ usage: TokenUsage = field(default_factory=TokenUsage)
30
+ timings: Optional[AgentTimings] = None
31
+ refinement: RefinementInfo = field(default_factory=RefinementInfo)
32
+ model_reused: bool = False
33
+ weights_cached: bool = False
34
+ dropped_history_turns: int = 0
35
+ finish_reason: str = "stop"
36
+ # Whole worker job; shared across results from run_many(), never sum copies.
37
+ resources: ResourceUsage = field(default_factory=ResourceUsage)
38
+ agent_id: str = ""
39
+ step_index: Optional[int] = None
40
+ input_steps: list[int] = field(default_factory=list)
41
+ # In-memory handoff payload; these are not network-transfer counters.
42
+ handoff_chars: int = 0
43
+ handoff_bytes: int = 0
@@ -0,0 +1,109 @@
1
+ import io
2
+ import json
3
+ import time
4
+ import zipfile
5
+ from dataclasses import fields
6
+
7
+ import requests
8
+
9
+ from .integrity import text_sha256
10
+ from .repo import API, _headers
11
+ from .types import (
12
+ InferenceResult,
13
+ IntegrityError,
14
+ IntegrityInfo,
15
+ ResourceUsage,
16
+ TokenUsage,
17
+ )
18
+
19
+
20
+ def _download_result(
21
+ token,
22
+ username,
23
+ repo_name,
24
+ run_id,
25
+ job_id,
26
+ correlation_id,
27
+ verbose,
28
+ timeout=60,
29
+ expected_request_sha256=None,
30
+ http_timeout=30,
31
+ ):
32
+ deadline = time.monotonic() + timeout
33
+ target = None
34
+ artifact_name = f"ai-output-{correlation_id}"
35
+ while time.monotonic() < deadline:
36
+ response = requests.get(
37
+ f"{API}/repos/{username}/{repo_name}/actions/runs/{run_id}/artifacts",
38
+ headers=_headers(token),
39
+ timeout=min(http_timeout, max(0.001, deadline - time.monotonic())),
40
+ )
41
+ response.raise_for_status()
42
+ target = next(
43
+ (item for item in response.json().get("artifacts", []) if item["name"] == artifact_name),
44
+ None,
45
+ )
46
+ if target:
47
+ break
48
+ time.sleep(min(2, max(0, deadline - time.monotonic())))
49
+ if not target:
50
+ raise TimeoutError(f"No {artifact_name} artifact found before the deadline")
51
+
52
+ if time.monotonic() >= deadline:
53
+ raise TimeoutError("Timed out before downloading the result artifact")
54
+ response = requests.get(
55
+ f"{API}/repos/{username}/{repo_name}/actions/artifacts/{target['id']}/zip",
56
+ headers=_headers(token),
57
+ allow_redirects=True,
58
+ timeout=min(http_timeout, max(0.001, deadline - time.monotonic())),
59
+ )
60
+ response.raise_for_status()
61
+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
62
+ name = "result.json" if "result.json" in archive.namelist() else None
63
+ if not name:
64
+ raise RuntimeError(f"result.json not found in artifact. Contents: {archive.namelist()}")
65
+ data = json.loads(archive.read(name).decode("utf-8"))
66
+
67
+ if data.get("job_id") != job_id or data.get("correlation_id") != correlation_id:
68
+ raise IntegrityError("Result identity does not match the requested job", run_id=run_id)
69
+ integrity = data.get("integrity") or {}
70
+ if integrity.get("algorithm") != "sha256":
71
+ raise IntegrityError("Result uses an unsupported integrity algorithm", run_id=run_id)
72
+ actual_output_sha256 = text_sha256(data.get("output", ""))
73
+ if integrity.get("output_sha256") != actual_output_sha256:
74
+ raise IntegrityError("Result output checksum verification failed", run_id=run_id)
75
+ if expected_request_sha256 and integrity.get("request_sha256") != expected_request_sha256:
76
+ raise IntegrityError("Result request checksum verification failed", run_id=run_id)
77
+ if "agent" in data:
78
+ actual_agent_sha256 = text_sha256(json.dumps(data["agent"], sort_keys=True, separators=(",", ":")))
79
+ if integrity.get("agent_sha256") != actual_agent_sha256:
80
+ raise IntegrityError("Agent result checksum verification failed", run_id=run_id)
81
+
82
+ if data.get("error"):
83
+ raise IntegrityError("Worker reported an unsuccessful inference", run_id=run_id)
84
+
85
+ usage = data.get("usage") or {}
86
+ resources = data.get("resources") or {}
87
+ return InferenceResult(
88
+ job_id=job_id,
89
+ correlation_id=correlation_id,
90
+ run_id=run_id,
91
+ output=data.get("output", ""),
92
+ model=data.get("model", ""),
93
+ provider=data.get("provider", "local"),
94
+ usage=TokenUsage(
95
+ prompt_tokens=int(usage.get("prompt_tokens", 0)),
96
+ completion_tokens=int(usage.get("completion_tokens", 0)),
97
+ total_tokens=int(usage.get("total_tokens", 0)),
98
+ ),
99
+ resources=ResourceUsage(**{
100
+ item.name: resources.get(item.name, item.default)
101
+ for item in fields(ResourceUsage)
102
+ }),
103
+ integrity=IntegrityInfo(
104
+ algorithm=integrity.get("algorithm", "sha256"),
105
+ request_sha256=integrity.get("request_sha256", ""),
106
+ output_sha256=integrity.get("output_sha256", ""),
107
+ ),
108
+ raw=data,
109
+ )
gh_ai_runner/batch.py ADDED
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from typing import Optional
6
+
7
+ from .job import AIJob
8
+ from .types import InferenceResult, JobStatus
9
+
10
+
11
+ class BatchJob:
12
+ def __init__(self, jobs: list[AIJob], batch_id: Optional[str] = None) -> None:
13
+ if not jobs:
14
+ raise ValueError("a batch must contain at least one job")
15
+ self.jobs = list(jobs)
16
+ self.batch_id = batch_id or jobs[0].batch_id
17
+
18
+ def refresh(self) -> dict[str, JobStatus]:
19
+ return {job.job_id: job.refresh() for job in self.jobs}
20
+
21
+ def wait(self, timeout: Optional[float] = None) -> BatchJob:
22
+ started = time.monotonic()
23
+
24
+ def wait_one(job: AIJob) -> None:
25
+ remaining = None if timeout is None else max(0.0, timeout - (time.monotonic() - started))
26
+ job.wait(timeout=remaining)
27
+
28
+ with ThreadPoolExecutor(max_workers=min(8, len(self.jobs))) as executor:
29
+ list(executor.map(wait_one, self.jobs))
30
+ return self
31
+
32
+ def results(self, timeout: Optional[float] = None) -> list[InferenceResult]:
33
+ started = time.monotonic()
34
+
35
+ def result_one(job: AIJob) -> InferenceResult:
36
+ remaining = None if timeout is None else max(0.0, timeout - (time.monotonic() - started))
37
+ return job.result(timeout=remaining)
38
+
39
+ with ThreadPoolExecutor(max_workers=min(8, len(self.jobs))) as executor:
40
+ return list(executor.map(result_one, self.jobs))
41
+
42
+ def cancel(self) -> dict[str, bool]:
43
+ with ThreadPoolExecutor(max_workers=min(8, len(self.jobs))) as executor:
44
+ outcomes = list(executor.map(lambda job: job.cancel(), self.jobs))
45
+ return {job.job_id: outcome for job, outcome in zip(self.jobs, outcomes)}
46
+
47
+
48
+ class ComparisonJob(BatchJob):
49
+ def __init__(self, jobs: list[AIJob], models: list[str], batch_id: Optional[str] = None) -> None:
50
+ super().__init__(jobs, batch_id=batch_id)
51
+ self.models = list(models)
52
+
53
+ def results_by_model(self, timeout: Optional[float] = None) -> dict[str, InferenceResult]:
54
+ return dict(zip(self.models, self.results(timeout=timeout)))