typeagent-py 0.1.0__tar.gz → 0.1.1__tar.gz

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.
Files changed (102) hide show
  1. {typeagent_py-0.1.0/typeagent_py.egg-info → typeagent_py-0.1.1}/PKG-INFO +1 -1
  2. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/pyproject.toml +4 -1
  3. {typeagent_py-0.1.0 → typeagent_py-0.1.1/typeagent_py.egg-info}/PKG-INFO +1 -1
  4. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent_py.egg-info/SOURCES.txt +14 -1
  5. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent_py.egg-info/top_level.txt +1 -0
  6. typeagent_py-0.1.1/typechat/__about__.py +4 -0
  7. typeagent_py-0.1.1/typechat/__init__.py +25 -0
  8. typeagent_py-0.1.1/typechat/_internal/__init__.py +0 -0
  9. typeagent_py-0.1.1/typechat/_internal/interactive.py +37 -0
  10. typeagent_py-0.1.1/typechat/_internal/model.py +184 -0
  11. typeagent_py-0.1.1/typechat/_internal/result.py +21 -0
  12. typeagent_py-0.1.1/typechat/_internal/translator.py +125 -0
  13. typeagent_py-0.1.1/typechat/_internal/ts_conversion/__init__.py +37 -0
  14. typeagent_py-0.1.1/typechat/_internal/ts_conversion/python_type_to_ts_nodes.py +447 -0
  15. typeagent_py-0.1.1/typechat/_internal/ts_conversion/ts_node_to_string.py +96 -0
  16. typeagent_py-0.1.1/typechat/_internal/ts_conversion/ts_type_nodes.py +78 -0
  17. typeagent_py-0.1.1/typechat/_internal/validator.py +67 -0
  18. typeagent_py-0.1.1/typechat/py.typed +0 -0
  19. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/LICENSE +0 -0
  20. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/README.md +0 -0
  21. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/setup.cfg +0 -0
  22. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_auth.py +0 -0
  23. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_collections.py +0 -0
  24. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_conversation_metadata.py +0 -0
  25. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_demo.py +0 -0
  26. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_embeddings.py +0 -0
  27. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_interfaces.py +0 -0
  28. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_knowledge.py +0 -0
  29. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_kplib.py +0 -0
  30. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_message_text_index_population.py +0 -0
  31. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_message_text_index_serialization.py +0 -0
  32. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_messageindex.py +0 -0
  33. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_podcasts.py +0 -0
  34. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_property_index_population.py +0 -0
  35. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_propindex.py +0 -0
  36. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_query.py +0 -0
  37. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_related_terms_fast.py +0 -0
  38. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_related_terms_index_population.py +0 -0
  39. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_reltermsindex.py +0 -0
  40. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_searchlib.py +0 -0
  41. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_secindex.py +0 -0
  42. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_secindex_storage_integration.py +0 -0
  43. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_semrefindex.py +0 -0
  44. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_serialization.py +0 -0
  45. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_sqlite_indexes.py +0 -0
  46. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_sqlitestore.py +0 -0
  47. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_storage_providers_unified.py +0 -0
  48. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_timestampindex.py +0 -0
  49. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_utils.py +0 -0
  50. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/test/test_vectorbase.py +0 -0
  51. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/aitools/auth.py +0 -0
  52. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/aitools/embeddings.py +0 -0
  53. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/aitools/utils.py +0 -0
  54. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/aitools/vectorbase.py +0 -0
  55. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/answer_context_schema.py +0 -0
  56. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/answer_response_schema.py +0 -0
  57. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/answers.py +0 -0
  58. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/collections.py +0 -0
  59. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/common.py +0 -0
  60. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/convknowledge.py +0 -0
  61. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/convsettings.py +0 -0
  62. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/convutils.py +0 -0
  63. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/date_time_schema.py +0 -0
  64. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/field_helpers.py +0 -0
  65. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/fuzzyindex.py +0 -0
  66. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/interfaces.py +0 -0
  67. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/knowledge.py +0 -0
  68. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/kplib.py +0 -0
  69. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/query.py +0 -0
  70. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/search.py +0 -0
  71. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/search_query_schema.py +0 -0
  72. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/searchlang.py +0 -0
  73. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/searchlib.py +0 -0
  74. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/secindex.py +0 -0
  75. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/serialization.py +0 -0
  76. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/textlocindex.py +0 -0
  77. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/knowpro/utils.py +0 -0
  78. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/mcp/server.py +0 -0
  79. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/podcasts/podcast.py +0 -0
  80. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/podcasts/podcast_import.py +0 -0
  81. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/__init__.py +0 -0
  82. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/__init__.py +0 -0
  83. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/collections.py +0 -0
  84. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/convthreads.py +0 -0
  85. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/messageindex.py +0 -0
  86. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/propindex.py +0 -0
  87. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/provider.py +0 -0
  88. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/reltermsindex.py +0 -0
  89. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/semrefindex.py +0 -0
  90. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/memory/timestampindex.py +0 -0
  91. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/__init__.py +0 -0
  92. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/collections.py +0 -0
  93. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/messageindex.py +0 -0
  94. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/propindex.py +0 -0
  95. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/provider.py +0 -0
  96. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/reltermsindex.py +0 -0
  97. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/schema.py +0 -0
  98. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/semrefindex.py +0 -0
  99. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/sqlite/timestampindex.py +0 -0
  100. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent/storage/utils.py +0 -0
  101. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent_py.egg-info/dependency_links.txt +0 -0
  102. {typeagent_py-0.1.0 → typeagent_py-0.1.1}/typeagent_py.egg-info/requires.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: typeagent-py
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: TypeAgent implements an agentic memory framework.
5
5
  Author: Steven Lucco, Umesh Madan, Guido van Rossum
