prompty 0.1.7__py3-none-any.whl → 0.1.9__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
prompty/core.py CHANGED
@@ -6,9 +6,9 @@ import yaml
6
6
  import json
7
7
  import abc
8
8
  from pathlib import Path
9
+ from .tracer import Tracer, trace, to_dict
9
10
  from pydantic import BaseModel, Field, FilePath
10
- from typing import List, Literal, Dict, Callable, Set, TypeVar
11
- from .tracer import trace
11
+ from typing import Iterator, List, Literal, Dict, Callable, Set
12
12
 
13
13
 
14
14
  class PropertySettings(BaseModel):
@@ -449,3 +449,33 @@ class Frontmatter:
449
449
  "body": body,
450
450
  "frontmatter": fmatter,
451
451
  }
452
+
453
+
454
+ class PromptyStream(Iterator):
455
+ """PromptyStream class to iterate over LLM stream.
456
+ Necessary for Prompty to handle streaming data when tracing."""
457
+
458
+ def __init__(self, name: str, iterator: Iterator):
459
+ self.name = name
460
+ self.iterator = iterator
461
+ self.items: List[any] = []
462
+ self.__name__ = "PromptyStream"
463
+
464
+ def __iter__(self):
465
+ return self
466
+
467
+ def __next__(self):
468
+ try:
469
+ # enumerate but add to list
470
+ o = self.iterator.__next__()
471
+ self.items.append(o)
472
+ return o
473
+
474
+ except StopIteration:
475
+ # StopIteration is raised
476
+ # contents are exhausted
477
+ if len(self.items) > 0:
478
+ with Tracer.start(f"{self.name}.PromptyStream") as trace:
479
+ trace("items", [to_dict(s) for s in self.items])
480
+
481
+ raise StopIteration
prompty/executors.py CHANGED
@@ -1,8 +1,8 @@
1
1
  import azure.identity
2
- from .tracer import Trace
3
- from openai import AzureOpenAI
4
- from .core import Invoker, InvokerFactory, Prompty
5
2
  import importlib.metadata
3
+ from typing import Iterator
4
+ from openai import AzureOpenAI
5
+ from .core import Invoker, InvokerFactory, Prompty, PromptyStream
6
6
 
7
7
  VERSION = importlib.metadata.version("prompty")
8
8
 
@@ -87,9 +87,8 @@ class AzureOpenAIExecutor(Invoker):
87
87
  elif self.api == "image":
88
88
  raise NotImplementedError("Azure OpenAI Image API is not implemented yet")
89
89
 
90
- if hasattr(response, "usage") and response.usage:
91
- Trace.add("completion_tokens", response.usage.completion_tokens)
92
- Trace.add("prompt_tokens", response.usage.prompt_tokens)
93
- Trace.add("total_tokens", response.usage.total_tokens)
94
-
95
- return response
90
+ # stream response
91
+ if isinstance(response, Iterator):
92
+ return PromptyStream("AzureOpenAIExecutor", response)
93
+ else:
94
+ return response
prompty/processors.py CHANGED
@@ -1,10 +1,8 @@
1
- from .tracer import Trace
2
- from openai import Stream
3
1
  from typing import Iterator
4
2
  from pydantic import BaseModel
5
3
  from openai.types.completion import Completion
6
- from .core import Invoker, InvokerFactory, Prompty
7
4
  from openai.types.chat.chat_completion import ChatCompletion
5
+ from .core import Invoker, InvokerFactory, Prompty, PromptyStream
8
6
  from openai.types.create_embedding_response import CreateEmbeddingResponse
9
7
 
10
8
 
@@ -66,9 +64,8 @@ class OpenAIProcessor(Invoker):
66
64
  for chunk in data:
67
65
  if len(chunk.choices) == 1 and chunk.choices[0].delta.content != None:
68
66
  content = chunk.choices[0].delta.content
69
- Trace.add("stream", content)
70
67
  yield content
71
68
 
72
- return generator()
69
+ return PromptyStream("OpenAIProcessor", generator())
73
70
  else:
74
71
  return data
prompty/tracer.py CHANGED
@@ -1,197 +1,200 @@
1
- import abc
1
+ import os
2
2
  import json
3
3
  import inspect
4
- import datetime
4
+ import contextlib
5
+ from pathlib import Path
5
6
  from numbers import Number
6
- import os
7
7
  from datetime import datetime
8
- from pathlib import Path
9
8
  from pydantic import BaseModel
10
9
  from functools import wraps, partial
