@effect/ai-typesafe 0.0.0 → 4.0.0-rc.116

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 (111) hide show
  1. package/AGENTS.md +410 -0
  2. package/CLAUDE.md +410 -0
  3. package/LICENSE +21 -0
  4. package/README.md +3 -41
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  69. package/ai-docs/src/60_child-process/index.md +3 -0
  70. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  71. package/ai-docs/src/70_cli/index.md +5 -0
  72. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  73. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  74. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  75. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  76. package/ai-docs/src/71_ai/index.md +5 -0
  77. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  78. package/ai-docs/src/80_cluster/index.md +4 -0
  79. package/ai-docs/src/index.md +10 -0
  80. package/ai-docs/tsconfig.json +24 -0
  81. package/dist/TypeSafeClient.d.ts +71 -0
  82. package/dist/TypeSafeClient.d.ts.map +1 -0
  83. package/dist/TypeSafeClient.js +74 -0
  84. package/dist/TypeSafeClient.js.map +1 -0
  85. package/dist/TypeSafeConfig.d.ts +68 -0
  86. package/dist/TypeSafeConfig.d.ts.map +1 -0
  87. package/dist/TypeSafeConfig.js +36 -0
  88. package/dist/TypeSafeConfig.js.map +1 -0
  89. package/dist/TypeSafeDecisionModel.d.ts +44 -0
  90. package/dist/TypeSafeDecisionModel.d.ts.map +1 -0
  91. package/dist/TypeSafeDecisionModel.js +118 -0
  92. package/dist/TypeSafeDecisionModel.js.map +1 -0
  93. package/dist/TypeSafeSchema.d.ts +188 -0
  94. package/dist/TypeSafeSchema.d.ts.map +1 -0
  95. package/dist/TypeSafeSchema.js +130 -0
  96. package/dist/TypeSafeSchema.js.map +1 -0
  97. package/dist/index.d.ts +20 -0
  98. package/dist/index.d.ts.map +1 -0
  99. package/dist/index.js +21 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/internal/errors.d.ts +7 -0
  102. package/dist/internal/errors.d.ts.map +1 -0
  103. package/dist/internal/errors.js +120 -0
  104. package/dist/internal/errors.js.map +1 -0
  105. package/package.json +58 -7
  106. package/src/TypeSafeClient.ts +143 -0
  107. package/src/TypeSafeConfig.ts +85 -0
  108. package/src/TypeSafeDecisionModel.ts +106 -0
  109. package/src/TypeSafeSchema.ts +134 -0
  110. package/src/index.ts +25 -0
  111. package/src/internal/errors.ts +113 -0
