|
| 1 | +--- |
| 2 | +"effect": minor |
| 3 | +--- |
| 4 | + |
| 5 | +add LayerMap module |
| 6 | + |
| 7 | +A `LayerMap` allows you to create a map of Layer's that can be used to |
| 8 | +dynamically access resources based on a key. |
| 9 | + |
| 10 | +Here is an example of how you can use a `LayerMap` to create a service that |
| 11 | +provides access to multiple OpenAI completions services. |
| 12 | + |
| 13 | +```ts |
| 14 | +import { Completions } from "@effect/ai" |
| 15 | +import { OpenAiClient, OpenAiCompletions } from "@effect/ai-openai" |
| 16 | +import { FetchHttpClient } from "@effect/platform" |
| 17 | +import { NodeRuntime } from "@effect/platform-node" |
| 18 | +import { Config, Effect, Layer, LayerMap } from "effect" |
| 19 | + |
| 20 | +// create the openai client layer |
| 21 | +const OpenAiLayer = OpenAiClient.layerConfig({ |
| 22 | + apiKey: Config.redacted("OPENAI_API_KEY") |
| 23 | +}).pipe(Layer.provide(FetchHttpClient.layer)) |
| 24 | + |
| 25 | +// create a service that wraps a LayerMap |
| 26 | +class AiClients extends LayerMap.Service<AiClients>()("AiClients", { |
| 27 | + // this LayerMap will provide the ai Completions service |
| 28 | + provides: Completions.Completions, |
| 29 | + |
| 30 | + // define the lookup function for the layer map |
| 31 | + // |
| 32 | + // The returned Layer will be used to provide the Completions service for the |
| 33 | + // given model. |
| 34 | + lookup: (model: OpenAiCompletions.Model) => |
| 35 | + OpenAiCompletions.layer({ model }), |
| 36 | + |
| 37 | + // If a layer is not used for a certain amount of time, it can be removed |
| 38 | + idleTimeToLive: "5 seconds", |
| 39 | + |
| 40 | + // Supply the dependencies for the layers in the LayerMap |
| 41 | + dependencies: [OpenAiLayer] |
| 42 | +}) {} |
| 43 | + |
| 44 | +// usage |
| 45 | +Effect.gen(function* () { |
| 46 | + // access and use the generic Completions service |
| 47 | + const ai = yield* Completions.Completions |
| 48 | + const response = yield* ai.create("Hello, world!") |
| 49 | + console.log(response.text) |
| 50 | +}).pipe( |
| 51 | + // use the AiClients service to provide a variant of the Completions service |
| 52 | + AiClients.provide("gpt-4o"), |
| 53 | + // provide the LayerMap service |
| 54 | + Effect.provide(AiClients.Default), |
| 55 | + NodeRuntime.runMain |
| 56 | +) |
| 57 | +``` |
0 commit comments