11
- from typing import Any, Callable, Dict, List
12
-
13
-
14
- class Tracer(abc.ABC):
10
+ from typing import Any, Callable, Dict, Iterator, List
15
11
 
16
- @abc.abstractmethod
17
- def start(self, name: str) -> None:
18
- pass
19
12
 
20
- @abc.abstractmethod
21
- def add(self, key: str, value: Any) -> None:
22
- pass
23
-
24
- @abc.abstractmethod
25
- def end(self) -> None:
26
- pass
27
-
28
-
29
- class Trace:
30
- _tracers: Dict[str, Tracer] = {}
13
+ class Tracer:
14
+ _tracers: Dict[str, Callable[[str], Iterator[Callable[[str, Any], None]]]] = {}
31
15
 
32
16
  @classmethod
33
- def add_tracer(cls, name: str, tracer: Tracer) -> None:
17
+ def add(
18
+ cls, name: str, tracer: Callable[[str], Iterator[Callable[[str, Any], None]]]
19
+ ) -> None:
34
20
  cls._tracers[name] = tracer
35
21
 
36
- @classmethod
37
- def start(cls, name: str) -> None:
38
- for tracer in cls._tracers.values():
39
- tracer.start(name)
40
-
41
- @classmethod
42
- def add(cls, name: str, value: Any) -> None:
43
- for tracer in cls._tracers.values():
44
- tracer.add(name, value)
45
-
46
- @classmethod
47
- def end(cls) -> None:
48
- for tracer in cls._tracers.values():
49
- tracer.end()
50
-
51
22
  @classmethod
52
23
  def clear(cls) -> None:
53
24
  cls._tracers = {}
54
25
 
55
26
  @classmethod
56
- def register(cls, name: str):
57
- def inner_wrapper(wrapped_class: Tracer) -> Callable:
58
- cls._tracers[name] = wrapped_class()
59
- return wrapped_class
60
-
61
- return inner_wrapper
62
-
63
- @classmethod
64
- def to_dict(cls, obj: Any) -> Dict[str, Any]:
65
- # simple json types
66
- if isinstance(obj, str) or isinstance(obj, Number) or isinstance(obj, bool):
67
- return obj
68
- # datetime
69
- elif isinstance(obj, datetime):
70
- return obj.isoformat()
71
- # safe Prompty obj serialization
72
- elif type(obj).__name__ == "Prompty":
73
- return obj.to_safe_dict()
74
- # pydantic models have their own json serialization
75
- elif isinstance(obj, BaseModel):
76
- return obj.model_dump()
77
- # recursive list and dict
78
- elif isinstance(obj, list):
79
- return [Trace.to_dict(item) for item in obj]
80
- elif isinstance(obj, dict):
81
- return {
82
- k: v if isinstance(v, str) else Trace.to_dict(v)
83
- for k, v in obj.items()
84
- }
85
- elif isinstance(obj, Path):
86
- return str(obj)
87
- # cast to string otherwise...
88
- else:
89
- return str(obj)
90
-
91
-
92
- def trace(func: Callable = None, *, description: str = None) -> Callable:
93
- if func is None:
94
- return partial(trace, description=description)
95
-
27
+ @contextlib.contextmanager
28
+ def start(cls, name: str) -> Iterator[Callable[[str, Any], None]]:
29
+ with contextlib.ExitStack() as stack:
30
+ traces = [
31
+ stack.enter_context(tracer(name)) for tracer in cls._tracers.values()
32
+ ]
33
+ yield lambda key, value: [trace(key, value) for trace in traces]
34
+
35
+
36
+ def to_dict(obj: Any) -> Dict[str, Any]:
37
+ # simple json types
38
+ if isinstance(obj, str) or isinstance(obj, Number) or isinstance(obj, bool):
39
+ return obj
40
+ # datetime
41
+ elif isinstance(obj, datetime):
42
+ return obj.isoformat()
43
+ # safe Prompty obj serialization
44
+ elif type(obj).__name__ == "Prompty":
45
+ return obj.to_safe_dict()
46
+ # safe PromptyStream obj serialization
47
+ elif type(obj).__name__ == "PromptyStream":
48
+ return "PromptyStream"
49
+ # pydantic models have their own json serialization
50
+ elif isinstance(obj, BaseModel):
51
+ return obj.model_dump()
52
+ # recursive list and dict
53
+ elif isinstance(obj, list):
54
+ return [to_dict(item) for item in obj]
55
+ elif isinstance(obj, dict):
56
+ return {k: v if isinstance(v, str) else to_dict(v) for k, v in obj.items()}
57
+ elif isinstance(obj, Path):
58
+ return str(obj)
59
+ # cast to string otherwise...
60
+ else:
61
+ return str(obj)
62
+
63
+
64
+ def _name(func: Callable, args):
65
+ if hasattr(func, "__qualname__"):
66
+ signature = f"{func.__module__}.{func.__qualname__}"
67
+ else:
68
+ signature = f"{func.__module__}.{func.__name__}"
69
+
70
+ # core invoker gets special treatment
71
+ core_invoker = signature == "prompty.core.Invoker.__call__"
72
+ if core_invoker:
73
+ name = type(args[0]).__name__
74
+ signature = f"{args[0].__module__}.{args[0].__class__.__name__}.invoke"
75
+ else:
76
+ name = func.__name__
77
+
78
+ return name, signature
79
+
80
+
81
+ def _inputs(func: Callable, args, kwargs) -> dict:
82
+ ba = inspect.signature(func).bind(*args, **kwargs)
83
+ ba.apply_defaults()
84
+
85
+ inputs = {k: to_dict(v) for k, v in ba.arguments.items() if k != "self"}
86
+
87
+ return inputs
88
+
89
+
90
+ def _results(result: Any) -> dict:
91
+ return to_dict(result) if result is not None else "None"
92
+
93
+
94
+ def _trace_sync(func: Callable = None, *, description: str = None) -> Callable:
96
95
  description = description or ""
