messages.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { Schema } from "effect"
  2. import { ToolContent, ToolFileContent, ToolTextContent } from "@opencode-ai/schema/llm"
  3. import { JsonSchema, MessageRole, ProviderMetadata } from "./ids"
  4. import { CacheHint, CachePolicy, GenerationOptions, HttpOptions, ModelSchema, ProviderOptions } from "./options"
  5. import { isRecord } from "../utils/record"
  6. const systemPartSchema = Schema.Struct({
  7. type: Schema.Literal("text"),
  8. text: Schema.String,
  9. cache: Schema.optional(CacheHint),
  10. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  11. }).annotate({ identifier: "LLM.SystemPart" })
  12. export type SystemPart = Schema.Schema.Type<typeof systemPartSchema>
  13. const makeSystemPart = (text: string): SystemPart => ({ type: "text", text })
  14. export const SystemPart = Object.assign(systemPartSchema, {
  15. make: makeSystemPart,
  16. content: (input?: string | SystemPart | ReadonlyArray<SystemPart>) => {
  17. if (input === undefined) return []
  18. return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input]
  19. },
  20. })
  21. export const TextPart = Schema.Struct({
  22. type: Schema.Literal("text"),
  23. text: Schema.String,
  24. cache: Schema.optional(CacheHint),
  25. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  26. providerMetadata: Schema.optional(ProviderMetadata),
  27. }).annotate({ identifier: "LLM.Content.Text" })
  28. export type TextPart = Schema.Schema.Type<typeof TextPart>
  29. export const MediaPart = Schema.Struct({
  30. type: Schema.Literal("media"),
  31. mediaType: Schema.String,
  32. data: Schema.Union([Schema.String, Schema.Uint8Array]),
  33. filename: Schema.optional(Schema.String),
  34. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  35. }).annotate({ identifier: "LLM.Content.Media" })
  36. export type MediaPart = Schema.Schema.Type<typeof MediaPart>
  37. export { ToolContent, ToolFileContent, ToolTextContent }
  38. const isToolResultValue = (value: unknown): value is ToolResultValue =>
  39. isRecord(value) &&
  40. (value.type === "text" || value.type === "json" || value.type === "error" || value.type === "content") &&
  41. "value" in value
  42. export const ToolResultValue = Object.assign(
  43. Schema.Union([
  44. Schema.Struct({
  45. type: Schema.Literal("json"),
  46. value: Schema.Unknown,
  47. }),
  48. Schema.Struct({
  49. type: Schema.Literal("text"),
  50. value: Schema.Unknown,
  51. }),
  52. Schema.Struct({
  53. type: Schema.Literal("error"),
  54. value: Schema.Unknown,
  55. }),
  56. Schema.Struct({
  57. type: Schema.Literal("content"),
  58. value: Schema.Array(ToolContent),
  59. }),
  60. ]).annotate({ identifier: "LLM.ToolResult" }),
  61. {
  62. is: isToolResultValue,
  63. make: (value: unknown, type: ToolResultValue["type"] = "json"): ToolResultValue => {
  64. if (isToolResultValue(value)) return value
  65. if (type === "content") return { type, value: Array.isArray(value) ? value : [] }
  66. return { type, value }
  67. },
  68. },
  69. )
  70. export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
  71. export interface ToolOutput {
  72. readonly structured: unknown
  73. readonly content: ReadonlyArray<ToolContent>
  74. }
  75. export const ToolOutput = Object.assign(
  76. Schema.Struct({
  77. structured: Schema.Unknown,
  78. content: Schema.Array(ToolContent),
  79. }).annotate({ identifier: "LLM.ToolOutput" }),
  80. {
  81. make: (structured: unknown, content: ReadonlyArray<ToolContent> = []): ToolOutput => ({ structured, content }),
  82. fromResultValue: (result: ToolResultValue): ToolOutput | undefined => {
  83. switch (result.type) {
  84. case "json":
  85. return { structured: result.value, content: [] }
  86. case "text":
  87. return { structured: {}, content: [{ type: "text", text: toolResultText(result.value) }] }
  88. case "content":
  89. return { structured: {}, content: result.value }
  90. case "error":
  91. return undefined
  92. }
  93. },
  94. toResultValue: (output: ToolOutput): ToolResultValue => {
  95. if (output.content.length === 0) return { type: "json", value: output.structured }
  96. if (output.content.length === 1 && output.content[0]?.type === "text")
  97. return { type: "text", value: output.content[0].text }
  98. return { type: "content", value: output.content }
  99. },
  100. },
  101. )
  102. const toolResultText = (value: unknown) => {
  103. if (typeof value === "string") return value
  104. try {
  105. return JSON.stringify(value) ?? String(value)
  106. } catch {
  107. return String(value)
  108. }
  109. }
  110. export const ToolCallPart = Object.assign(
  111. Schema.Struct({
  112. type: Schema.Literal("tool-call"),
  113. id: Schema.String,
  114. name: Schema.String,
  115. input: Schema.Unknown,
  116. providerExecuted: Schema.optional(Schema.Boolean),
  117. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  118. providerMetadata: Schema.optional(ProviderMetadata),
  119. }).annotate({ identifier: "LLM.Content.ToolCall" }),
  120. {
  121. make: (input: Omit<ToolCallPart, "type">): ToolCallPart => ({ type: "tool-call", ...input }),
  122. },
  123. )
  124. export type ToolCallPart = Schema.Schema.Type<typeof ToolCallPart>
  125. export const ToolResultPart = Object.assign(
  126. Schema.Struct({
  127. type: Schema.Literal("tool-result"),
  128. id: Schema.String,
  129. name: Schema.String,
  130. result: ToolResultValue,
  131. providerExecuted: Schema.optional(Schema.Boolean),
  132. cache: Schema.optional(CacheHint),
  133. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  134. providerMetadata: Schema.optional(ProviderMetadata),
  135. }).annotate({ identifier: "LLM.Content.ToolResult" }),
  136. {
  137. make: (
  138. input: Omit<ToolResultPart, "type" | "result"> & {
  139. readonly result: unknown
  140. readonly resultType?: ToolResultValue["type"]
  141. },
  142. ): ToolResultPart => ({
  143. type: "tool-result",
  144. id: input.id,
  145. name: input.name,
  146. result: ToolResultValue.make(input.result, input.resultType),
  147. providerExecuted: input.providerExecuted,
  148. cache: input.cache,
  149. metadata: input.metadata,
  150. providerMetadata: input.providerMetadata,
  151. }),
  152. },
  153. )
  154. export type ToolResultPart = Schema.Schema.Type<typeof ToolResultPart>
  155. export const ReasoningPart = Schema.Struct({
  156. type: Schema.Literal("reasoning"),
  157. text: Schema.String,
  158. encrypted: Schema.optional(Schema.String),
  159. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  160. providerMetadata: Schema.optional(ProviderMetadata),
  161. }).annotate({ identifier: "LLM.Content.Reasoning" })
  162. export type ReasoningPart = Schema.Schema.Type<typeof ReasoningPart>
  163. export const ContentPart = Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
  164. Schema.toTaggedUnion("type"),
  165. )
  166. export type ContentPart = Schema.Schema.Type<typeof ContentPart>
  167. export class Message extends Schema.Class<Message>("LLM.Message")({
  168. id: Schema.optional(Schema.String),
  169. role: MessageRole,
  170. content: Schema.Array(ContentPart),
  171. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  172. native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  173. }) {}
  174. export namespace Message {
  175. export type ContentInput = string | ContentPart | ReadonlyArray<ContentPart>
  176. export type SystemContentInput = string | TextPart | ReadonlyArray<TextPart>
  177. export type Input = Omit<ConstructorParameters<typeof Message>[0], "content"> & {
  178. readonly content: ContentInput
  179. }
  180. export const text = (value: string): ContentPart => ({ type: "text", text: value })
  181. export const content = (input: ContentInput) =>
  182. typeof input === "string" ? [text(input)] : Array.isArray(input) ? [...input] : [input]
  183. export const make = (input: Message | Input) => {
  184. if (input instanceof Message) return input
  185. return new Message({ ...input, content: content(input.content) })
  186. }
  187. export const user = (content: ContentInput) => make({ role: "user", content })
  188. export const assistant = (content: ContentInput) => make({ role: "assistant", content })
  189. /**
  190. * Add an operator-authored instruction at this chronological point in the
  191. * conversation. This is distinct from the initial `LLMRequest.system`
  192. * prompt. Keep raw retrieved, tool, and web content out of privileged system
  193. * updates; pass that untrusted content through ordinary user/tool channels.
  194. */
  195. export const system = (content: SystemContentInput) => make({ role: "system", content })
  196. export const tool = (result: ToolResultPart | Parameters<typeof ToolResultPart.make>[0]) =>
  197. make({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] })
  198. }
  199. export class ToolDefinition extends Schema.Class<ToolDefinition>("LLM.ToolDefinition")({
  200. name: Schema.String,
  201. description: Schema.String,
  202. inputSchema: JsonSchema,
  203. outputSchema: Schema.optional(JsonSchema),
  204. cache: Schema.optional(CacheHint),
  205. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  206. native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  207. }) {}
  208. export namespace ToolDefinition {
  209. export type Input = ToolDefinition | ConstructorParameters<typeof ToolDefinition>[0]
  210. /** Normalize tool definition input into the canonical `ToolDefinition` class. */
  211. export const make = (input: Input) => (input instanceof ToolDefinition ? input : new ToolDefinition(input))
  212. }
  213. export class ToolChoice extends Schema.Class<ToolChoice>("LLM.ToolChoice")({
  214. type: Schema.Literals(["auto", "none", "required", "tool"]),
  215. name: Schema.optional(Schema.String),
  216. }) {}
  217. export namespace ToolChoice {
  218. export type Mode = Exclude<ToolChoice["type"], "tool">
  219. export type Input = ToolChoice | ConstructorParameters<typeof ToolChoice>[0] | ToolDefinition | string
  220. const isMode = (value: string): value is Mode => value === "auto" || value === "none" || value === "required"
  221. /** Select a specific named tool. */
  222. export const named = (value: string) => new ToolChoice({ type: "tool", name: value })
  223. /** Normalize ergonomic tool-choice inputs into the canonical `ToolChoice` class. */
  224. export const make = (input: Input) => {
  225. if (input instanceof ToolChoice) return input
  226. if (input instanceof ToolDefinition) return named(input.name)
  227. if (typeof input === "string") return isMode(input) ? new ToolChoice({ type: input }) : named(input)
  228. return new ToolChoice(input)
  229. }
  230. }
  231. export const ResponseFormat = Schema.Union([
  232. Schema.Struct({ type: Schema.Literal("text") }),
  233. Schema.Struct({ type: Schema.Literal("json"), schema: JsonSchema }),
  234. Schema.Struct({ type: Schema.Literal("tool"), tool: ToolDefinition }),
  235. ]).pipe(Schema.toTaggedUnion("type"))
  236. export type ResponseFormat = Schema.Schema.Type<typeof ResponseFormat>
  237. export class LLMRequest extends Schema.Class<LLMRequest>("LLM.Request")({
  238. id: Schema.optional(Schema.String),
  239. model: ModelSchema,
  240. system: Schema.Array(SystemPart),
  241. messages: Schema.Array(Message),
  242. tools: Schema.Array(ToolDefinition),
  243. toolChoice: Schema.optional(ToolChoice),
  244. generation: Schema.optional(GenerationOptions),
  245. providerOptions: Schema.optional(ProviderOptions),
  246. http: Schema.optional(HttpOptions),
  247. responseFormat: Schema.optional(ResponseFormat),
  248. cache: Schema.optional(CachePolicy),
  249. metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
  250. }) {}
  251. export namespace LLMRequest {
  252. export type Input = ConstructorParameters<typeof LLMRequest>[0]
  253. export const input = (request: LLMRequest): Input => ({
  254. id: request.id,
  255. model: request.model,
  256. system: request.system,
  257. messages: request.messages,
  258. tools: request.tools,
  259. toolChoice: request.toolChoice,
  260. generation: request.generation,
  261. providerOptions: request.providerOptions,
  262. http: request.http,
  263. responseFormat: request.responseFormat,
  264. cache: request.cache,
  265. metadata: request.metadata,
  266. })
  267. export const update = (request: LLMRequest, patch: Partial<Input>) => {
  268. if (Object.keys(patch).length === 0) return request
  269. return new LLMRequest({
  270. ...input(request),
  271. ...patch,
  272. model: patch.model ?? request.model,
  273. })
  274. }
  275. }