6
6
  Author-email: Guido van Rossum <gvanrossum@microsoft.com>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "typeagent-py"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "TypeAgent implements an agentic memory framework."
9
9
  authors = [
10
10
  { name = "Guido van Rossum", email = "gvanrossum@microsoft.com" },
@@ -48,6 +48,9 @@ packages = [
48
48
  "typeagent.storage",
49
49
  "typeagent.storage.memory",
50
50
  "typeagent.storage.sqlite",
51
+ "typechat",
52
+ "typechat._internal",
53
+ "typechat._internal.ts_conversion",
51
54
  ]
52
55
 
53
56
  [tool.pytest.ini_options]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: typeagent-py
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: TypeAgent implements an agentic memory framework.
5
5
  Author: Steven Lucco, Umesh Madan, Guido van Rossum
6
6
  Author-email: Guido van Rossum <gvanrossum@microsoft.com>
@@ -84,4 +84,17 @@ typeagent_py.egg-info/PKG-INFO
84
84
  typeagent_py.egg-info/SOURCES.txt
85
85
  typeagent_py.egg-info/dependency_links.txt
86
86
  typeagent_py.egg-info/requires.txt
87
- typeagent_py.egg-info/top_level.txt
87
+ typeagent_py.egg-info/top_level.txt
88
+ typechat/__about__.py
89
+ typechat/__init__.py
90
+ typechat/py.typed
91
+ typechat/_internal/__init__.py
92
+ typechat/_internal/interactive.py
93
+ typechat/_internal/model.py
94
+ typechat/_internal/result.py
95
+ typechat/_internal/translator.py
96
+ typechat/_internal/validator.py
97
+ typechat/_internal/ts_conversion/__init__.py
98
+ typechat/_internal/ts_conversion/python_type_to_ts_nodes.py
99
+ typechat/_internal/ts_conversion/ts_node_to_string.py
100
+ typechat/_internal/ts_conversion/ts_type_nodes.py
@@ -0,0 +1,4 @@
1
+ # SPDX-FileCopyrightText: Microsoft Corporation
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ __version__ = "0.0.2"
@@ -0,0 +1,25 @@
1
+ # SPDX-FileCopyrightText: Microsoft Corporation
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from typechat._internal.model import PromptSection, TypeChatLanguageModel, create_language_model, create_openai_language_model, create_azure_openai_language_model
6
+ from typechat._internal.result import Failure, Result, Success
7
+ from typechat._internal.translator import TypeChatJsonTranslator
8
+ from typechat._internal.ts_conversion import python_type_to_typescript_schema
9
+ from typechat._internal.validator import TypeChatValidator
10
+ from typechat._internal.interactive import process_requests
11
+
12
+ __all__ = [
13
+ "TypeChatLanguageModel",
14
+ "TypeChatJsonTranslator",
15
+ "TypeChatValidator",
16
+ "Success",
17
+ "Failure",
18
+ "Result",
19
+ "python_type_to_typescript_schema",
20
+ "PromptSection",
21
+ "create_language_model",
22
+ "create_openai_language_model",
23
+ "create_azure_openai_language_model",
24
+ "process_requests",
25
+ ]
File without changes
@@ -0,0 +1,37 @@
1
+ from typing import Callable, Awaitable
2
+
3
+ async def process_requests(interactive_prompt: str, input_file_name: str | None, process_request: Callable[[str], Awaitable[None]]):
4
+ """
5
+ A request processor for interactive input or input from a text file. If an input file name is specified,
6
+ the callback function is invoked for each line in file. Otherwise, the callback function is invoked for
7
+ each line of interactive input until the user types "quit" or "exit".
8
+
9
+ Args:
10
+ interactive_prompt: Prompt to present to user.
11
+ input_file_name: Input text file name, if any.
12
+ process_request: Async callback function that is invoked for each interactive input or each line in text file.
13
+ """
14
+ if input_file_name is not None:
15
+ with open(input_file_name, "r") as file:
16
+ lines = filter(str.rstrip, file)
17
+ for line in lines:
18
+ if line.startswith("# "):
19
+ continue
20
+ print(interactive_prompt + line)
21
+ await process_request(line)
22
+ else:
23
+ try:
24
+ # Use readline to enable input editing and history
25
+ import readline # type: ignore
26
+ except ImportError:
27
+ pass
28
+ while True:
29
+ try:
30
+ line = input(interactive_prompt)
31
+ except EOFError:
32
+ print("\n")
33
+ break
34
+ if line.lower().strip() in ("quit", "exit"):
35
+ break
36
+ else:
37
+ await process_request(line)
@@ -0,0 +1,184 @@
1
+ import asyncio
2
+ from types import TracebackType
3
+ from typing_extensions import AsyncContextManager, Literal, Protocol, Self, TypedDict, cast, override
4
+
5
+ from typechat._internal.result import Failure, Result, Success
6
+
7
+ import httpx
8
+
9
+ class PromptSection(TypedDict):
10
+ """
11
+ Represents a section of an LLM prompt with an associated role. TypeChat uses the "user" role for
12
+ prompts it generates and the "assistant" role for previous LLM responses (which will be part of
13
+ the prompt in repair attempts). TypeChat currently doesn't use the "system" role.
14
+ """
15
+ role: Literal["system", "user", "assistant"]
16
+ content: str
17
+
18
+ class TypeChatLanguageModel(Protocol):
19
+ async def complete(self, prompt: str | list[PromptSection]) -> Result[str]:
20
+ """
21
+ Represents a AI language model that can complete prompts.
22
+
23
+ TypeChat uses an implementation of this protocol to communicate
24
+ with an AI service that can translate natural language requests to JSON
25
+ instances according to a provided schema.
26
+ The `create_language_model` function can create an instance.
27
+ """
28
+ ...
29
+
30
+ _TRANSIENT_ERROR_CODES = [
31
+ 429,
32
+ 500,
33
+ 502,
34
+ 503,
35
+ 504,
36
+ ]
37
+
38
+ class HttpxLanguageModel(TypeChatLanguageModel, AsyncContextManager):
39
+ url: str
40
+ headers: dict[str, str]
41
+ default_params: dict[str, str]
42
+ # Specifies the maximum number of retry attempts.
43
+ max_retry_attempts: int = 3
44
+ # Specifies the delay before retrying in milliseconds.
45
+ retry_pause_seconds: float = 1.0
46
+ # Specifies how long a request should wait in seconds
47
+ # before timing out with a Failure.
48
+ timeout_seconds = 10
49
+ _async_client: httpx.AsyncClient
50
+
51
+ def __init__(self, url: str, headers: dict[str, str], default_params: dict[str, str]):
52
+ super().__init__()
53
+ self.url = url
54
+ self.headers = headers
55
+ self.default_params = default_params
56
+ self._async_client = httpx.AsyncClient()
57
+
58
+ @override
59
+ async def complete(self, prompt: str | list[PromptSection]) -> Success[str] | Failure:
60
+ headers = {
61
+ "Content-Type": "application/json",
62
+ **self.headers,
63
+ }
64
+
65
+ if isinstance(prompt, str):
66
+ prompt = [{"role": "user", "content": prompt}]
67
+
68
+ body = {
69
+ **self.default_params,
70
+ "messages": prompt,
71
+ "temperature": 0.0,
72
+ "n": 1,
73
+ }
74
+ retry_count = 0
75
+ while True:
76
+ try:
77
+ response = await self._async_client.post(
78
+ self.url,
79
+ headers=headers,
80
+ json=body,
81
+ timeout=self.timeout_seconds
82
+ )
83
+ if response.is_success:
84
+ json_result = cast(
85
+ dict[Literal["choices"], list[dict[Literal["message"], PromptSection]]],
86
+ response.json()
87
+ )
88
+ return Success(json_result["choices"][0]["message"]["content"] or "")
89
+
90
+ if response.status_code not in _TRANSIENT_ERROR_CODES or retry_count >= self.max_retry_attempts:
91
+ return Failure(f"REST API error {response.status_code}: {response.reason_phrase}")
92
+ except Exception as e:
93
+ if retry_count >= self.max_retry_attempts:
94
+ return Failure(str(e) or f"{repr(e)} raised from within internal TypeChat language model.")
95
+
96
+ await asyncio.sleep(self.retry_pause_seconds)
97
+ retry_count += 1
98
+
99
+ @override
100
+ async def __aenter__(self) -> Self:
101
+ return self
102
+
103
+ @override
104
+ async def __aexit__(self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None) -> bool | None:
105
+ await self._async_client.aclose()
106
+
107
+ def __del__(self):
108
+ try:
109
+ asyncio.get_running_loop().create_task(self._async_client.aclose())
110
+ except Exception:
111
+ pass
112
+
113
+ def create_language_model(vals: dict[str, str | None]) -> HttpxLanguageModel:
114
+ """
115
+ Creates a language model encapsulation of an OpenAI or Azure OpenAI REST API endpoint
116
+ chosen by a dictionary of variables (typically just `os.environ`).
117
+
118
+ If an `OPENAI_API_KEY` environment variable exists, an OpenAI model is constructed.
119
+ The `OPENAI_ENDPOINT` and `OPENAI_MODEL` environment variables must also be defined or an error will be raised.
120
+
121
+ If an `AZURE_OPENAI_API_KEY` environment variable exists, an Azure OpenAI model is constructed.
122
+ The `AZURE_OPENAI_ENDPOINT` environment variable must also be defined or an exception will be thrown.
123
+
124
+ If none of these key variables are defined, an exception is thrown.
125
+ @returns An instance of `TypeChatLanguageModel`.
126
+
127
+ Args:
128
+ vals: A dictionary of variables. Typically just `os.environ`.
129
+ """
130
+
131
+ def required_var(name: str) -> str:
132
+ val = vals.get(name, None)
133
+ if val is None:
134
+ raise ValueError(f"Missing environment variable {name}.")
135
+ return val
136
+
137
+ if "OPENAI_API_KEY" in vals:
138
+ api_key = required_var("OPENAI_API_KEY")
139
+ model = required_var("OPENAI_MODEL")
140
+ endpoint = vals.get("OPENAI_ENDPOINT", None) or "https://api.openai.com/v1/chat/completions"
141
+ org = vals.get("OPENAI_ORG", None) or ""
142
+ return create_openai_language_model(api_key, model, endpoint, org)
143
+
144
+ elif "AZURE_OPENAI_API_KEY" in vals:
145
+ api_key=required_var("AZURE_OPENAI_API_KEY")
146
+ endpoint=required_var("AZURE_OPENAI_ENDPOINT")
147
+ return create_azure_openai_language_model(api_key, endpoint)
148
+ else:
149
+ raise ValueError("Missing environment variables for OPENAI_API_KEY or AZURE_OPENAI_API_KEY.")
150
+
151
+ def create_openai_language_model(api_key: str, model: str, endpoint: str = "https://api.openai.com/v1/chat/completions", org: str = "") -> HttpxLanguageModel:
152
+ """
153
+ Creates a language model encapsulation of an OpenAI REST API endpoint.
154
+
155
+ Args:
156
+ api_key: The OpenAI API key.
157
+ model: The OpenAI model name.
158
+ endpoint: The OpenAI REST API endpoint.
159
+ org: The OpenAI organization.
160
+ """
161
+ headers = {
162
+ "Authorization": f"Bearer {api_key}",
163
+ "OpenAI-Organization": org,
164
+ }
165
+ default_params = {
166
+ "model": model,
167
+ }
168
+ return HttpxLanguageModel(url=endpoint, headers=headers, default_params=default_params)
169
+
170
+ def create_azure_openai_language_model(api_key: str, endpoint: str) -> HttpxLanguageModel:
171
+ """
172
+ Creates a language model encapsulation of an Azure OpenAI REST API endpoint.
173
+
174
+ Args:
175
+ api_key: The Azure OpenAI API key.
176
+ endpoint: The Azure OpenAI REST API endpoint.
177
+ """
178
+ headers = {
179
+ # Needed when using managed identity
180
+ "Authorization": f"Bearer {api_key}",
181
+ # Needed when using regular API key
182
+ "api-key": api_key,
183
+ }
184
+ return HttpxLanguageModel(url=endpoint, headers=headers, default_params={})
@@ -0,0 +1,21 @@
1
+ from dataclasses import dataclass
2
+ from typing_extensions import Generic, TypeAlias, TypeVar
3
+
4
+ T = TypeVar("T", covariant=True)
5
+
6
+ @dataclass
7
+ class Success(Generic[T]):
8
+ "An object representing a successful operation with a result of type `T`."
9
+ value: T
10
+
11
+
12
+ @dataclass
13
+ class Failure:
14
+ "An object representing an operation that failed for the reason given in `message`."
15
+ message: str
16
+
17
+
18
+ """
19
+ An object representing a successful or failed operation of type `T`.
20
+ """
21
+ Result: TypeAlias = Success[T] | Failure
@@ -0,0 +1,125 @@
1
+ from typing_extensions import Generic, TypeVar
2
+
3
+ import pydantic_core
4
+
5
+ from typechat._internal.model import PromptSection, TypeChatLanguageModel
6
+ from typechat._internal.result import Failure, Result, Success
7
+ from typechat._internal.ts_conversion import python_type_to_typescript_schema
8
+ from typechat._internal.validator import TypeChatValidator
9
+
10
+ T = TypeVar("T", covariant=True)
11
+
12
+ class TypeChatJsonTranslator(Generic[T]):
13
+ """
14
+ Represents an object that can translate natural language requests in JSON objects of the given type.
15
+ """
16
+
17
+ model: TypeChatLanguageModel
18
+ validator: TypeChatValidator[T]
19
+ target_type: type[T]
20
+ type_name: str
21
+ schema_str: str
22
+ _max_repair_attempts = 1
23
+
24
+ def __init__(
25
+ self,
26
+ model: TypeChatLanguageModel,
27
+ validator: TypeChatValidator[T],
28
+ target_type: type[T],
29
+ *, # keyword-only parameters follow
30
+ _raise_on_schema_errors: bool = True,
31
+ ):
32
+ """
33
+ Args:
34
+ model: The associated `TypeChatLanguageModel`.
35
+ validator: The associated `TypeChatValidator[T]`.
36
+ target_type: A runtime type object describing `T` - the expected shape of JSON data.
37
+ """
38
+ super().__init__()
39
+ self.model = model
40
+ self.validator = validator
41
+ self.target_type = target_type
42
+
43
+ conversion_result = python_type_to_typescript_schema(target_type)
44
+
45
+ if _raise_on_schema_errors and conversion_result.errors:
46
+ error_text = "".join(f"\n- {error}" for error in conversion_result.errors)
47
+ raise ValueError(f"Could not convert Python type to TypeScript schema: \n{error_text}")
48
+
49
+ self.type_name = conversion_result.typescript_type_reference
50
+ self.schema_str = conversion_result.typescript_schema_str
51
+
52
+ async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]:
53
+ """
54
+ Translates a natural language request into an object of type `T`. If the JSON object returned by
55
+ the language model fails to validate, repair attempts will be made up until `_max_repair_attempts`.
56
+ The prompt for the subsequent attempts will include the diagnostics produced for the prior attempt.
57
+ This often helps produce a valid instance.
58
+
59
+ Args:
60
+ input: A natural language request.
61
+ prompt_preamble: An optional string or list of prompt sections to prepend to the generated prompt.\
62
+ If a string is given, it is converted to a single "user" role prompt section.
63
+ """
64
+
65
+ messages: list[PromptSection] = []
66
+
67
+ if prompt_preamble:
68
+ if isinstance(prompt_preamble, str):
69
+ prompt_preamble = [{"role": "user", "content": prompt_preamble}]
70
+ messages.extend(prompt_preamble)
71
+
72
+ messages.append({"role": "user", "content": self._create_request_prompt(input)})
73
+
74
+ num_repairs_attempted = 0
75
+ while True:
76
+ completion_response = await self.model.complete(messages)
77
+ if isinstance(completion_response, Failure):
78
+ return completion_response
79
+
80
+ text_response = completion_response.value
81
+ first_curly = text_response.find("{")
82
+ last_curly = text_response.rfind("}") + 1
83
+ error_message: str
84
+ if 0 <= first_curly < last_curly:
85
+ trimmed_response = text_response[first_curly:last_curly]
86
+ try:
87
+ parsed_response = pydantic_core.from_json(trimmed_response, allow_inf_nan=False, cache_strings=False)
88
+ except ValueError as e:
89
+ error_message = f"Error: {e}\n\nAttempted to parse:\n\n{trimmed_response}"
90
+ else:
91
+ result = self.validator.validate_object(parsed_response)
92
+ if isinstance(result, Success):
93
+ return result
94
+ error_message = result.message
95
+ else:
96
+ error_message = f"Response did not contain any text resembling JSON.\nResponse was\n\n{text_response}"
97
+ if num_repairs_attempted >= self._max_repair_attempts:
98
+ return Failure(error_message)
99
+ num_repairs_attempted += 1
100
+ messages.append({"role": "assistant", "content": text_response})
101
+ messages.append({"role": "user", "content": self._create_repair_prompt(error_message)})
102
+
103
+ def _create_request_prompt(self, intent: str) -> str:
104
+ prompt = f"""
105
+ You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions:
106
+ ```
107
+ {self.schema_str}
108
+ ```
109
+ The following is a user request:
110
+ '''
111
+ {intent}
112
+ '''
113
+ The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined:
114
+ """
115
+ return prompt
116
+
117
+ def _create_repair_prompt(self, validation_error: str) -> str:
118
+ prompt = f"""
119
+ The above JSON object is invalid for the following reason:
120
+ '''
121
+ {validation_error}
122
+ '''
123
+ The following is a revised JSON object:
124
+ """
125
+ return prompt
@@ -0,0 +1,37 @@
1
+ from dataclasses import dataclass
2
+ from typing_extensions import TypeAliasType
3
+
4
+ from typechat._internal.ts_conversion.python_type_to_ts_nodes import python_type_to_typescript_nodes
5
+ from typechat._internal.ts_conversion.ts_node_to_string import ts_declaration_to_str
6
+
7
+ __all__ = [
8
+ "python_type_to_typescript_schema",
9
+ "TypeScriptSchemaConversionResult",
10
+ ]
11
+
12
+ @dataclass
13
+ class TypeScriptSchemaConversionResult:
14
+ typescript_schema_str: str
15
+ """The TypeScript declarations generated from the Python declarations."""
16
+
17
+ typescript_type_reference: str
18
+ """The TypeScript string representation of a given Python type."""
19
+
20
+ errors: list[str]
21
+ """Any errors that occurred during conversion."""
22
+
23
+ def python_type_to_typescript_schema(py_type: type | TypeAliasType) -> TypeScriptSchemaConversionResult:
24
+ """Converts a Python type to a TypeScript schema."""
25
+
26
+ node_conversion_result = python_type_to_typescript_nodes(py_type)
27
+
28
+ decl_strs = map(ts_declaration_to_str, node_conversion_result.type_declarations)
29
+ decl_strs = reversed(list(decl_strs))
30
+
31
+ schema_str = "\n".join(decl_strs)
32
+
33
+ return TypeScriptSchemaConversionResult(
34
+ typescript_schema_str=schema_str,
35
+ typescript_type_reference=py_type.__name__,
36
+ errors=node_conversion_result.errors,
37
+ )