97
96
 
98
97
  @wraps(func)
99
98
  def wrapper(*args, **kwargs):
100
- if hasattr(func, "__qualname__"):
101
- signature = f"{func.__module__}.{func.__qualname__}"
102
- else:
103
- signature = f"{func.__module__}.{func.__name__}"
99
+ name, signature = _name(func, args)
100
+ with Tracer.start(name) as trace:
101
+ trace("signature", signature)
102
+ if description and description != "":
103
+ trace("description", description)
104
104
 
105
- # core invoker gets special treatment
106
- core_invoker = signature == "prompty.core.Invoker.__call__"
107
- if core_invoker:
108
- name = type(args[0]).__name__
109
- else:
110
- name = func.__name__
105
+ inputs = _inputs(func, args, kwargs)
106
+ trace("inputs", inputs)
111
107
 
112
- Trace.start(name)
108
+ result = func(*args, **kwargs)
109
+ trace("result", _results(result))
113
110
 
114
- if core_invoker:
115
- Trace.add(
116
- "signature",
117
- f"{args[0].__module__}.{args[0].__class__.__name__}.invoke",
118
- )
119
- else:
120
- Trace.add("signature", signature)
111
+ return result
121
112
 
122
- if len(description) > 0:
123
- Trace.add("description", description)
113
+ return wrapper
124
114
 
125
- ba = inspect.signature(func).bind(*args, **kwargs)
126
- ba.apply_defaults()
127
115
 
128
- inputs = {k: Trace.to_dict(v) for k, v in ba.arguments.items() if k != "self"}
116
+ def _trace_async(func: Callable = None, *, description: str = None) -> Callable:
117
+ description = description or ""
129
118
 
130
- Trace.add("input", Trace.to_dict(inputs))
131
- result = func(*args, **kwargs)
119
+ @wraps(func)
120
+ async def wrapper(*args, **kwargs):
121
+ name, signature = _name(func, args)
122
+ with Tracer.start(name) as trace:
123
+ trace("signature", signature)
124
+ if description and description != "":
125
+ trace("description", description)
132
126
 
133
- Trace.add(
134
- "result",
135
- Trace.to_dict(result) if result is not None else "None",
136
- )
127
+ inputs = _inputs(func, args, kwargs)
128
+ trace("inputs", inputs)
137
129
 
138
- Trace.end()
130
+ result = await func(*args, **kwargs)
131
+ trace("result", _results(result))
139
132
 
140
- return result
133
+ return result
141
134
 
142
135
  return wrapper
143
136
 
144
137
 
145
- class PromptyTracer(Tracer):
146
- _stack: List[Dict[str, Any]] = []
147
- _name: str = None
138
+ def trace(func: Callable = None, *, description: str = None) -> Callable:
139
+ if func is None:
140
+ return partial(trace, description=description)
148
141
 