package/package.json CHANGED
@@ -1,10 +1,61 @@
1
1
  {
2
2
  "name": "@effect/ai-typesafe",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for @effect/ai-typesafe",
3
+ "version": "4.0.0-rc.116",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "A TypeSafe DecisionModel provider for Effect",
7
+ "homepage": "https://effect.website",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Effect-TS/effect.git",
11
+ "directory": "packages/ai/typesafe"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/Effect-TS/effect/issues"
15
+ },
16
+ "tags": [
17
+ "typescript",
18
+ "ai",
19
+ "typesafe"
20
+ ],
5
21
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
22
+ "typescript",
23
+ "ai",
24
+ "typesafe"
25
+ ],
26
+ "sideEffects": [],
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": "./dist/index.js",
30
+ "./*": "./dist/*.js",
31
+ "./internal/*": null,
32
+ "./index": null,
33
+ "./*/index": null
34
+ },
35
+ "files": [
36
+ "src/**/*.ts",
37
+ "dist/**/*.js",
38
+ "dist/**/*.js.map",
39
+ "dist/**/*.d.ts",
40
+ "dist/**/*.d.ts.map",
41
+ "AGENTS.md",
42
+ "CLAUDE.md",
43
+ "ai-docs/**/*"
44
+ ],
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "provenance": true
48
+ },
49
+ "devDependencies": {
50
+ "effect": "^4.0.0-rc.116"
51
+ },
52
+ "peerDependencies": {
53
+ "effect": "^4.0.0-rc.116"
54
+ },
55
+ "scripts": {
56
+ "codegen": "effect-utils codegen",
57
+ "build": "tsc -b tsconfig.json && pnpm babel",
58
+ "babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
59
+ "check": "tsc -b tsconfig.json"
60
+ }
61
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * HTTP client for TypeSafe System One and model discovery.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+ import * as Config from "effect/Config"
7
+ import * as Context from "effect/Context"
8
+ import * as Effect from "effect/Effect"
9
+ import { flow, identity } from "effect/Function"
10
+ import * as Layer from "effect/Layer"
11
+ import * as Redacted from "effect/Redacted"
12
+ import type * as Schema from "effect/Schema"
13
+ import * as AiError from "effect/unstable/ai/AiError"
14
+ import * as HttpClient from "effect/unstable/http/HttpClient"
15
+ import type * as HttpClientError from "effect/unstable/http/HttpClientError"
16
+ import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"
17
+ import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"
18
+ import * as Errors from "./internal/errors.ts"
19
+ import { TypeSafeConfig } from "./TypeSafeConfig.ts"
20
+ import * as TypeSafeSchema from "./TypeSafeSchema.ts"
21
+
22
+ /**
23
+ * Low-level TypeSafe operations.
24
+ *
25
+ * @category services
26
+ * @since 4.0.0
27
+ */
28
+ export interface Service {
29
+ readonly client: HttpClient.HttpClient
30
+ readonly systemOne: (
31
+ request: typeof TypeSafeSchema.SystemOneRequest.Encoded
32
+ ) => Effect.Effect<typeof TypeSafeSchema.SystemOneResponse.Type, AiError.AiError>
33
+ readonly listModels: () => Effect.Effect<typeof TypeSafeSchema.ListModelsResponse.Type, AiError.AiError>
34
+ }
35
+
36
+ /**
37
+ * TypeSafe client service.
38
+ *
39
+ * @category services
40
+ * @since 4.0.0
41
+ */
42
+ export class TypeSafeClient extends Context.Service<TypeSafeClient, Service>()("@effect/ai-typesafe/TypeSafeClient") {}
43
+
44
+ /**
45
+ * Authentication, endpoint and HTTP customization options.
46
+ *
47
+ * @category options
48
+ * @since 4.0.0
49
+ */
50
+ export interface Options {
51
+ readonly apiKey?: Redacted.Redacted<string> | undefined
52
+ readonly apiUrl?: string | undefined
53
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
54
+ }
55
+
56
+ const decodeSystemOne = HttpClientResponse.schemaBodyJson(TypeSafeSchema.SystemOneResponse)
57
+ const decodeListModels = HttpClientResponse.schemaBodyJson(TypeSafeSchema.ListModelsResponse)
58
+
59
+ /**
60
+ * Builds a client without automatic retries. Scoped transforms run after the constructor transform.
61
+ *
62
+ * @category constructors
63
+ * @since 4.0.0
64
+ */
65
+ export const make = Effect.fnUntraced(
66
+ function*(options: Options): Effect.fn.Return<Service, never, HttpClient.HttpClient> {
67
+ const base = yield* HttpClient.HttpClient
68
+ const client = base.pipe(
69
+ HttpClient.mapRequest(flow(
70
+ HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.typesafe.ai/v1"),
71
+ options.apiKey ? HttpClientRequest.bearerToken(Redacted.value(options.apiKey)) : identity,
72
+ HttpClientRequest.acceptJson
73
+ )),
74
+ HttpClient.filterStatusOk,
75
+ options.transformClient ?? identity
76
+ )
77
+ const resolveClient = Effect.map(
78
+ TypeSafeConfig.getOrUndefined,
79
+ (config) => config?.transformClient?.(client) ?? client
80
+ )
81
+ const execute = <A>(
82
+ request: HttpClientRequest.HttpClientRequest,
83
+ decode: (
84
+ response: HttpClientResponse.HttpClientResponse
85
+ ) => Effect.Effect<A, HttpClientError.HttpClientError | Schema.SchemaError>,
86
+ method: string
87
+ ) =>
88
+ resolveClient.pipe(
89
+ Effect.flatMap((client) => client.execute(request)),
90
+ Effect.flatMap(decode),
91
+ Effect.catchTags({
92
+ HttpClientError: (error) => Errors.mapHttpClientError(error, method),
93
+ SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, method))
94
+ })
95
+ )
96
+ return TypeSafeClient.of({
97
+ client,
98
+ systemOne: (payload) =>
99
+ HttpClientRequest.bodyJson(HttpClientRequest.post("/systemone"), payload).pipe(
100
+ Effect.mapError((error) =>
101
+ AiError.make({
102
+ module: "TypeSafeClient",
103
+ method: "systemOne",
104
+ reason: new AiError.InvalidRequestError({ description: String(error) })
105
+ })
106
+ ),
107
+ Effect.flatMap((request) => execute(request, decodeSystemOne, "systemOne"))
108
+ ),
109
+ listModels: () => execute(HttpClientRequest.get("/models"), decodeListModels, "listModels")
110
+ })
111
+ }
112
+ )
113
+
114
+ /**
115
+ * Provides a client from explicit options.
116
+ *
117
+ * @category layers
118
+ * @since 4.0.0
119
+ */
120
+ export const layer = (options: Options): Layer.Layer<TypeSafeClient, never, HttpClient.HttpClient> =>
121
+ Layer.effect(TypeSafeClient, make(options))
122
+
123
+ /**
124
+ * Provides a client from configuration, defaulting to TYPESAFE_API_KEY.
125
+ *
126
+ * @category layers
127
+ * @since 4.0.0
128
+ */
129
+ export const layerConfig = (options?: {
130
+ readonly apiKey?: Config.Config<Redacted.Redacted<string> | undefined> | undefined
131
+ readonly apiUrl?: Config.Config<string> | undefined
132
+ readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
133
+ }): Layer.Layer<TypeSafeClient, Config.ConfigError, HttpClient.HttpClient> =>
134
+ Layer.effect(
135
+ TypeSafeClient,
136
+ Effect.gen(function*() {
137
+ return yield* make({
138
+ apiKey: yield* (options?.apiKey ?? Config.Redacted("TYPESAFE_API_KEY")),
139
+ apiUrl: options?.apiUrl ? yield* options.apiUrl : undefined,
140
+ transformClient: options?.transformClient
141
+ })
142
+ })
143
+ )
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Scoped HTTP client customization for TypeSafe requests.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+ import * as Context from "effect/Context"
7
+ import * as Effect from "effect/Effect"
8
+ import { dual } from "effect/Function"
9
+ import type { HttpClient } from "effect/unstable/http/HttpClient"
10
+
11
+ /**
12
+ * Scoped configuration read when executing TypeSafe requests.
13
+ *
14
+ * @see {@link withClientTransform} for scoping an HTTP client transformation
15
+ *
16
+ * @category services
17
+ * @since 4.0.0
18
+ */
19
+ export class TypeSafeConfig extends Context.Service<
20
+ TypeSafeConfig,
21
+ TypeSafeConfig.Service
22
+ >()("@effect/ai-typesafe/TypeSafeConfig") {
23
+ /**
24
+ * Reads the current configuration, if present.
25
+ *
26
+ * @since 4.0.0
27
+ */
28
+ static readonly getOrUndefined: Effect.Effect<typeof TypeSafeConfig.Service | undefined> = Effect.map(
29
+ Effect.context<never>(),
30
+ Context.getOrUndefined(TypeSafeConfig)
31
+ )
32
+ }
33
+
34
+ /**
35
+ * Types used by the `TypeSafeConfig` context service.
36
+ *
37
+ * @since 4.0.0
38
+ */
39
+ export declare namespace TypeSafeConfig {
40
+ /**
41
+ * Per-request HTTP client configuration.
42
+ *
43
+ * @category services
44
+ * @since 4.0.0
45
+ */
46
+ export interface Service {
47
+ readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Transforms the TypeSafe HTTP client for requests made by the supplied effect.
53
+ * Replaces any existing scoped transform; compose them manually to apply both.
54
+ *
55
+ * @category configuration
56
+ * @since 4.0.0
57
+ */
58
+ export const withClientTransform: {
59
+ /**
60
+ * Transforms the TypeSafe HTTP client for requests made by the supplied effect.
61
+ * Replaces any existing scoped transform; compose them manually to apply both.
62
+ *
63
+ * @category configuration
64
+ * @since 4.0.0
65
+ */
66
+ (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
67
+ /**
68
+ * Transforms the TypeSafe HTTP client for requests made by the supplied effect.
69
+ * Replaces any existing scoped transform; compose them manually to apply both.
70
+ *
71
+ * @category configuration
72
+ * @since 4.0.0
73
+ */
74
+ <A, E, R>(
75
+ self: Effect.Effect<A, E, R>,
76
+ transform: (client: HttpClient) => HttpClient
77
+ ): Effect.Effect<A, E, R>
78
+ } = dual(2, <A, E, R>(
79
+ self: Effect.Effect<A, E, R>,
80
+ transformClient: (client: HttpClient) => HttpClient
81
+ ) =>
82
+ Effect.flatMap(
83
+ TypeSafeConfig.getOrUndefined,
84
+ (config) => Effect.provideService(self, TypeSafeConfig, { ...config, transformClient })
85
+ ))
@@ -0,0 +1,106 @@
1
+ /**
2
+ * TypeSafe's System One implementation of DecisionModel.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+ import * as Effect from "effect/Effect"
7
+ import * as Layer from "effect/Layer"
8
+ import * as DecisionModel from "effect/unstable/ai/DecisionModel"
9
+ import * as AiModel from "effect/unstable/ai/Model"
10
+ import { TypeSafeClient } from "./TypeSafeClient.ts"
11
+ import type * as TypeSafeSchema from "./TypeSafeSchema.ts"
12
+
13
+ /**
14
+ * Known TypeSafe model identifiers. Constructors also accept custom identifiers.
15
+ *
16
+ * @category models
17
+ * @since 4.0.0
18
+ */
19
+ export type Model = "jev-latest" | "jev-preview" | "jev-1.13.0"
20
+
21
+ /**
22
+ * Creates a decision model with TypeSafe provider metadata.
23
+ *
24
+ * @category constructors
25
+ * @since 4.0.0
26
+ */
27
+ export const model = (
28
+ model: Model | (string & {})
29
+ ): AiModel.Model<"typesafe", DecisionModel.DecisionModel, TypeSafeClient> =>
30
+ AiModel.make("typesafe", model, layer({ model }))
31
+
32
+ /**
33
+ * Builds a decision service. Provider values are preserved without normalization;
34
+ * DecisionModel validates distributions and derives rating labels.
35
+ *
36
+ * @category constructors
37
+ * @since 4.0.0
38
+ */
39
+ export const make = Effect.fnUntraced(
40
+ function*(
41
+ options: { readonly model: Model | (string & {}) }
42
+ ): Effect.fn.Return<DecisionModel.DecisionModel, never, TypeSafeClient> {
43
+ const client = yield* TypeSafeClient
44
+ return yield* DecisionModel.make({
45
+ decide: Effect.fnUntraced(function*({ state, decisions }) {
46
+ const questions: Record<string, typeof TypeSafeSchema.Question.Encoded> = Object.create(null)
47
+ for (const [key, decision] of Object.entries(decisions)) {
48
+ switch (decision._tag) {
49
+ case "Classify":
50
+ questions[key] = { type: "choice", instructions: decision.instructions, criteria: decision.criteria }
51
+ break
52
+ case "Rate":
53
+ questions[key] = { type: "score", instructions: decision.instructions, criteria: decision.criteria }
54
+ break
55
+ case "Probability":
56
+ questions[key] = { type: "noul", instructions: decision.instructions, criteria: decision.criteria }
57
+ break
58
+ }
59
+ }
60
+ const response = yield* client.systemOne({ model: options.model, state, questions })
61
+ const answers: Record<string, DecisionModel.ProviderAnswer> = Object.create(null)
62
+ for (const [key, decision] of Object.entries(decisions)) {
63
+ const answer = response.answers[key]
64
+ switch (answer?.type) {
65
+ case "choice":
66
+ answers[key] = {
67
+ _tag: "Classify",
68
+ label: answer.choice,
69
+ probabilities: answer.probabilities,
70
+ confidence: answer.confidence
71
+ }
72
+ break
73
+ case "score": {
74
+ const levels = decision._tag === "Rate" ? decision.criteria : []
75
+ const probabilities: Record<string, number> = Object.create(null)
76
+ for (let index = 0; index < levels.length; index++) {
77
+ const probability = answer.probabilities[String(index)]
78
+ if (probability !== undefined) probabilities[levels[index]] = probability
79
+ }
80
+ answers[key] = { _tag: "Rate", rating: answer.score, probabilities, confidence: answer.confidence }
81
+ break
82
+ }
83
+ case "noul":
84
+ answers[key] = { _tag: "Probability", probability: answer.noul }
85
+ break
86
+ }
87
+ }
88
+ return {
89
+ answers,
90
+ usage: { inputTokens: response.usage?.input_tokens, outputTokens: response.usage?.output_tokens }
91
+ }
92
+ })
93
+ })
94
+ }
95
+ )
96
+
97
+ /**
98
+ * Provides DecisionModel using an existing TypeSafeClient.
99
+ *
100
+ * @category layers
101
+ * @since 4.0.0
102
+ */
103
+ export const layer = (
104
+ options: { readonly model: Model | (string & {}) }
105
+ ): Layer.Layer<DecisionModel.DecisionModel, never, TypeSafeClient> =>
106
+ Layer.effect(DecisionModel.DecisionModel, make(options))
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Codecs for the TypeSafe System One API.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+ import * as Schema from "effect/Schema"
7
+
8
+ /**
9
+ * A classification question.
10
+ *
11
+ * @category schemas
12
+ * @since 4.0.0
13
+ */
14
+ export const ChoiceQuestion = Schema.Struct({
15
+ type: Schema.Literal("choice"),
16
+ instructions: Schema.String,
17
+ criteria: Schema.Record(Schema.String, Schema.String)
18
+ })
19
+
20
+ /**
21
+ * An ordered rating question.
22
+ *
23
+ * @category schemas
24
+ * @since 4.0.0
25
+ */
26
+ export const ScoreQuestion = Schema.Struct({
27
+ type: Schema.Literal("score"),
28
+ instructions: Schema.String,
29
+ criteria: Schema.Array(Schema.String)
30
+ })
31
+
32
+ /**
33
+ * A probability question.
34
+ *
35
+ * @category schemas
36
+ * @since 4.0.0
37
+ */
38
+ export const NoulQuestion = Schema.Struct({
39
+ type: Schema.Literal("noul"),
40
+ instructions: Schema.String,
41
+ criteria: Schema.optional(Schema.Struct({ false: Schema.String, true: Schema.String }))
42
+ })
43
+
44
+ /**
45
+ * A System One question.
46
+ *
47
+ * @category schemas
48
+ * @since 4.0.0
49
+ */
50
+ export const Question = Schema.Union([ChoiceQuestion, ScoreQuestion, NoulQuestion])
51
+
52
+ /**
53
+ * A batch of questions against encoded state.
54
+ *
55
+ * @category schemas
56
+ * @since 4.0.0
57
+ */
58
+ export const SystemOneRequest = Schema.Struct({
59
+ model: Schema.String,
60
+ state: Schema.Json,
61
+ questions: Schema.Record(Schema.String, Question)
62
+ })
63
+
64
+ /**
65
+ * A classification distribution.
66
+ *
67
+ * @category schemas
68
+ * @since 4.0.0
69
+ */
70
+ export const ChoiceAnswer = Schema.Struct({
71
+ type: Schema.Literal("choice"),
72
+ choice: Schema.String,
73
+ probabilities: Schema.Record(Schema.String, Schema.Number),
74
+ confidence: Schema.Number
75
+ })
76
+
77
+ /**
78
+ * A zero-based rating and index-keyed distribution.
79
+ *
80
+ * @category schemas
81
+ * @since 4.0.0
82
+ */
83
+ export const ScoreAnswer = Schema.Struct({
84
+ type: Schema.Literal("score"),
85
+ score: Schema.Number,
86
+ probabilities: Schema.Record(Schema.String, Schema.Number),
87
+ confidence: Schema.Number,
88
+ legend: Schema.optional(Schema.Record(Schema.String, Schema.String))
89
+ })
90
+
91
+ /**
92
+ * A Bernoulli probability.
93
+ *
94
+ * @category schemas
95
+ * @since 4.0.0
96
+ */
97
+ export const NoulAnswer = Schema.Struct({ type: Schema.Literal("noul"), noul: Schema.Number })
98
+
99
+ /**
100
+ * A System One answer.
101
+ *
102
+ * @category schemas
103
+ * @since 4.0.0
104
+ */
105
+ export const Answer = Schema.Union([ChoiceAnswer, ScoreAnswer, NoulAnswer])
106
+
107
+ /**
108
+ * Answers and token usage for a batch.
109
+ *
110
+ * @category schemas
111
+ * @since 4.0.0
112
+ */
113
+ export const SystemOneResponse = Schema.Struct({
114
+ model: Schema.String,
115
+ answers: Schema.Record(Schema.String, Answer),
116
+ usage: Schema.optional(Schema.Struct({
117
+ input_tokens: Schema.optional(Schema.Number),
118
+ output_tokens: Schema.optional(Schema.Number)
119
+ }))
120
+ })
121
+
122
+ /**
123
+ * Available TypeSafe models.
124
+ *
125
+ * @category schemas
126
+ * @since 4.0.0
127
+ */
128
+ export const ListModelsResponse = Schema.Struct({
129
+ models: Schema.Array(Schema.Struct({
130
+ name: Schema.String,
131
+ description: Schema.optional(Schema.String),
132
+ release_date: Schema.optional(Schema.String)
133
+ }))
134
+ })
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @since 4.0.0
3
+ */
4
+
5
+ // @barrel
6
+
7
+ /**
8
+ * @since 4.0.0
9
+ */
10
+ export * as TypeSafeClient from "./TypeSafeClient.ts"
11
+
12
+ /**
13
+ * @since 4.0.0
14
+ */
15
+ export * as TypeSafeConfig from "./TypeSafeConfig.ts"
16
+
17
+ /**
18
+ * @since 4.0.0
19
+ */
20
+ export * as TypeSafeDecisionModel from "./TypeSafeDecisionModel.ts"
21
+
22
+ /**
23
+ * @since 4.0.0
24
+ */
25
+ export * as TypeSafeSchema from "./TypeSafeSchema.ts"
@@ -0,0 +1,113 @@
1
+ import * as Duration from "effect/Duration"
2
+ import * as Effect from "effect/Effect"
3
+ import * as Num from "effect/Number"
4
+ import * as Option from "effect/Option"
5
+ import * as Redactable from "effect/Redactable"
6
+ import * as Schema from "effect/Schema"
7
+ import * as AiError from "effect/unstable/ai/AiError"
8
+ import type * as HttpClientError from "effect/unstable/http/HttpClientError"
9
+ import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"
10
+
11
+ const requestDetails = (request: HttpClientRequest.HttpClientRequest) => ({
12
+ method: request.method,
13
+ url: request.url,
14
+ urlParams: Array.from(request.urlParams),
15
+ hash: Option.getOrUndefined(request.hash),
16
+ headers: Redactable.redact(request.headers) as Record<string, string>
17
+ })
18
+
19
+ const ErrorBody = Schema.Struct({
20
+ message: Schema.optional(Schema.String),
21
+ type: Schema.optional(Schema.String),
22
+ code: Schema.optional(Schema.String)
23
+ })
24
+
25
+ const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody)
26
+
27
+ const nonNegative = (value: string | undefined): number | undefined => {
28
+ if (value === undefined) return undefined
29
+ const parsed = Option.getOrUndefined(Num.parse(value))
30
+ return parsed !== undefined && Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined
31
+ }
32
+
33
+ const retryAfter = (headers: Readonly<Record<string, string>>) => {
34
+ const ms = nonNegative(headers["retry-after-ms"])
35
+ if (ms !== undefined) return Duration.millis(ms)
36
+ const raw = headers["retry-after"]
37
+ if (raw === undefined || raw.trim() === "") return undefined
38
+ const seconds = nonNegative(raw)
39
+ if (seconds !== undefined) return Duration.seconds(seconds)
40
+ const date = Date.parse(raw)
41
+ return Number.isNaN(date) ? undefined : Duration.millis(Math.max(0, date - Date.now()))
42
+ }
43
+
44
+ export const mapSchemaError = (error: Schema.SchemaError, method: string): AiError.AiError =>
45
+ AiError.make({
46
+ module: "TypeSafeClient",
47
+ method,
48
+ reason: AiError.InvalidOutputError.fromSchemaError(error)
49
+ })
50
+
51
+ export const mapHttpClientError = Effect.fnUntraced(
52
+ function*(error: HttpClientError.HttpClientError, method: string): Effect.fn.Return<never, AiError.AiError> {
53
+ const source = error.reason
54
+ let reason: AiError.AiErrorReason
55
+ switch (source._tag) {
56
+ case "TransportError":
57
+ case "EncodeError":
58
+ case "InvalidUrlError":
59
+ reason = new AiError.NetworkError({
60
+ reason: source._tag,
61
+ description: source.description,
62
+ request: requestDetails(source.request)
63
+ })
64
+ break
65
+ case "DecodeError":
66
+ case "EmptyBodyError":
67
+ reason = new AiError.InvalidOutputError({
68
+ description: source.description ?? "Failed to decode TypeSafe response"
69
+ })
70
+ break
71
+ case "StatusCodeError": {
72
+ const { request, response } = source
73
+ const body = yield* response.text.pipe(Effect.catch(() => Effect.succeed(source.description)))
74
+ const parsed = yield* Effect.try(() => JSON.parse(body ?? "")).pipe(Effect.orElseSucceed(() => undefined))
75
+ const details = Option.getOrUndefined(decodeErrorBody(parsed))
76
+ const http = {
77
+ request: requestDetails(request),
78
+ response: { status: response.status, headers: Redactable.redact(response.headers) as Record<string, string> },
79
+ body
80
+ }
81
+ const description = AiError.buildErrorDescription({
82
+ status: response.status,
83
+ method: request.method,
84
+ url: request.url,
85
+ body,
86
+ message: details?.message,
87
+ errorCode: details?.code,
88
+ errorType: details?.type,
89
+ requestId: response.headers["x-typesafe-request-id"]
90
+ })
91
+ if (response.status === 429) {
92
+ reason = new AiError.RateLimitError({
93
+ retryAfter: retryAfter(response.headers),
94
+ http,
95
+ metadata: {
96
+ typesafe: {
97
+ requestId: response.headers["x-typesafe-request-id"] ?? null,
98
+ errorCode: details?.code ?? null,
99
+ errorType: details?.type ?? null
100
+ }
101
+ }
102
+ })
103
+ } else if (response.status === 404 || response.status === 422) {
104
+ reason = new AiError.InvalidRequestError({ description, http })
105
+ } else {
106
+ reason = AiError.reasonFromHttpStatus({ status: response.status, description, http })
107
+ }
108
+ break
109
+ }
110
+ }
111
+ return yield* AiError.make({ module: "TypeSafeClient", method, reason })
112
+ }
113
+ )