genai-forge 0.1.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.
Potentially problematic release.
This version of genai-forge might be problematic. Click here for more details.
- genai_forge/__init__.py +23 -0
- genai_forge/chain.py +87 -0
- genai_forge/llm/__init__.py +7 -0
- genai_forge/llm/base.py +62 -0
- genai_forge/llm/registry.py +84 -0
- genai_forge/parsing/__init__.py +14 -0
- genai_forge/parsing/output_parser.py +151 -0
- genai_forge/prompting/__init__.py +6 -0
- genai_forge/prompting/prompt.py +93 -0
- genai_forge/providers/__init__.py +6 -0
- genai_forge/providers/openai.py +48 -0
- genai_forge-0.1.2.dist-info/METADATA +146 -0
- genai_forge-0.1.2.dist-info/RECORD +15 -0
- genai_forge-0.1.2.dist-info/WHEEL +4 -0
- genai_forge-0.1.2.dist-info/licenses/LICENSE +201 -0
genai_forge/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .llm.registry import create_llm
|
|
2
|
+
from .parsing import (
|
|
3
|
+
OutputParserException,
|
|
4
|
+
BaseOutputParser,
|
|
5
|
+
PydanticOutputParser,
|
|
6
|
+
)
|
|
7
|
+
from .prompting import PromptTemplate, ChatPrompt
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"create_llm",
|
|
11
|
+
"OutputParserException",
|
|
12
|
+
"BaseOutputParser",
|
|
13
|
+
"PydanticOutputParser",
|
|
14
|
+
"PromptTemplate",
|
|
15
|
+
"ChatPrompt",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
# Ensure providers register themselves at import time
|
|
19
|
+
# Importing the module triggers the @register_llm decorators.
|
|
20
|
+
from . import providers as _providers # noqa: F401
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
genai_forge/chain.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from .parsing import BaseOutputParser
|
|
6
|
+
from .prompting import PromptTemplate, ChatPrompt
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Chain:
|
|
10
|
+
"""
|
|
11
|
+
Sequential executor for prompt -> llm -> parser compositions.
|
|
12
|
+
Auto-injects parser format instructions into the prompt template if a parser
|
|
13
|
+
is present as the final step.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, steps: List[Any]) -> None:
|
|
17
|
+
self._steps = steps
|
|
18
|
+
|
|
19
|
+
def __or__(self, other: Any) -> "Chain":
|
|
20
|
+
return Chain(self._steps + [other])
|
|
21
|
+
|
|
22
|
+
def __call__(self, user_input: Optional[Any] = None) -> Any:
|
|
23
|
+
steps = list(self._steps)
|
|
24
|
+
|
|
25
|
+
# Support a leading embedded input value if the chain was started with `query | ...`
|
|
26
|
+
initial_input = None
|
|
27
|
+
if steps and isinstance(steps[0], _InputValue):
|
|
28
|
+
initial_input = steps.pop(0).value
|
|
29
|
+
|
|
30
|
+
# Resolve current input by merging initial embedded input with provided input
|
|
31
|
+
current: Any
|
|
32
|
+
if user_input is None:
|
|
33
|
+
current = initial_input
|
|
34
|
+
else:
|
|
35
|
+
if isinstance(initial_input, dict) and isinstance(user_input, dict):
|
|
36
|
+
merged: Dict[str, Any] = {**initial_input, **user_input}
|
|
37
|
+
current = merged
|
|
38
|
+
else:
|
|
39
|
+
current = user_input
|
|
40
|
+
parser: Optional[BaseOutputParser] = None
|
|
41
|
+
if steps and isinstance(steps[-1], BaseOutputParser):
|
|
42
|
+
parser = steps[-1]
|
|
43
|
+
|
|
44
|
+
instructions: Optional[str] = None
|
|
45
|
+
if parser is not None:
|
|
46
|
+
instructions = parser.get_format_instructions()
|
|
47
|
+
|
|
48
|
+
current: Any = user_input
|
|
49
|
+
for idx, step in enumerate(steps):
|
|
50
|
+
if isinstance(step, PromptTemplate):
|
|
51
|
+
current = step(current, instructions=instructions)
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
# LLM-like step: expects ChatPrompt or str; returns str
|
|
55
|
+
# Delay parsing to parser step only
|
|
56
|
+
if hasattr(step, "__call__") and not isinstance(step, BaseOutputParser):
|
|
57
|
+
current = step(current)
|
|
58
|
+
continue
|
|
59
|
+
|
|
60
|
+
if isinstance(step, BaseOutputParser):
|
|
61
|
+
current = step.parse(str(current))
|
|
62
|
+
continue
|
|
63
|
+
|
|
64
|
+
raise TypeError(f"Unsupported chain step at index {idx}: {type(step)}")
|
|
65
|
+
|
|
66
|
+
return current
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def to_chain(left: Any, right: Any) -> Chain:
|
|
70
|
+
"""
|
|
71
|
+
Helper: combine two steps into a chain.
|
|
72
|
+
"""
|
|
73
|
+
left_chain = left if isinstance(left, Chain) else Chain([left])
|
|
74
|
+
return left_chain | right
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _InputValue:
|
|
78
|
+
"""
|
|
79
|
+
Internal step to embed an initial input value into a chain, enabling
|
|
80
|
+
expressions like: `query | template | llm | parser`.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, value: Any) -> None:
|
|
84
|
+
self.value = value
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
genai_forge/llm/base.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Common LLM interfaces and base class.
|
|
5
|
+
|
|
6
|
+
Exposes:
|
|
7
|
+
- LLM (Protocol): minimal callable interface.
|
|
8
|
+
- BaseLLM (ABC): enforces __call__ and supports piping with parsers via `|`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from abc import ABC, abstractmethod
|
|
12
|
+
from typing import Any, Callable, Protocol, runtime_checkable
|
|
13
|
+
|
|
14
|
+
from genai_forge.chain import Chain, to_chain
|
|
15
|
+
from genai_forge.prompting import ChatPrompt
|
|
16
|
+
from genai_forge.parsing import BaseOutputParser
|
|
17
|
+
|
|
18
|
+
@runtime_checkable
|
|
19
|
+
class LLM(Protocol):
|
|
20
|
+
"""Protocol for any Large Language Model interface."""
|
|
21
|
+
|
|
22
|
+
def __call__(self, prompt: Any) -> str: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class BaseLLM(ABC):
|
|
26
|
+
"""
|
|
27
|
+
Abstract base class for LLMs.
|
|
28
|
+
Responsibilities:
|
|
29
|
+
- Require subclasses to implement `__call__(prompt) -> str`.
|
|
30
|
+
- Provide the `|` operator to compose with a parser/transformer.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def __call__(self, prompt: Any) -> str:
|
|
35
|
+
"""Execute the LLM on the given prompt and return the text output."""
|
|
36
|
+
raise NotImplementedError
|
|
37
|
+
|
|
38
|
+
def __or__(self, other: Any) -> Chain:
|
|
39
|
+
"""
|
|
40
|
+
Compose into a Chain so we can auto-inject parser instructions and
|
|
41
|
+
support PromptTemplate -> LLM -> OutputParser flows.
|
|
42
|
+
"""
|
|
43
|
+
return to_chain(self, other)
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def _normalize_prompt(prompt: Any) -> str:
|
|
47
|
+
"""
|
|
48
|
+
Normalize a prompt to a plain string.
|
|
49
|
+
If `prompt` has `.to_string()`, it will be used; otherwise `str(prompt)`.
|
|
50
|
+
"""
|
|
51
|
+
if hasattr(prompt, "to_string"):
|
|
52
|
+
return str(prompt.to_string())
|
|
53
|
+
# Accept ChatPrompt: convert to string user content (system handled in provider)
|
|
54
|
+
if isinstance(prompt, ChatPrompt):
|
|
55
|
+
# Concatenate system + user text as a plain string fallback
|
|
56
|
+
if prompt.system:
|
|
57
|
+
return f"{prompt.system}\n\n{prompt.user}"
|
|
58
|
+
return prompt.user
|
|
59
|
+
return str(prompt)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Provider registry + LLM factory.
|
|
5
|
+
Exposes:
|
|
6
|
+
- register_llm(provider: str)
|
|
7
|
+
- create_llm(model: str, **kwargs)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from .base import LLM
|
|
13
|
+
|
|
14
|
+
_LLM_REGISTRY: Dict[str, Callable[..., LLM]] = {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def register_llm(provider: str) -> Callable[[Callable[..., LLM]], Callable[..., LLM]]:
|
|
18
|
+
"""
|
|
19
|
+
Decorator to register an LLM provider class or factory.
|
|
20
|
+
Usage:
|
|
21
|
+
@register_llm("openai")
|
|
22
|
+
class OpenAIChatLLM(BaseLLM):
|
|
23
|
+
...
|
|
24
|
+
"""
|
|
25
|
+
prov = provider.lower().strip()
|
|
26
|
+
|
|
27
|
+
def _wrap(cls_or_factory: Callable[..., LLM]) -> Callable[..., LLM]:
|
|
28
|
+
_LLM_REGISTRY[prov] = cls_or_factory
|
|
29
|
+
return cls_or_factory
|
|
30
|
+
|
|
31
|
+
return _wrap
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def create_llm(
|
|
35
|
+
model: str,
|
|
36
|
+
*,
|
|
37
|
+
temperature: float = 0.3,
|
|
38
|
+
api_key: Optional[str] = None,
|
|
39
|
+
provider: Optional[str] = None,
|
|
40
|
+
logger: Any = None,
|
|
41
|
+
) -> LLM:
|
|
42
|
+
"""
|
|
43
|
+
Factory to create an LLM instance from a model string.
|
|
44
|
+
Args:
|
|
45
|
+
model: Either "provider:model_id" (e.g., "openai:chatgpt-4o")
|
|
46
|
+
or just "model_id" (provider inferred/overridden by `provider`).
|
|
47
|
+
temperature: Sampling temperature.
|
|
48
|
+
system_prompt: Optional system message.
|
|
49
|
+
api_key: Optional explicit key override.
|
|
50
|
+
provider: Optional explicit provider if not in `model`.
|
|
51
|
+
logger: Optional logger.
|
|
52
|
+
Returns:
|
|
53
|
+
An initialized LLM instance.
|
|
54
|
+
Raises:
|
|
55
|
+
ValueError: Unknown/unsupported provider.
|
|
56
|
+
"""
|
|
57
|
+
prov, model_id = _split_provider_model(model, provider)
|
|
58
|
+
prov_norm = prov.lower().strip()
|
|
59
|
+
factory = _LLM_REGISTRY.get(prov_norm)
|
|
60
|
+
if factory is None:
|
|
61
|
+
raise ValueError(
|
|
62
|
+
f"Unknown LLM provider '{prov_norm}'. Registered: {sorted(_LLM_REGISTRY.keys())}"
|
|
63
|
+
)
|
|
64
|
+
return factory(model=model_id, temperature=temperature, api_key=api_key, logger=logger)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _split_provider_model(model: str, provider: Optional[str]) -> Tuple[str, str]:
|
|
68
|
+
"""
|
|
69
|
+
Split a model string into (provider, model_id).
|
|
70
|
+
Examples:
|
|
71
|
+
"openai:chatgpt-4o" -> ("openai", "chatgpt-4o")
|
|
72
|
+
"gpt-4.1" + provider="openai" -> ("openai", "gpt-4.1")
|
|
73
|
+
"gpt-4.1" (no provider) -> defaults to ("openai", "gpt-4.1")
|
|
74
|
+
"""
|
|
75
|
+
if ":" in model:
|
|
76
|
+
p, _, m = model.partition(":")
|
|
77
|
+
return p, m
|
|
78
|
+
if provider:
|
|
79
|
+
return provider, model
|
|
80
|
+
# default provider for bare model strings
|
|
81
|
+
return "openai", model
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Dict, Generic, Optional, Tuple, Type, TypeVar
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ValidationError
|
|
8
|
+
|
|
9
|
+
TModel = TypeVar("TModel", bound=BaseModel)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class OutputParserException(Exception):
|
|
13
|
+
"""Raised when parsing the LLM output fails."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BaseOutputParser(Generic[TModel]):
|
|
17
|
+
"""
|
|
18
|
+
Base output parser that validates LLM output against a Pydantic model.
|
|
19
|
+
- Provide `get_format_instructions()` to guide the model to emit valid JSON.
|
|
20
|
+
- Provide `parse(text)` to extract/validate JSON into the Pydantic model.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
model: Type[TModel],
|
|
26
|
+
*,
|
|
27
|
+
strict: bool = True,
|
|
28
|
+
) -> None:
|
|
29
|
+
self._model_type = model
|
|
30
|
+
self._strict = strict
|
|
31
|
+
|
|
32
|
+
def get_format_instructions(self) -> str:
|
|
33
|
+
"""
|
|
34
|
+
Return instructions to include in prompts so the model emits parseable JSON.
|
|
35
|
+
"""
|
|
36
|
+
schema = self._model_type.model_json_schema()
|
|
37
|
+
return (
|
|
38
|
+
"Return ONLY valid JSON, with no extra commentary or code fences.\n"
|
|
39
|
+
"The JSON must conform to this schema:\n"
|
|
40
|
+
f"{json.dumps(schema, indent=2)}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Convenience alias used in some frameworks
|
|
44
|
+
format_instructions = get_format_instructions
|
|
45
|
+
|
|
46
|
+
def parse(self, text: str) -> TModel:
|
|
47
|
+
"""
|
|
48
|
+
Parse and validate the text into the target Pydantic model instance.
|
|
49
|
+
Accepts tolerant inputs: may contain surrounding text or code fences.
|
|
50
|
+
"""
|
|
51
|
+
json_obj = self._extract_json(text)
|
|
52
|
+
try:
|
|
53
|
+
return self._model_type.model_validate(json_obj)
|
|
54
|
+
except ValidationError as e:
|
|
55
|
+
if self._strict:
|
|
56
|
+
raise OutputParserException(f"Validation failed: {e}") from e
|
|
57
|
+
# Non-strict: attempt field-level coercion by dumping/loads again.
|
|
58
|
+
try:
|
|
59
|
+
as_json = json.loads(json.dumps(json_obj))
|
|
60
|
+
return self._model_type.model_validate(as_json)
|
|
61
|
+
except Exception as e2:
|
|
62
|
+
raise OutputParserException(f"Coercion failed: {e2}") from e2
|
|
63
|
+
|
|
64
|
+
# ---------- internal helpers ----------
|
|
65
|
+
_FENCE_RE = re.compile(r"^```(?:json)?\s*([\s\S]*?)\s*```$", re.IGNORECASE)
|
|
66
|
+
|
|
67
|
+
def _extract_json(self, text: str) -> Dict[str, Any]:
|
|
68
|
+
"""
|
|
69
|
+
Extract a JSON object from the model output.
|
|
70
|
+
Strategy:
|
|
71
|
+
1) Trim and strip common markdown JSON code-fences.
|
|
72
|
+
2) Try json.loads directly.
|
|
73
|
+
3) Fallback: find the first balanced {...} block and parse it.
|
|
74
|
+
"""
|
|
75
|
+
candidate = text.strip()
|
|
76
|
+
|
|
77
|
+
# 1) Try to unwrap fenced code blocks ─ e.g. ```json { ... } ```
|
|
78
|
+
fenced = self._maybe_unwrap_fence(candidate)
|
|
79
|
+
if fenced is not None:
|
|
80
|
+
candidate = fenced
|
|
81
|
+
|
|
82
|
+
# 2) Direct attempt
|
|
83
|
+
try:
|
|
84
|
+
loaded = json.loads(candidate)
|
|
85
|
+
if isinstance(loaded, dict):
|
|
86
|
+
return loaded
|
|
87
|
+
except Exception:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
# 3) Fallback: find balanced JSON object
|
|
91
|
+
obj_str = self._find_first_balanced_object(candidate)
|
|
92
|
+
if obj_str is None:
|
|
93
|
+
raise OutputParserException("No JSON object found in output.")
|
|
94
|
+
try:
|
|
95
|
+
loaded = json.loads(obj_str)
|
|
96
|
+
if isinstance(loaded, dict):
|
|
97
|
+
return loaded
|
|
98
|
+
except Exception as e:
|
|
99
|
+
raise OutputParserException(f"Invalid JSON content: {e}") from e
|
|
100
|
+
raise OutputParserException("Parsed JSON is not an object.")
|
|
101
|
+
|
|
102
|
+
def _maybe_unwrap_fence(self, text: str) -> Optional[str]:
|
|
103
|
+
m = self._FENCE_RE.match(text)
|
|
104
|
+
if m:
|
|
105
|
+
return m.group(1).strip()
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
def _find_first_balanced_object(self, text: str) -> Optional[str]:
|
|
109
|
+
"""
|
|
110
|
+
Find the first balanced {...} substring. Handles nested braces and ignores
|
|
111
|
+
braces inside string literals (simple heuristic).
|
|
112
|
+
"""
|
|
113
|
+
start = -1
|
|
114
|
+
depth = 0
|
|
115
|
+
in_string = False
|
|
116
|
+
escape = False
|
|
117
|
+
for i, ch in enumerate(text):
|
|
118
|
+
if in_string:
|
|
119
|
+
if escape:
|
|
120
|
+
escape = False
|
|
121
|
+
elif ch == "\\":
|
|
122
|
+
escape = True
|
|
123
|
+
elif ch == '"':
|
|
124
|
+
in_string = False
|
|
125
|
+
continue
|
|
126
|
+
else:
|
|
127
|
+
if ch == '"':
|
|
128
|
+
in_string = True
|
|
129
|
+
continue
|
|
130
|
+
if ch == "{":
|
|
131
|
+
if depth == 0:
|
|
132
|
+
start = i
|
|
133
|
+
depth += 1
|
|
134
|
+
elif ch == "}":
|
|
135
|
+
if depth > 0:
|
|
136
|
+
depth -= 1
|
|
137
|
+
if depth == 0 and start != -1:
|
|
138
|
+
return text[start : i + 1]
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class PydanticOutputParser(BaseOutputParser[TModel]):
|
|
143
|
+
"""
|
|
144
|
+
Concrete parser. Alias of BaseOutputParser for clarity/ergonomics.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(self, model: Type[TModel], *, strict: bool = True) -> None:
|
|
148
|
+
super().__init__(model=model, strict=strict)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class ChatPrompt:
|
|
9
|
+
"""
|
|
10
|
+
Minimal chat prompt representation.
|
|
11
|
+
"""
|
|
12
|
+
system: Optional[str]
|
|
13
|
+
user: str
|
|
14
|
+
|
|
15
|
+
def to_messages(self) -> list[dict]:
|
|
16
|
+
messages: list[dict] = []
|
|
17
|
+
if self.system:
|
|
18
|
+
messages.append({"role": "system", "content": self.system})
|
|
19
|
+
messages.append({"role": "user", "content": self.user})
|
|
20
|
+
return messages
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PromptTemplate:
|
|
24
|
+
"""
|
|
25
|
+
Simple Python format-based prompt template with a single system prompt string,
|
|
26
|
+
and a user template string.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, *, system: Optional[str], template: str) -> None:
|
|
30
|
+
self._system = system
|
|
31
|
+
self._template = template
|
|
32
|
+
|
|
33
|
+
def __or__(self, other: Any):
|
|
34
|
+
from genai_forge.chain import Chain # local import to avoid cycle
|
|
35
|
+
return Chain([self]) | other
|
|
36
|
+
|
|
37
|
+
def __ror__(self, left: Any):
|
|
38
|
+
"""
|
|
39
|
+
Enable chaining from a raw query or variables dictionary:
|
|
40
|
+
"some question" | template | llm | parser
|
|
41
|
+
"""
|
|
42
|
+
from genai_forge.chain import Chain, _InputValue # local import to avoid cycle
|
|
43
|
+
return Chain([_InputValue(_normalize_left(left)), self])
|
|
44
|
+
|
|
45
|
+
def format(self, variables: Any, *, instructions: Optional[str] = None) -> ChatPrompt:
|
|
46
|
+
"""
|
|
47
|
+
Format the template with variables. If variables is not a mapping, it will
|
|
48
|
+
be available as the 'input' variable. If instructions are provided, they
|
|
49
|
+
are appended to the user content automatically.
|
|
50
|
+
"""
|
|
51
|
+
context: Dict[str, Any]
|
|
52
|
+
if isinstance(variables, dict):
|
|
53
|
+
context = dict(variables)
|
|
54
|
+
else:
|
|
55
|
+
# Treat raw input as the user's query
|
|
56
|
+
context = {"query": variables}
|
|
57
|
+
|
|
58
|
+
user_text = self._template.format(**context)
|
|
59
|
+
|
|
60
|
+
# Ensure the raw user query is present even if not in the template
|
|
61
|
+
if "query" in context and "{query}" not in self._template:
|
|
62
|
+
q = str(context["query"]).strip()
|
|
63
|
+
if q:
|
|
64
|
+
if user_text.strip():
|
|
65
|
+
user_text = f"{user_text.rstrip()}\n\n{q}"
|
|
66
|
+
else:
|
|
67
|
+
user_text = q
|
|
68
|
+
|
|
69
|
+
# Automatically include parser instructions if present
|
|
70
|
+
if instructions:
|
|
71
|
+
user_text = f"{user_text.rstrip()}\n\n{instructions}"
|
|
72
|
+
|
|
73
|
+
return ChatPrompt(system=self._system, user=user_text)
|
|
74
|
+
|
|
75
|
+
def __call__(self, variables: Any, *, instructions: Optional[str] = None) -> ChatPrompt:
|
|
76
|
+
return self.format(variables, instructions=instructions)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _normalize_left(left: Any) -> Any:
|
|
80
|
+
"""
|
|
81
|
+
Normalize left operand value when starting a chain with `query | template`.
|
|
82
|
+
- str -> {"query": str}
|
|
83
|
+
- dict -> dict (unchanged)
|
|
84
|
+
- other -> {"query": str(value)}
|
|
85
|
+
"""
|
|
86
|
+
if isinstance(left, dict):
|
|
87
|
+
return left
|
|
88
|
+
if isinstance(left, str):
|
|
89
|
+
return {"query": left}
|
|
90
|
+
return {"query": str(left)}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
|
|
6
|
+
from dotenv import load_dotenv
|
|
7
|
+
from openai import OpenAI
|
|
8
|
+
|
|
9
|
+
from genai_forge.llm.base import BaseLLM
|
|
10
|
+
from genai_forge.llm.registry import register_llm
|
|
11
|
+
from genai_forge.prompting import ChatPrompt
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@register_llm("openai")
|
|
15
|
+
class OpenAIChatLLM(BaseLLM):
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
*,
|
|
19
|
+
model: str,
|
|
20
|
+
temperature: float = 0.3,
|
|
21
|
+
api_key: Optional[str] = None,
|
|
22
|
+
logger: Any = None,
|
|
23
|
+
) -> None:
|
|
24
|
+
load_dotenv()
|
|
25
|
+
key = api_key or os.getenv("OPENAI_API_KEY")
|
|
26
|
+
# Client can also read key from env automatically, but we pass it if present
|
|
27
|
+
self._client = OpenAI(api_key=key) if key else OpenAI()
|
|
28
|
+
self._model = model
|
|
29
|
+
self._temperature = float(temperature)
|
|
30
|
+
self._logger = logger
|
|
31
|
+
|
|
32
|
+
def __call__(self, prompt: Any) -> str:
|
|
33
|
+
if isinstance(prompt, ChatPrompt):
|
|
34
|
+
messages = prompt.to_messages()
|
|
35
|
+
else:
|
|
36
|
+
# Fallback: treat as plain user text
|
|
37
|
+
content = self._normalize_prompt(prompt)
|
|
38
|
+
messages = [{"role": "user", "content": content}]
|
|
39
|
+
resp = self._client.chat.completions.create(
|
|
40
|
+
model=self._model,
|
|
41
|
+
messages=messages, # type: ignore[arg-type]
|
|
42
|
+
temperature=self._temperature,
|
|
43
|
+
)
|
|
44
|
+
message = resp.choices[0].message.content or ""
|
|
45
|
+
return message
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: genai-forge
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Generative AI tools from ToolForge-AI organization
|
|
5
|
+
Project-URL: Homepage, https://github.com/ToolForge-AI/genai-forge
|
|
6
|
+
Project-URL: Repository, https://github.com/ToolForge-AI/genai-forge
|
|
7
|
+
Project-URL: Issues, https://github.com/your-org/ToolForge-AI/issues
|
|
8
|
+
Author-email: Daniel Aguilera <daniel.aguilera@toolforge-ai.com>
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Requires-Dist: openai>=2.7.1
|
|
12
|
+
Requires-Dist: pydantic>=2.5.0
|
|
13
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# genai-forge
|
|
17
|
+
|
|
18
|
+
Lightweight utilities to call LLMs and parse their outputs with Pydantic.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
Install from PyPI:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install genai-forge
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Or from TestPyPI (for pre-releases):
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install --index-url https://pypi.org/simple genai-forge
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Requirements
|
|
35
|
+
|
|
36
|
+
- Python 3.10+
|
|
37
|
+
- An OpenAI API key in your environment:
|
|
38
|
+
- Create a `.env` file at your project root with:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
OPENAI_API_KEY=sk-...
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`genai_forge` will load `.env` automatically via `python-dotenv` when using the OpenAI provider.
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from genai_forge.llm import create_llm
|
|
50
|
+
from genai_forge.prompting import PromptTemplate
|
|
51
|
+
|
|
52
|
+
template = PromptTemplate(
|
|
53
|
+
system="You are a concise expert assistant.",
|
|
54
|
+
template="Generate one actionable tip.\nAudience: {audience}\nTime: {time}",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
llm = create_llm("openai:gpt-4o-mini", temperature=0.2)
|
|
58
|
+
|
|
59
|
+
# Chain: query | template | llm
|
|
60
|
+
query = "Provide a short productivity tip."
|
|
61
|
+
chain = query | template | llm
|
|
62
|
+
print(chain({"audience": "Backend Python developer", "time": "30 minutes"}))
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Parsing structured outputs with Pydantic
|
|
66
|
+
|
|
67
|
+
Use `PydanticOutputParser` to have the LLM return valid JSON that is validated into a Pydantic model. When you add a parser to the chain, the parser’s format instructions are automatically appended to the prompt; you do not need to place `{instructions}` in your template.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from typing import List
|
|
71
|
+
from pydantic import BaseModel
|
|
72
|
+
from genai_forge.llm import create_llm
|
|
73
|
+
from genai_forge import PydanticOutputParser
|
|
74
|
+
from genai_forge.prompting import PromptTemplate
|
|
75
|
+
|
|
76
|
+
class CityPlan(BaseModel):
|
|
77
|
+
city: str
|
|
78
|
+
attractions: List[str]
|
|
79
|
+
days: int
|
|
80
|
+
|
|
81
|
+
template = PromptTemplate(
|
|
82
|
+
system="You are a helpful travel planner.",
|
|
83
|
+
template="Create a city plan.\nCity: {city}\nDays: {days}",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
llm = create_llm("openai:gpt-4o-mini", temperature=0.1)
|
|
87
|
+
parser = PydanticOutputParser(CityPlan)
|
|
88
|
+
|
|
89
|
+
# Chain: query | template | llm | parser
|
|
90
|
+
query = "Create a 2-day city plan for Kyoto."
|
|
91
|
+
chain = query | template | llm | parser
|
|
92
|
+
result = chain({"city": "Kyoto", "days": 2}) # -> CityPlan
|
|
93
|
+
print(result)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### What chaining does
|
|
97
|
+
|
|
98
|
+
The `|` operator builds a Chain:
|
|
99
|
+
- `template | llm` produces a function that formats the prompt (system + user) and calls the LLM.
|
|
100
|
+
- `template | llm | parser` also injects the parser's format instructions automatically into the prompt and validates the output.
|
|
101
|
+
|
|
102
|
+
## Output parser: how it works
|
|
103
|
+
|
|
104
|
+
`PydanticOutputParser`:
|
|
105
|
+
- Accepts tolerant output formats (e.g., extra text or ```json fences).
|
|
106
|
+
- Extracts JSON from the text (tries direct parse, then finds the first balanced `{...}` block).
|
|
107
|
+
- Validates the JSON against your Pydantic model.
|
|
108
|
+
- Provides `get_format_instructions()`; the Chain appends it for you when a parser is present.
|
|
109
|
+
|
|
110
|
+
API surface:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from genai_forge import PydanticOutputParser, BaseOutputParser, OutputParserException
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Key methods:
|
|
117
|
+
- `get_format_instructions() -> str`: Include in your prompt.
|
|
118
|
+
- `parse(text: str) -> BaseModel`: Parse and validate output.
|
|
119
|
+
|
|
120
|
+
## Provider configuration
|
|
121
|
+
|
|
122
|
+
By default, models without an explicit provider use `openai`. You can specify:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
create_llm("openai:gpt-4o-mini")
|
|
126
|
+
# or
|
|
127
|
+
create_llm("gpt-4.1", provider="openai")
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The OpenAI provider reads the key from `OPENAI_API_KEY` (or `api_key` argument).
|
|
131
|
+
|
|
132
|
+
## Running the example
|
|
133
|
+
|
|
134
|
+
An `example.py` is included at the repo root. It demonstrates:
|
|
135
|
+
- A chain: user input → PromptTemplate (with system prompt) → LLM → PydanticOutputParser
|
|
136
|
+
- Automatic format instructions injection
|
|
137
|
+
|
|
138
|
+
Ensure you have a `.env` with `OPENAI_API_KEY`, then:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
python example.py
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
See `LICENSE`.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
genai_forge/__init__.py,sha256=CZ5QGhR2_VuBOitIkMTxdnUi1VyB_mZ4xEUIL3Xd5fg,513
|
|
2
|
+
genai_forge/chain.py,sha256=HgX_0V1x8jVIH6H6jqxe8N2vlysekTllvZBHpqTuqiM,2757
|
|
3
|
+
genai_forge/llm/__init__.py,sha256=0QzApuP-lkO9kWVvu0cGEc7Nfnlbb4ON1cWsYPBDZxc,141
|
|
4
|
+
genai_forge/llm/base.py,sha256=JknTaRjqkUJnuYKhBFYWDj0Di-Q9gwmJmpo3jVQV7kw,1914
|
|
5
|
+
genai_forge/llm/registry.py,sha256=l-skiGbOhY2fK9ghxXRy0sjGN3ZE0VXoM8YlSIjP76s,2456
|
|
6
|
+
genai_forge/parsing/__init__.py,sha256=ofwkLD78qmHhAW_ymTatnInCwrB0ZGxnZRI6RQx_F0E,205
|
|
7
|
+
genai_forge/parsing/output_parser.py,sha256=3gMDyfwL0VCTpcrDIfhjgKm2p6RdqFqw2o3BtYK68cQ,5054
|
|
8
|
+
genai_forge/prompting/__init__.py,sha256=7OfIT0lyogvY2PRyhq4lmy1aq9kcNKh8A1pLIep-PW0,94
|
|
9
|
+
genai_forge/prompting/prompt.py,sha256=AHJZNXlxZEhT32oUyD7w034VwrA4X9jxK5GjTywXJq0,3008
|
|
10
|
+
genai_forge/providers/__init__.py,sha256=6ZY50483mYp-jRINEo2Daoc-QG7h_TUuLbeZ9olFQNw,66
|
|
11
|
+
genai_forge/providers/openai.py,sha256=2j3kVcwl3182uBPKmboIVZTSgf1x3GYD9s8QWDw0haI,1424
|
|
12
|
+
genai_forge-0.1.2.dist-info/METADATA,sha256=BQ9q9XrryEGhwSCBYfB4TknDOK-LN0DhqRbNoEyMHd0,4202
|
|
13
|
+
genai_forge-0.1.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
14
|
+
genai_forge-0.1.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
15
|
+
genai_forge-0.1.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|