149
- def __init__(self, output_dir: str = None) -> None:
150
- super().__init__()
151
- if output_dir:
152
- self.root = Path(output_dir).resolve().absolute()
153
- else:
154
- self.root = Path(Path(os.getcwd()) / ".runs").resolve().absolute()
155
-
156
- if not self.root.exists():
157
- self.root.mkdir(parents=True, exist_ok=True)
158
-
159
- def start(self, name: str) -> None:
160
- self._stack.append({"name": name})
161
- # first entry frame
162
- if self._name is None:
163
- self._name = name
164
-
165
- def add(self, name: str, value: Any) -> None:
166
- frame = self._stack[-1]
167
- if name not in frame:
168
- frame[name] = value
169
- # multiple values creates list
170
- else:
171
- if isinstance(frame[name], list):
172
- frame[name].append(value)
173
- else:
174
- frame[name] = [frame[name], value]
142
+ wrapped_method = _trace_async if inspect.iscoroutinefunction(func) else _trace_sync
175
143
 
144
+ return wrapped_method(func, description=description)
176
145
 
177
- def end(self) -> None:
178
- # pop the current stack
179
- frame = self._stack.pop()
180
146
 
181
- # if stack is empty, dump the frame
182
- if len(self._stack) == 0:
183
- self.flush(frame)
184
- # otherwise, append the frame to the parent
147
+ class PromptyTracer:
148
+ def __init__(self, output_dir: str = None) -> None:
149
+ if output_dir:
150
+ self.output = Path(output_dir).resolve().absolute()
185
151
  else:
