gh-inference 0.5.0__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.

Potentially problematic release.


This version of gh-inference might be problematic. Click here for more details.

@@ -0,0 +1,65 @@
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.5.0"
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
64
+
65
+ __all__ += ["search_models", "list_quantizations", "resolve_model", "clear_model_cache"]
gh_ai_runner/agent.py ADDED
@@ -0,0 +1,152 @@
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
+
16
+
17
+ class Agent:
18
+ """A reusable GitHub connection with optional conversation and timing.
19
+
20
+ Set GH_AI_TOKEN once, then use Agent().run("your prompt"). run_many() keeps
21
+ the model loaded for all prompts within one GitHub job.
22
+ """
23
+
24
+ def __init__(self, github_token=None, *, model="qwen0.5b",
25
+ instructions="You are a helpful assistant.", track_time=False,
26
+ refine_prompt=False, remember=True, max_history_turns=6, trim_history=True,
27
+ n_ctx=None, max_tokens=512, temperature=.7,
28
+ limits=None, cache=True, model_options=None, generation_options=None,
29
+ repo_name="ai-inference-runner", runner=None,
30
+ quantization=None, filename=None, revision="main"):
31
+ model = resolve_model(model, quantization, filename=filename, revision=revision)
32
+ if not isinstance(instructions, str):
33
+ raise TypeError("instructions must be a string")
34
+ for name, value in (("track_time", track_time), ("refine_prompt", refine_prompt),
35
+ ("remember", remember), ("trim_history", trim_history), ("cache", cache)):
36
+ if type(value) is not bool:
37
+ raise TypeError(f"{name} must be a bool")
38
+ if max_history_turns is not None and (type(max_history_turns) is not int or max_history_turns < 1):
39
+ raise ValueError("max_history_turns must be a positive integer or None")
40
+ if limits is not None and not isinstance(limits, Limits):
41
+ raise TypeError("limits must be a Limits instance")
42
+ self.limits = limits if limits is not None else (runner.limits if isinstance(runner, GitHubAIRunner) else Limits())
43
+ validate_options(model_options, generation_options)
44
+ self.model_options, self.generation_options = dict(model_options or {}), dict(generation_options or {})
45
+ self.cache = cache
46
+ self.model, self.instructions = model, instructions
47
+ self.track_time, self.refine_prompt, self.remember = track_time, refine_prompt, remember
48
+ self.max_history_turns = max_history_turns
49
+ self.trim_history = trim_history
50
+ self.n_ctx, self.max_tokens, self.temperature = n_ctx, max_tokens, temperature
51
+ self.last_result = None
52
+ self.last_results = []
53
+ self.last_job = None
54
+ self._history = []
55
+ self._lock = threading.RLock()
56
+ if runner is None:
57
+ token = github_token or os.environ.get("GH_AI_TOKEN")
58
+ if not token:
59
+ raise ValueError("Set GH_AI_TOKEN once, or pass Agent(github_token=...). Models run only on GitHub.")
60
+ runner = GitHubAIRunner(token, repo_name=repo_name, metadata_path=None, limits=self.limits)
61
+ self.runner = runner
62
+
63
+ @classmethod
64
+ def experimental(cls, **kwargs):
65
+ """Remove project ceilings and history trimming; external limits still apply."""
66
+ options = {"limits": Limits.unrestricted(), "trim_history": False,
67
+ "max_history_turns": None}
68
+ options.update(kwargs)
69
+ return cls(**options)
70
+
71
+ def connect(self):
72
+ """Optional: prepare the repository now. run() also does this automatically."""
73
+ self.runner.prepare()
74
+ return self
75
+
76
+ def reset(self):
77
+ """Forget this conversation without changing the runner repository."""
78
+ with self._lock:
79
+ self._history = []
80
+
81
+ def __call__(self, prompt, **kwargs):
82
+ return self.run(prompt, **kwargs)
83
+
84
+ def run(self, prompt, *, timeout=None, track_time=None):
85
+ """Return plain text. Inspect last_result for optional diagnostics."""
86
+ return self.run_many([prompt], timeout=timeout, track_time=track_time)[0]
87
+
88
+ def run_many(self, prompts, *, timeout=None, track_time=None):
89
+ """Return text answers from one GitHub job; load the model only once."""
90
+ if not isinstance(prompts, (list, tuple)) or not prompts:
91
+ raise ValueError("prompts must be a nonempty list or tuple")
92
+ if self.limits.max_prompts is not None and len(prompts) > self.limits.max_prompts:
93
+ raise ValueError(f"prompts exceeds configured max_prompts={self.limits.max_prompts}")
94
+ if any(not isinstance(prompt, str) or not prompt.strip() for prompt in prompts):
95
+ raise ValueError("Every prompt must be a nonempty string")
96
+ if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
97
+ or not math.isfinite(timeout) or timeout <= 0):
98
+ raise ValueError("timeout must be finite and positive")
99
+ if track_time is not None and type(track_time) is not bool:
100
+ raise TypeError("track_time must be a bool")
101
+ enabled = self.track_time if track_time is None else track_time
102
+ with self._lock:
103
+ started = time.monotonic()
104
+ config = {
105
+ "tasks": list(prompts[1:]), "refine_prompt": self.refine_prompt,
106
+ "track_time": enabled, "remember": self.remember,
107
+ "max_history_turns": self.max_history_turns,
108
+ "trim_history": self.trim_history,
109
+ "history": self._history if self.remember else [],
110
+ }
111
+ transport_dropped = 0
112
+ while True:
113
+ try:
114
+ job = self.runner.submit(
115
+ prompts[0], model=self.model, system=self.instructions,
116
+ n_ctx=self.n_ctx, max_tokens=self.max_tokens, temperature=self.temperature,
117
+ cache=self.cache, limits=self.limits,
118
+ model_options=self.model_options, generation_options=self.generation_options,
119
+ agent_config=config,
120
+ )
121
+ break
122
+ except ValueError as error:
123
+ if (not self.trim_history or "Combined workflow inputs exceed" not in str(error)
124
+ or not config["history"]):
125
+ raise
126
+ config["history"] = config["history"][2:]
127
+ transport_dropped += 1
128
+ self.last_job = job
129
+ remote = job.result(timeout=timeout)
130
+ elapsed = time.monotonic() - started
131
+ payload = remote.raw.get("agent")
132
+ if not isinstance(payload, dict) or len(payload.get("results", [])) != len(prompts):
133
+ raise RuntimeError("GitHub worker returned an incomplete agent result")
134
+ results = []
135
+ for item in payload["results"]:
136
+ refinement = dict(item.get("refinement", {}))
137
+ refinement["usage"] = TokenUsage(**refinement.get("usage", {}))
138
+ timings = AgentTimings(**item["timings"]) if enabled else None
139
+ if timings is not None:
140
+ timings.remote_seconds = elapsed
141
+ results.append(AgentResult(
142
+ output=item["output"], model=self.model,
143
+ usage=TokenUsage(**item.get("usage", {})), timings=timings,
144
+ refinement=RefinementInfo(**refinement), model_reused=item.get("model_reused", False),
145
+ weights_cached=item.get("weights_cached", False),
146
+ dropped_history_turns=item.get("dropped_history_turns", 0) + transport_dropped,
147
+ finish_reason=item.get("finish_reason", "stop"),
148
+ ))
149
+ if self.remember:
150
+ self._history = payload.get("history", [])
151
+ self.last_results, self.last_result = results, results[-1]
152
+ return [result.output for result in results]
@@ -0,0 +1,35 @@
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
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"
@@ -0,0 +1,117 @@
1
+ import io
2
+ import json
3
+ import time
4
+ import zipfile
5
+
6
+ import requests
7
+
8
+ from .integrity import text_sha256
9
+ from .repo import API, _headers
10
+ from .types import (
11
+ InferenceResult,
12
+ IntegrityError,
13
+ IntegrityInfo,
14
+ ResourceUsage,
15
+ TokenUsage,
16
+ )
17
+
18
+
19
+ def _download_result(
20
+ token,
21
+ username,
22
+ repo_name,
23
+ run_id,
24
+ job_id,
25
+ correlation_id,
26
+ verbose,
27
+ timeout=60,
28
+ expected_request_sha256=None,
29
+ http_timeout=30,
30
+ ):
31
+ deadline = time.monotonic() + timeout
32
+ target = None
33
+ artifact_name = f"ai-output-{correlation_id}"
34
+ while time.monotonic() < deadline:
35
+ response = requests.get(
36
+ f"{API}/repos/{username}/{repo_name}/actions/runs/{run_id}/artifacts",
37
+ headers=_headers(token),
38
+ timeout=min(http_timeout, max(0.001, deadline - time.monotonic())),
39
+ )
40
+ response.raise_for_status()
41
+ target = next(
42
+ (item for item in response.json().get("artifacts", []) if item["name"] == artifact_name),
43
+ None,
44
+ )
45
+ if target:
46
+ break
47
+ time.sleep(min(2, max(0, deadline - time.monotonic())))
48
+ if not target:
49
+ raise TimeoutError(f"No {artifact_name} artifact found before the deadline")
50
+
51
+ if time.monotonic() >= deadline:
52
+ raise TimeoutError("Timed out before downloading the result artifact")
53
+ response = requests.get(
54
+ f"{API}/repos/{username}/{repo_name}/actions/artifacts/{target['id']}/zip",
55
+ headers=_headers(token),
56
+ allow_redirects=True,
57
+ timeout=min(http_timeout, max(0.001, deadline - time.monotonic())),
58
+ )
59
+ response.raise_for_status()
60
+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:
61
+ name = "result.json" if "result.json" in archive.namelist() else None
62
+ if not name:
63
+ raise RuntimeError(f"result.json not found in artifact. Contents: {archive.namelist()}")
64
+ data = json.loads(archive.read(name).decode("utf-8"))
65
+
66
+ if data.get("job_id") != job_id or data.get("correlation_id") != correlation_id:
67
+ raise IntegrityError("Result identity does not match the requested job", run_id=run_id)
68
+ integrity = data.get("integrity") or {}
69
+ if integrity.get("algorithm") != "sha256":
70
+ raise IntegrityError("Result uses an unsupported integrity algorithm", run_id=run_id)
71
+ actual_output_sha256 = text_sha256(data.get("output", ""))
72
+ if integrity.get("output_sha256") != actual_output_sha256:
73
+ raise IntegrityError("Result output checksum verification failed", run_id=run_id)
74
+ if expected_request_sha256 and integrity.get("request_sha256") != expected_request_sha256:
75
+ raise IntegrityError("Result request checksum verification failed", run_id=run_id)
76
+ if "agent" in data:
77
+ actual_agent_sha256 = text_sha256(json.dumps(data["agent"], sort_keys=True, separators=(",", ":")))
78
+ if integrity.get("agent_sha256") != actual_agent_sha256:
79
+ raise IntegrityError("Agent result checksum verification failed", run_id=run_id)
80
+
81
+ if data.get("error"):
82
+ raise IntegrityError("Worker reported an unsuccessful inference", run_id=run_id)
83
+
84
+ usage = data.get("usage") or {}
85
+ resources = data.get("resources") or {}
86
+ return InferenceResult(
87
+ job_id=job_id,
88
+ correlation_id=correlation_id,
89
+ run_id=run_id,
90
+ output=data.get("output", ""),
91
+ model=data.get("model", ""),
92
+ provider=data.get("provider", "local"),
93
+ usage=TokenUsage(
94
+ prompt_tokens=int(usage.get("prompt_tokens", 0)),
95
+ completion_tokens=int(usage.get("completion_tokens", 0)),
96
+ total_tokens=int(usage.get("total_tokens", 0)),
97
+ ),
98
+ resources=ResourceUsage(**{
99
+ field: resources.get(field, default)
100
+ for field, default in {
101
+ "cpu_count": 0,
102
+ "memory_total_bytes": 0,
103
+ "memory_available_bytes": 0,
104
+ "disk_total_bytes": 0,
105
+ "disk_free_bytes": 0,
106
+ "peak_memory_bytes": 0,
107
+ "duration_seconds": 0.0,
108
+ "runner_os": "",
109
+ }.items()
110
+ }),
111
+ integrity=IntegrityInfo(
112
+ algorithm=integrity.get("algorithm", "sha256"),
113
+ request_sha256=integrity.get("request_sha256", ""),
114
+ output_sha256=integrity.get("output_sha256", ""),
115
+ ),
116
+ raw=data,
117
+ )
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)))