186
- if "__frames" not in self._stack[-1]:
187
- self._stack[-1]["__frames"] = []
188
- self._stack[-1]["__frames"].append(frame)
189
-
190
- def flush(self, frame: Dict[str, Any]) -> None:
191
-
192
- trace_file = (
193
- self.root / f"{self._name}.{datetime.now().strftime('%Y%m%d.%H%M%S')}.ptrace"
194
- )
195
-
196
- with open(trace_file, "w") as f:
197
- json.dump(frame, f, indent=4)
152
+ self.output = Path(Path(os.getcwd()) / ".runs").resolve().absolute()
153
+
154
+ if not self.output.exists():
155
+ self.output.mkdir(parents=True, exist_ok=True)
156
+
157
+ self.stack: List[Dict[str, Any]] = []
158
+
159
+ @contextlib.contextmanager
160
+ def tracer(self, name: str) -> Iterator[Callable[[str, Any], None]]:
161
+ try:
162
+ self.stack.append({"name": name})
163
+ frame = self.stack[-1]
164
+
165
+ def add(key: str, value: Any) -> None:
166
+ if key not in frame:
167
+ frame[key] = value
168
+ # multiple values creates list
169
+ else:
170
+ if isinstance(frame[key], list):
171
+ frame[key].append(value)
172
+ else:
173
+ frame[key] = [frame[key], value]
174
+
175
+ yield add
176
+ finally:
177
+ frame = self.stack.pop()
178
+ # if stack is empty, dump the frame
179
+ if len(self.stack) == 0:
180
+ trace_file = (
181
+ self.output
182
+ / f"{frame['name']}.{datetime.now().strftime('%Y%m%d.%H%M%S')}.ptrace"
183
+ )
184
+
185
+ with open(trace_file, "w") as f:
186
+ json.dump(frame, f, indent=4)
187
+ # otherwise, append the frame to the parent
188
+ else:
189
+ if "__frames" not in self.stack[-1]:
190
+ self.stack[-1]["__frames"] = []
191
+ self.stack[-1]["__frames"].append(frame)
192
+
193
+
194
+ @contextlib.contextmanager
195
+ def console_tracer(name: str) -> Iterator[Callable[[str, Any], None]]:
196
+ try:
197
+ print(f"Starting {name}")
198
+ yield lambda key, value: print(f"{key}:\n{json.dumps(value, indent=4)}")
199
+ finally:
200
+ print(f"Ending {name}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: prompty
3
- Version: 0.1.7
3
+ Version: 0.1.9
4
4
  Summary: Prompty is a new asset class and format for LLM prompts that aims to provide observability, understandability, and portability for developers. It includes spec, tooling, and a runtime. This Prompty runtime supports Python
5
5
  Author-Email: Seth Juarez <seth.juarez@microsoft.com>
6
6
  License: MIT
@@ -15,7 +15,7 @@ Requires-Dist: click>=8.1.7
15
15
  Description-Content-Type: text/markdown
16
16
 
17
17
 
18
- Prompty is an asset class and format for LLM prompts designed to enhance observability, understandability, and portability for developers. The primary goal is to accelerate the developer inner loop of prompt engineering and prompt source management in a cross-language and cross-platform implentation.
18
+ Prompty is an asset class and format for LLM prompts designed to enhance observability, understandability, and portability for developers. The primary goal is to accelerate the developer inner loop of prompt engineering and prompt source management in a cross-language and cross-platform implementation.
19
19
 
20
20
  The file format has a supporting toolchain with a VS Code extension and runtimes in multiple programming languages to simplify and accelerate your AI application development.
21
21
 
@@ -133,4 +133,4 @@ prompty -s path/to/prompty/file
133
133
  This will execute the prompt and print the response to the console. It also has default tracing enabled.
134
134
 
135
135
  ## Contributing
136
- We welcome contributions to the Prompty project! This community led project is open to all contributors. The project cvan be found on [GitHub](https://github.com/Microsoft/prompty).
136
+ We welcome contributions to the Prompty project! This community led project is open to all contributors. The project cvan be found on [GitHub](https://github.com/Microsoft/prompty).
@@ -0,0 +1,12 @@
1
+ prompty-0.1.9.dist-info/METADATA,sha256=6YLGAUn8xPP0LW4VEGKpsYesMAIrx5usRw7ToD8CvkI,4668
2
+ prompty-0.1.9.dist-info/WHEEL,sha256=rSwsxJWe3vzyR5HCwjWXQruDgschpei4h_giTm0dJVE,90
3
+ prompty-0.1.9.dist-info/licenses/LICENSE,sha256=KWSC4z9cfML_t0xThoQYjzTdcZQj86Y_mhXdatzU-KM,1052
4
+ prompty/__init__.py,sha256=Msp8eiKdrDq0wyl6G5DFDH8r5BxM2_E60uzzL7_MJ5w,11183
5
+ prompty/cli.py,sha256=_bx_l5v7OGhtAn4d_73b8tyfEw7OOkjCqGMQPu0YP5A,2489
6
+ prompty/core.py,sha256=N6BTwLzmGovUVPBRp0Gg9YJa2Uo-5Q7SQnEBGU0czI8,14432
7
+ prompty/executors.py,sha256=z_SXF-i2qBbxmsBexQ4Ouiqwil6L0lU2wWfwIeSN-eE,3083
8
+ prompty/parsers.py,sha256=4mmIn4SVNs8B0R1BufanqUJk8v4r0OEEo8yx6UOxQpA,4670
9
+ prompty/processors.py,sha256=VaB7fGyaeIPRGuAZ9KTwktx7MIkfCtPALLQgNko1-Gk,2310
10
+ prompty/renderers.py,sha256=RSHFQFx7AtKLUfsMLCXR0a56Mb7DL1NJNgjUqgg3IqU,776
11
+ prompty/tracer.py,sha256=GRHsm6661K8eyA7FkgU2ell0lw8pl2QCZXtjLboR-PY,6244
12
+ prompty-0.1.9.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- prompty-0.1.7.dist-info/METADATA,sha256=WnpHqfmMVpAyXSIjChwWCNo5lTB19gLTiYVEm0xCvCU,4665
2
- prompty-0.1.7.dist-info/WHEEL,sha256=rSwsxJWe3vzyR5HCwjWXQruDgschpei4h_giTm0dJVE,90
3
- prompty-0.1.7.dist-info/licenses/LICENSE,sha256=KWSC4z9cfML_t0xThoQYjzTdcZQj86Y_mhXdatzU-KM,1052
4
- prompty/__init__.py,sha256=Msp8eiKdrDq0wyl6G5DFDH8r5BxM2_E60uzzL7_MJ5w,11183
5
- prompty/cli.py,sha256=_bx_l5v7OGhtAn4d_73b8tyfEw7OOkjCqGMQPu0YP5A,2489
6
- prompty/core.py,sha256=WYSvognjMUl08FT0_mkcqZfymb_guKcp3sK8_RO4Kq0,13528
7
- prompty/executors.py,sha256=TankDTAEBTZkvnPfNUw2KNb1TnNuWhyY8TkWOogUXKs,3185
8
- prompty/parsers.py,sha256=4mmIn4SVNs8B0R1BufanqUJk8v4r0OEEo8yx6UOxQpA,4670
9
- prompty/processors.py,sha256=GmReygLx2XW1UuanlX71HG3rTZL86y0yAGyNdbGWkcg,2366
10
- prompty/renderers.py,sha256=RSHFQFx7AtKLUfsMLCXR0a56Mb7DL1NJNgjUqgg3IqU,776
11
- prompty/tracer.py,sha256=ac7b0M94RjeTqmMAypTlqq5kSnfxge4Oo8sJFEqVp9c,5497
12
- prompty-0.1.7.dist-info/RECORD,,