├── .github
└── workflows
│ └── preternatural-build.yml
├── .gitignore
├── Images
├── ios-active.svg
├── ios.svg
├── ipados-active.svg
├── ipados.svg
├── macos-active.svg
├── macos.svg
├── tvos-active.svg
├── tvos.svg
├── watchos-active.svg
└── watchos.svg
├── LICENSE
├── Package.resolved
├── Package.swift
├── README.md
├── Sources
├── AI
│ └── module.swift
├── Anthropic
│ ├── Intramodular
│ │ ├── Anthropic+LLMRequestHandling.swift
│ │ ├── Anthropic.API.RequestBodies.swift
│ │ ├── Anthropic.API.swift
│ │ ├── Anthropic.ChatMessage+LargeLanguageModels.swift
│ │ ├── Anthropic.ChatMessage.Content.swift
│ │ ├── Anthropic.ChatMessage.swift
│ │ ├── Anthropic.Client+CoreMI.swift
│ │ ├── Anthropic.Client.swift
│ │ ├── Anthropic.Model-Latest.swift
│ │ ├── Anthropic.Model.swift
│ │ ├── Anthropic.Tool.swift
│ │ └── Anthropic.swift
│ └── module.swift
├── Cohere
│ ├── Cohere.swift
│ └── Intramodular
│ │ ├── Cohere.APISpecification.swift
│ │ ├── Cohere.Client+TextEmbeddingsRequestHandling.swift.swift
│ │ ├── Cohere.Client.swift
│ │ ├── Cohere.Embeddings.swift
│ │ └── Cohere.Model.swift
├── CoreMI
│ ├── Intramodular
│ │ ├── ASR
│ │ │ └── AutomaticSpeechRecognitionRequest.swift
│ │ ├── Developer
│ │ │ └── _PreternaturalDotFile.swift
│ │ ├── Foundation
│ │ │ ├── CoreMI.Context.swift
│ │ │ └── CoreMI.RequestHandling.swift
│ │ ├── Model Identifier
│ │ │ ├── ModelIdentifier+Utilities.swift
│ │ │ ├── ModelIdentifier.Provider.swift
│ │ │ ├── ModelIdentifier.swift
│ │ │ ├── ModelIdentifierConvertible.swift
│ │ │ └── ModelIdentifierScope.swift
│ │ ├── Service
│ │ │ ├── CoreMI._ServiceAccountProtocol.swift
│ │ │ ├── CoreMI._ServiceClientProtocol.swift
│ │ │ ├── CoreMI._ServiceCredentialProtocol.swift
│ │ │ ├── CoreMI._ServiceCredentialTypes.swift
│ │ │ ├── CoreMI._ServiceFileDrive.swift
│ │ │ └── CoreMI._ServiceVendorIdentifier.swift
│ │ └── TTS
│ │ │ ├── SpeechSynthesizers.VoiceName.swift
│ │ │ ├── SpeechSynthesizers.swift
│ │ │ ├── TTSRequest.swift
│ │ │ └── TTSRequestHandling.swift
│ └── module.swift
├── ElevenLabs
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── ElevenLabs.APISpecification.RequestBodies.swift
│ │ │ ├── ElevenLabs.APISpecification.ResponseBodies.swift
│ │ │ └── ElevenLabs.APISpecification.swift
│ │ ├── ElevenLabs.Client.swift
│ │ ├── ElevenLabs.Model.swift
│ │ ├── ElevenLabs.Voice.swift
│ │ ├── ElevenLabs.VoiceSettings.swift
│ │ └── ElevenLabs.swift
│ └── module.swift
├── Groq
│ ├── Intramodular
│ │ ├── Groq+LLMRequestHandling.swift
│ │ ├── Groq.APISpecification.swift
│ │ ├── Groq.Client.swift
│ │ ├── Groq.Model.swift
│ │ └── Groq.swift
│ └── module.swift
├── HuggingFace
│ ├── Intramodular
│ │ ├── HuggingFace.Downloader.swift
│ │ ├── HuggingFace.Hub.Client.swift
│ │ ├── HuggingFace.Hub.swift
│ │ └── HuggingFace.swift
│ └── Resources
│ │ ├── gpt2_tokenizer_config.json
│ │ └── t5_tokenizer_config.json
├── HumeAI
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── HumeAI.APISpecification.RequestBodies.swift
│ │ │ ├── HumeAI.APISpecification.swift
│ │ │ └── HumeAI.APISpeicification.ResponseBodies.swift
│ │ ├── HumeAI.Client-Batch.swift
│ │ ├── HumeAI.Client-Chat.swift
│ │ ├── HumeAI.Client-ChatGroups.swift
│ │ ├── HumeAI.Client-Chats.swift
│ │ ├── HumeAI.Client-Configs.swift
│ │ ├── HumeAI.Client-CustomVoices.swift
│ │ ├── HumeAI.Client-Datasets.swift
│ │ ├── HumeAI.Client-Files.swift
│ │ ├── HumeAI.Client-Jobs.swift
│ │ ├── HumeAI.Client-Models.swift
│ │ ├── HumeAI.Client-Prompts.swift
│ │ ├── HumeAI.Client-Stream.swift
│ │ ├── HumeAI.Client-Tools.swift
│ │ ├── HumeAI.Client.swift
│ │ ├── HumeAI.Model.swift
│ │ ├── HumeAI.swift
│ │ └── Models
│ │ │ ├── HumeAI.Chat.swift
│ │ │ ├── HumeAI.ChatEvent.swift
│ │ │ ├── HumeAI.ChatGroup.swift
│ │ │ ├── HumeAI.ChatMessage.swift
│ │ │ ├── HumeAI.ChatResponse.swift
│ │ │ ├── HumeAI.Config.swift
│ │ │ ├── HumeAI.Dataset.swift
│ │ │ ├── HumeAI.File.swift
│ │ │ ├── HumeAI.FileInput.swift
│ │ │ ├── HumeAI.Job.swift
│ │ │ ├── HumeAI.JobPrediction.swift
│ │ │ ├── HumeAI.Models.swift
│ │ │ ├── HumeAI.Prompt.swift
│ │ │ ├── HumeAI.Tool.swift
│ │ │ └── HumeAI.Voice.swift
│ └── module.swift
├── Jina
│ ├── Intramodular
│ │ ├── Jina.APISpecification.swift
│ │ ├── Jina.Client+TextEmbeddingsRequestHandling.swift
│ │ ├── Jina.Client.swift
│ │ ├── Jina.Embeddings.swift
│ │ ├── Jina.Model.swift
│ │ └── Jina.swift
│ └── module.swift
├── LargeLanguageModels
│ ├── Intramodular
│ │ ├── LLMs
│ │ │ ├── AbstractLLM.ChatCompletionDecodable.swift
│ │ │ ├── AbstractLLM.ChatCompletionDecodableResultType.swift
│ │ │ ├── AbstractLLM.ChatCompletionStream.swift
│ │ │ ├── AbstractLLM.ChatOrTextCompletion.swift
│ │ │ ├── AbstractLLM.ChatOrTextPrompt.swift
│ │ │ ├── AbstractLLM.CompletionParameters.swift
│ │ │ ├── AbstractLLM.swift
│ │ │ ├── Chat
│ │ │ │ ├── AbstractLLM.ChatCompletion.StopReason.swift
│ │ │ │ ├── AbstractLLM.ChatCompletion.swift
│ │ │ │ ├── AbstractLLM.ChatCompletionParameters.swift
│ │ │ │ ├── AbstractLLM.ChatMessage-Initializers.swift
│ │ │ │ ├── AbstractLLM.ChatMessage.Partial.swift
│ │ │ │ ├── AbstractLLM.ChatMessage.swift
│ │ │ │ ├── AbstractLLM.ChatPrompt.swift
│ │ │ │ ├── AbstractLLM.ChatRole.swift
│ │ │ │ └── LLMRequestHandling+Chat.swift
│ │ │ ├── Function Calling
│ │ │ │ ├── Abstract.LLM.ChatFunctionCall.swift
│ │ │ │ ├── AbstractLLM.ChatFunction.swift
│ │ │ │ ├── AbstractLLM.ChatFunctionDefinition.swift
│ │ │ │ ├── AbstractLLM.ChatFunctionExecuting.swift
│ │ │ │ └── AbstractLLM.ResultOfFunctionCall.swift
│ │ │ ├── LLMRequestHandling-Internal.swift
│ │ │ ├── LLMRequestHandling.swift
│ │ │ └── Text
│ │ │ │ ├── AbstractLLM.TextCompletion.swift
│ │ │ │ ├── AbstractLLM.TextCompletionParameters.swift
│ │ │ │ └── AbstractLLM.TextPrompt.swift
│ │ ├── Prompt Literal
│ │ │ ├── AbstractLLM._AnyPromptCompletionConfigurationType.swift
│ │ │ ├── PromptContextValues.swift
│ │ │ ├── PromptLiteral+AbstractLLM.Prompt.swift
│ │ │ ├── PromptLiteral-Ergonomics.swift
│ │ │ ├── PromptLiteral-Initializers.swift
│ │ │ ├── PromptLiteral.StringInterpolation.Component.Payload.swift
│ │ │ ├── PromptLiteral.StringInterpolation.Component.swift
│ │ │ ├── PromptLiteral.StringInterpolation.swift
│ │ │ ├── PromptLiteral._Degenerate.swift
│ │ │ ├── PromptLiteral.swift
│ │ │ ├── PromptLiteralContext.swift
│ │ │ ├── PromptLiteralConvertible.swift
│ │ │ ├── PromptLiteralError.swift
│ │ │ ├── PromptLiteralTokenizer.swift
│ │ │ ├── PromptMatterRole.swift
│ │ │ ├── _PromptLiteralEncodingContainer.swift
│ │ │ └── _opaque_DynamicPromptVariable.swift
│ │ └── Text Embeddings
│ │ │ ├── ISO639LanguageCode.swift
│ │ │ ├── LLMRequestHandlingError.swift
│ │ │ ├── NLEmbeddingProvider.swift
│ │ │ ├── NLLanguage.Name.swift
│ │ │ ├── SingleTextEmbedding.swift
│ │ │ ├── TextEmbeddings.swift
│ │ │ ├── TextEmbeddingsRequestHandling.swift
│ │ │ ├── _RawTextEmbedding.swift
│ │ │ └── _StopwordsMap.swift
│ ├── Resources
│ │ └── stopwords-iso.json
│ └── module.swift
├── Mistral
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── Mistral.APISpecification.RequestBodies.swift
│ │ │ └── Mistral.APISpecification.ResponseBodies.swift
│ │ ├── Mistral.Client+LLMRequestHandling.swift
│ │ ├── Mistral.Client+TextEmbeddingsRequestHandling.swift
│ │ ├── Mistral.Client.swift
│ │ ├── Mistral.Model.swift
│ │ ├── Mistral.swift
│ │ └── Models
│ │ │ ├── Mistral.ChatMessage.swift
│ │ │ └── Mistral.Embedding.swift
│ └── module.swift
├── NeetsAI
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── NeetsAI.APISpecification.RequestBodies.swift
│ │ │ ├── NeetsAI.APISpecification.ResponseBodies.swift
│ │ │ └── NeetsAI.APISpecification.swift
│ │ ├── Models
│ │ │ ├── NeetsAI.ChatMessage.swift
│ │ │ └── NeetsAI.Voice.swift
│ │ ├── NeetsAI.Client.swift
│ │ ├── NeetsAI.Model.swift
│ │ └── NeetsAI.swift
│ └── module.swift
├── Ollama
│ ├── Intramodular
│ │ ├── Ollama+LLMRequestHandling.swift
│ │ ├── Ollama.APISpecification+Requests.swift
│ │ ├── Ollama.APISpecification+Responses.swift
│ │ ├── Ollama.APISpecification.swift
│ │ ├── Ollama.ChatMessage.swift
│ │ ├── Ollama.Model.swift
│ │ └── Ollama.swift
│ └── module.swift
├── OpenAI
│ ├── Intramodular (WIP)
│ │ └── OpenAI.ChatFunctionHandler.swift
│ ├── Intramodular
│ │ ├── API Client
│ │ │ ├── OpenAI.Client+CoreMI.swift
│ │ │ ├── OpenAI.Client+LLMRequestHandling.swift
│ │ │ ├── OpenAI.Client+TextEmbeddingsRequestHandling.swift
│ │ │ ├── OpenAI.Client-Embeddings.swift
│ │ │ ├── OpenAI.Client-Files.swift
│ │ │ ├── OpenAI.Client-FineTuning.swift
│ │ │ ├── OpenAI.Client-Image.swift
│ │ │ ├── OpenAI.Client-Speech.swift
│ │ │ ├── OpenAI.Client-VectorStore.swift
│ │ │ ├── OpenAI.Client-Whisper.swift
│ │ │ ├── OpenAI.Client.ChatCompletionParameters.swift
│ │ │ └── OpenAI.Client.swift
│ │ ├── API Specification
│ │ │ ├── OpenAI.APISpecification.RequestBodies.swift
│ │ │ ├── OpenAI.APISpecification.ResponseBodies.swift
│ │ │ └── OpenAI.APISpecification.swift
│ │ ├── Assistants
│ │ │ └── OpenAI.AssistantSession.swift
│ │ ├── Miscellaneous
│ │ │ └── Tiktoken
│ │ │ │ ├── BPEVocabulary.swift
│ │ │ │ ├── CoreBPE.swift
│ │ │ │ ├── OpenAI.Model+BPEVocabulary.swift
│ │ │ │ ├── Tiktoken.Encoding.swift
│ │ │ │ ├── Tiktoken.swift
│ │ │ │ ├── TokenizerResources.swift
│ │ │ │ └── _VocabularyFileDecoder.swift
│ │ ├── Models
│ │ │ ├── OpenAI.Assistant.swift
│ │ │ ├── OpenAI.AssistantFile.swift
│ │ │ ├── OpenAI.AudioTranscription.swift
│ │ │ ├── OpenAI.ChatCompletion.swift
│ │ │ ├── OpenAI.ChatFunctionDefinition.swift
│ │ │ ├── OpenAI.ChatMessage.swift
│ │ │ ├── OpenAI.ChatMessageBody.swift
│ │ │ ├── OpenAI.ChatRole.swift
│ │ │ ├── OpenAI.Embedding.swift
│ │ │ ├── OpenAI.File.swift
│ │ │ ├── OpenAI.FineTuning.swift
│ │ │ ├── OpenAI.Image.swift
│ │ │ ├── OpenAI.List.swift
│ │ │ ├── OpenAI.Message.Content.swift
│ │ │ ├── OpenAI.Message.swift
│ │ │ ├── OpenAI.Model-Latest.swift
│ │ │ ├── OpenAI.Model.swift
│ │ │ ├── OpenAI.Object.swift
│ │ │ ├── OpenAI.ResponseFormat.swift
│ │ │ ├── OpenAI.Run.swift
│ │ │ ├── OpenAI.Speech.swift
│ │ │ ├── OpenAI.TextCompletion.swift
│ │ │ ├── OpenAI.Thread.swift
│ │ │ ├── OpenAI.ToolChoice.swift
│ │ │ ├── OpenAI.VectorStore.swift
│ │ │ └── OpenAI.Voice.swift
│ │ ├── OpenAI.ChatCompletionSession.swift
│ │ ├── OpenAI.ChatMessage+LargeLanguageModels.swift
│ │ ├── OpenAI.ModelRating.swift
│ │ └── OpenAI.swift
│ └── module.swift
├── Perplexity
│ ├── Intramodular
│ │ ├── Perplexity+LLMRequestHandling.swift
│ │ ├── Perplexity.APISpecification
│ │ │ ├── Perplexity.APISpecification.RequestBodies.swift
│ │ │ ├── Perplexity.APISpecification.ResponseBodies.swift
│ │ │ └── Perplexity.APISpecification.swift
│ │ ├── Perplexity.ChatMessage.swift
│ │ ├── Perplexity.Client.swift
│ │ ├── Perplexity.Model.swift
│ │ └── Perplexity.swift
│ └── module.swift
├── PlayHT
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── PlayHT.APISpecification.RequestBodies.swift
│ │ │ ├── PlayHT.APISpecification.swift
│ │ │ └── PlayHT.APISpeicification.ResponseBodies.swift
│ │ ├── Models
│ │ │ ├── PlayHT.OutputSettings.swift
│ │ │ ├── PlayHT.Voice.swift
│ │ │ └── PlayHT.VoiceSettings.swift
│ │ ├── PlayHT.Client.swift
│ │ ├── PlayHT.Model.swift
│ │ └── PlayHT.swift
│ └── module.swift
├── Rime
│ ├── Intramodular
│ │ ├── API
│ │ │ ├── Rime.APISpecification.RequestBodies.swift
│ │ │ ├── Rime.APISpecification.ResponseBodies.swift
│ │ │ └── Rime.APISpecification.swift
│ │ ├── Models
│ │ │ └── Rime.Voice.swift
│ │ ├── Rime.Client.OutputAudioType.swift
│ │ ├── Rime.Client.swift
│ │ ├── Rime.Model.swift
│ │ └── Rime.swift
│ └── module.swift
├── TogetherAI
│ ├── Intramodular
│ │ ├── TogetherAI.APISpecification.swift
│ │ ├── TogetherAI.Client.swift
│ │ ├── TogetherAI.Embeddings.swift
│ │ ├── TogetherAI.Model.swift
│ │ └── TogetherAI.swift
│ └── module.swift
├── VoyageAI
│ ├── Intramodular
│ │ ├── VoyageAI.APISpecification.swift
│ │ ├── VoyageAI.Client+TextEmbeddingsRequestHandling.swift
│ │ ├── VoyageAI.Client.swift
│ │ ├── VoyageAI.Embeddings.swift
│ │ ├── VoyageAI.Model.swift
│ │ └── VoyageAI.swift
│ └── module.swift
└── _Gemini
│ ├── Intramodular
│ ├── API
│ │ ├── _Gemini.APISpecification.RequestBodies.swift
│ │ ├── _Gemini.APISpecification.ResponseBodies.swift
│ │ └── _Gemini.APISpecification.swift
│ ├── Models
│ │ ├── Fine Tuning
│ │ │ ├── _Gemini.FineTuningExample.swift
│ │ │ ├── _Gemini.FineTuningExamples.swift
│ │ │ ├── _Gemini.Hyperparameters.swift
│ │ │ ├── _Gemini.TrainingData.swift
│ │ │ ├── _Gemini.TunedModel.swift
│ │ │ ├── _Gemini.TuningConfig.swift
│ │ │ ├── _Gemini.TuningOperation.swift
│ │ │ └── _Gemini.TuningTask.swift
│ │ ├── _Gemini.Content.swift
│ │ ├── _Gemini.File.swift
│ │ ├── _Gemini.FunctionCall.swift
│ │ ├── _Gemini.GenerationConfig.swift
│ │ ├── _Gemini.GoogleSearchRetrieval.swift
│ │ ├── _Gemini.Message.swift
│ │ └── _Gemini.Tool.swift
│ ├── _Gemini.Client+CodeExecution.swift
│ ├── _Gemini.Client+ContentGeneration.swift
│ ├── _Gemini.Client+CoreMI._ServiceClientProvisionedFileSpace.swift
│ ├── _Gemini.Client+Embeddings.swift
│ ├── _Gemini.Client+Files.swift
│ ├── _Gemini.Client+FineTuning.swift
│ ├── _Gemini.Client+FunctionCalling.swift
│ ├── _Gemini.Client+Grounding.swift
│ ├── _Gemini.Client.swift
│ ├── _Gemini.Model.swift
│ └── _Gemini.swift
│ └── module.swift
└── Tests
├── Anthropic
├── Intramodular
│ └── AnthropicTests.swift
└── module.swift
├── Cohere
├── Intramodular
│ └── EmbeddingsTests.swift
└── module.swift
├── ElevenLabs
├── Instramodular
│ └── SpeechTests.swift
└── module.swift
├── Groq
├── Intramodular
│ └── CompletionTests.swift
└── module.swift
├── HuggingFace
├── HuggingFaceHubClientTests.swift
└── HuggingFaceHubTests.swift
├── HumeAI
├── Intramodular
│ ├── Batch.swift
│ ├── Chat.swift
│ ├── ChatGroup.swift
│ ├── Config.swift
│ ├── Dataset.swift
│ ├── File.swift
│ ├── Job.swift
│ ├── Model.swift
│ ├── Prompts.swift
│ ├── Stream.swift
│ ├── Tools.swift
│ └── Voices.swift
└── module.swift
├── Jina
├── Intramodular
│ └── EmbeddingsTests.swift
└── module.swift
├── LargeLanguageModels
├── Intramodular
│ └── PromptLiteralTests.swift
└── main.swift
├── Mistral
├── Intramodular
│ └── EmbeddingsTests.swift
└── module.swift
├── NeetsAI
├── Intramodular
│ └── Tests.swift
└── module.swift
├── OpenAI
├── Intramodular
│ ├── CompletionTests.swift
│ ├── DALL_E_Tests.swift
│ ├── FileTests.swift
│ ├── FineTuningTests.swift
│ ├── FunctionCallingTests.swift
│ ├── StructuredOutputsTests.swift
│ ├── TranscriptionTests.swift
│ └── VectorStoreTests.swift
└── module.swift
├── Perplexity
├── Intramodular
│ └── CompletionTests.swift
└── module.swift
├── PlayHT
├── Intramodular
│ └── SpeechTests.swift
└── module.swift
├── TogetherAI
├── Intramodular
│ └── EmbeddingsTests.swift
└── module.swift
├── VoyageAI
├── Intramodular
│ └── EmbeddingsTests.swift
└── module.swift
└── _Gemini
├── Intramodular
├── _GeminiTests+CodeExecution.swift
├── _GeminiTests+Embeddings.swift
├── _GeminiTests+Files.swift
├── _GeminiTests+FineTuning.swift
├── _GeminiTests+FunctionCalling.swift
├── _GeminiTests+Grounding.swift
├── _GeminiTests+StructuredOutput.swift
└── _GeminiTests.swift
└── module.swift
/.github/workflows/preternatural-build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 | on:
3 | push:
4 | branches: [ main ]
5 | pull_request:
6 | branches: [ main ]
7 | workflow_dispatch:
8 | concurrency:
9 | group: ${{ github.workflow }}-${{ github.ref }}
10 | cancel-in-progress: true
11 | jobs:
12 | preternatural-build:
13 | name: Build (Xcode ${{ matrix.xcode }})
14 | runs-on: ghcr.io/cirruslabs/macos-runner:sequoia
15 | strategy:
16 | matrix:
17 | xcode: ['16.2', '16.3']
18 | steps:
19 | - name: Checkout repository
20 | uses: actions/checkout@v3
21 | - name: Run Preternatural Build
22 | uses: PreternaturalAI/preternatural-github-actions/preternatural-build@main
23 | with:
24 | xcode-version: ${{ matrix.xcode }}
25 | configurations: '["debug"]'
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .swiftpm/
3 | .swiftpm/*
4 | /*.xcodeproj
5 | /.build
6 | /Packages
7 | xcuserdata/
8 |
--------------------------------------------------------------------------------
/Images/ios-active.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/ios.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/ipados-active.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/ipados.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/macos-active.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/macos.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/tvos-active.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/tvos.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/watchos-active.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Images/watchos.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Preternatural AI, Inc.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Sources/AI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import CoreMI
6 | @_exported import LargeLanguageModels
7 | @_exported import OpenAI
8 | @_exported import SwallowMacrosClient
9 |
--------------------------------------------------------------------------------
/Sources/Anthropic/Intramodular/Anthropic.Client+CoreMI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import NetworkKit
7 | import Swallow
8 |
9 | extension Anthropic.Client: CoreMI._ServiceClientProtocol {
10 | public convenience init(
11 | account: (any CoreMI._ServiceAccountProtocol)?
12 | ) async throws {
13 | let account: any CoreMI._ServiceAccountProtocol = try account.unwrap()
14 | let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier = try account.serviceVendorIdentifier.unwrap()
15 |
16 | guard serviceVendorIdentifier == CoreMI._ServiceVendorIdentifier._Anthropic else {
17 | throw CoreMI._ServiceClientError.incompatibleVendor(serviceVendorIdentifier)
18 | }
19 |
20 | guard let credential = try account.credential as? CoreMI._ServiceCredentialTypes.APIKeyCredential else {
21 | throw CoreMI._ServiceClientError.invalidCredential(try account.credential)
22 | }
23 |
24 | self.init(apiKey: credential.apiKey)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/Anthropic/Intramodular/Anthropic.Client.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import NetworkKit
8 | import SwiftDI
9 |
10 | extension Anthropic {
11 | @RuntimeDiscoverable
12 | public final class Client: HTTPClient, PersistentlyRepresentableType, _StaticSwift.Namespace {
13 | public static var persistentTypeRepresentation: some IdentityRepresentation {
14 | CoreMI._ServiceVendorIdentifier._Anthropic
15 | }
16 |
17 | public let interface: API
18 | public let session: HTTPSession
19 |
20 | public init(
21 | interface: API,
22 | session: HTTPSession
23 | ) {
24 | self.interface = interface
25 | self.session = session
26 |
27 | session.disableTimeouts()
28 | }
29 |
30 | public convenience init(
31 | apiKey: String?
32 | ) {
33 | self.init(
34 | interface: API(configuration: Anthropic.API.Configuration(apiKey: apiKey)),
35 | session: .shared
36 | )
37 | }
38 | }
39 | }
40 |
41 | extension Anthropic.Client: CustomStringConvertible {
42 | public var description: String {
43 | let apiKey: String = self.interface.configuration.apiKey == nil ? "" : ""
44 |
45 | return "Anthropic.Client(apiKey: \(apiKey))"
46 | }
47 | }
48 |
49 | extension Anthropic.Client: _TaskDependenciesExporting {
50 | public var _exportedTaskDependencies: TaskDependencies {
51 | var result = TaskDependencies()
52 |
53 | result[\.llm] = self
54 |
55 | return result
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Sources/Anthropic/Intramodular/Anthropic.Model-Latest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | extension Anthropic.Model {
8 | public static var haiku: Self {
9 | .claude_3_haiku_20240307
10 | }
11 |
12 | public static var sonnet: Self {
13 | .claude_3_5_sonnet_20240620
14 | }
15 |
16 | public static var opus: Self {
17 | .claude_3_opus_20240229
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Sources/Anthropic/Intramodular/Anthropic.Tool.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swift
7 |
8 | extension Anthropic {
9 | public struct Tool: Codable, Hashable, Sendable {
10 | public let name: String
11 | public let description: String
12 | public let inputSchema: JSONSchema
13 | }
14 | }
15 |
16 | // MARK: - Auxiliary
17 |
18 | extension Anthropic.Tool {
19 | package init(_from function: AbstractLLM.ChatFunctionDefinition) throws {
20 | self.init(
21 | name: function.name.rawValue,
22 | description: function.context,
23 | inputSchema: function.parameters
24 | )
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/Anthropic/Intramodular/Anthropic.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Anthropic {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/Anthropic/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/Cohere/Cohere.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Cohere {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/Cohere/Intramodular/Cohere.Client+TextEmbeddingsRequestHandling.swift.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 | import LargeLanguageModels
8 |
9 | extension Cohere.Client: TextEmbeddingsRequestHandling {
10 |
11 | public var _availableModels: [ModelIdentifier]? {
12 | Cohere.Model.allCases.map({ $0.__conversion() })
13 | }
14 |
15 | public func fulfill(
16 | _ request: TextEmbeddingsRequest
17 | ) async throws -> TextEmbeddings {
18 | let model = request.model ?? Cohere.Model.embedEnglishV2.__conversion()
19 | let embeddingModel = Cohere.Model(rawValue: model.name)
20 |
21 | let embeddings: Cohere.Embeddings = try await createEmbeddings(
22 | for: embeddingModel,
23 | texts: request.input,
24 | inputType: .searchDocument,
25 | embeddingTypes: nil,
26 | truncate: nil
27 | )
28 |
29 | let textEmbeddingElements = zip(embeddings.texts, embeddings.embeddings).map { (text, embedding) in
30 | TextEmbeddings.Element(
31 | text: text,
32 | embedding: embedding.map { Double($0) },
33 | model: model)
34 | }
35 |
36 | return TextEmbeddings(model: model, data: textEmbeddingElements)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Sources/Cohere/Intramodular/Cohere.Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension Cohere {
8 | public struct Embeddings: Codable, Hashable, Sendable {
9 | public let responseType: String?
10 | public let id: String
11 | public let embeddings: [[Float]]
12 | public let texts: [String]
13 | public let meta: Meta?
14 | }
15 | }
16 |
17 | extension Cohere.Embeddings {
18 | public struct Meta: Codable, Hashable, Sendable {
19 | public let apiVersion: APIVersion
20 | public let billedUnits: BilledUnits?
21 | public let tokens: Tokens?
22 | public let warnings: [String]?
23 | }
24 |
25 | public struct APIVersion: Codable, Hashable, Sendable {
26 | public let version: String
27 | public let isDeprecated: Bool?
28 | public let isExperimental: Bool?
29 | }
30 |
31 | public struct BilledUnits: Codable, Hashable, Sendable {
32 | public let inputTokens: Int?
33 | public let outputTokens: Int?
34 | public let searchUnits: Int?
35 | public let classifications: Int?
36 | }
37 | }
38 |
39 | extension Cohere.Embeddings {
40 | public struct Tokens: Codable, Hashable, Sendable {
41 | public let inputTokens: Int?
42 | public let outputTokens: Int?
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/ASR/AutomaticSpeechRecognitionRequest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | public struct AutomaticSpeechRecognitionRequest {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Developer/_PreternaturalDotFile.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 |
7 | public struct _PreternaturalDotFile: Codable, Hashable, Sendable {
8 | @FileStorage(
9 | url: URL.homeDirectory.appending(path: ".preternatural.toml"),
10 | coder: TOMLCoder()
11 | )
12 | public static var dotfileForCurrentUser: Self? = nil
13 |
14 | public var TEST_ANTHROPIC_KEY: String?
15 | public var TEST_OPENAI_KEY: String?
16 |
17 | public func key(
18 | for provider: ModelIdentifier.Provider
19 | ) throws -> String? {
20 | switch provider {
21 | case .anthropic:
22 | return TEST_ANTHROPIC_KEY
23 | case .openAI:
24 | return TEST_OPENAI_KEY
25 | default:
26 | throw Never.Reason.unsupported
27 | }
28 | }
29 |
30 | public static func key(
31 | for provider: ModelIdentifier.Provider
32 | ) throws -> String? {
33 | try MainActor.unsafeAssumeIsolated {
34 | assert(ProcessInfo.processInfo._isRunningWithinXCTest)
35 |
36 | return try dotfileForCurrentUser?.key(for: provider)
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Foundation/CoreMI.Context.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Combine
6 | import Swallow
7 | import SwiftDI
8 |
9 | extension CoreMI {
10 | /// A context for machine intelligence.
11 | public final class _RequestHandlingContext: ObservableObject {
12 | @Published public var handlers: [any CoreMI.RequestHandling] = []
13 |
14 | public func add(_ x: T) {
15 | handlers.append(x)
16 | }
17 |
18 | public func _firstHandler(ofType type: T.Type) async throws -> T {
19 | try handlers.first(byUnwrapping: { try? cast($0, to: type) }).unwrap()
20 | }
21 | }
22 | }
23 |
24 | public enum CoreMI {
25 | public protocol Request {
26 |
27 | }
28 |
29 | public protocol RequestResult {
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Foundation/CoreMI.RequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension CoreMI {
8 | /// A type that handles generative machine learning requests.
9 | public protocol RequestHandling {
10 | /// The list of available models.
11 | ///
12 | /// `nil` if unknown.
13 | var _availableModels: [ModelIdentifier]? { get }
14 |
15 | func consider(_ request: R) async throws -> CoreMI.RequestConsideration
16 |
17 | func perform(
18 | _ request: Request,
19 | returning resultType: Result.Type
20 | ) async throws -> Result
21 | }
22 | }
23 |
24 | extension CoreMI.RequestHandling {
25 | public var _availableModels: [ModelIdentifier]? {
26 | nil
27 | }
28 |
29 | public func consider(
30 | _ request: R
31 | ) -> CoreMI.RequestConsideration {
32 | CoreMI.RequestConsideration()
33 | }
34 |
35 | public func perform(
36 | _ request: Request,
37 | returning resultType: Result.Type
38 | ) async throws -> Result {
39 | fatalError()
40 | }
41 | }
42 |
43 | extension CoreMI {
44 | public struct RequestConsideration {
45 |
46 | }
47 | }
48 |
49 | extension CoreMI {
50 | public protocol RequestHandlerAttributeKey {
51 |
52 | }
53 | }
54 |
55 | extension CoreMI {
56 | public enum ConceptualSchema {
57 | public protocol MultimodalModelCapability {
58 |
59 | }
60 | }
61 | }
62 |
63 | extension CoreMI.ConceptualSchema {
64 | public enum ModelCapabilities: _StaticSwift.Namespace {
65 |
66 | }
67 | }
68 |
69 | extension CoreMI.ConceptualSchema.ModelCapabilities {
70 | public struct FunctionCalling: CoreMI.ConceptualSchema.MultimodalModelCapability {
71 |
72 | }
73 |
74 | public struct Vision: CoreMI.ConceptualSchema.MultimodalModelCapability {
75 |
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Model Identifier/ModelIdentifierConvertible.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swallow
6 |
7 | public protocol ModelIdentifierConvertible {
8 | func __conversion() throws -> ModelIdentifier
9 | }
10 |
11 | public protocol ModelIdentifierRepresentable: ModelIdentifierConvertible {
12 | init(from _: ModelIdentifier) throws
13 | }
14 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Model Identifier/ModelIdentifierScope.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swallow
7 |
8 | @HadeanIdentifier("rajil-pagik-tibah-jibod")
9 | @RuntimeDiscoverable
10 | public enum ModelIdentifierScope: Codable, Hashable, Sendable {
11 | case one(ModelIdentifier)
12 | case choiceOf(Set)
13 |
14 | public var _oneValue: ModelIdentifier {
15 | get throws {
16 | guard case .one(let value) = self else {
17 | if case .choiceOf(let set) = self, let value = try set.toCollectionOfOne().first {
18 | return value
19 | }
20 |
21 | throw Never.Reason.illegal
22 | }
23 |
24 | return value
25 | }
26 | }
27 |
28 | public init(_ identifier: ModelIdentifier) {
29 | self = .one(identifier)
30 | }
31 |
32 | public func `as`(
33 | _ type: T.Type
34 | ) throws -> T {
35 | switch self {
36 | case .one(let identifier):
37 | return try T(from: identifier)
38 | case .choiceOf(let identifiers):
39 | return try identifiers.compactMap({ try? T(from: $0) }).toCollectionOfOne().first
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Service/CoreMI._ServiceAccountProtocol.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swallow
7 |
8 | extension CoreMI {
9 | /// An account used to authenticate access to a service.
10 | public protocol _ServiceAccountProtocol: Hashable {
11 | var serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier? { get throws }
12 | var credential: (any CoreMI._ServiceCredentialProtocol)? { get throws }
13 | }
14 |
15 | public struct _AnyServiceAccount: CoreMI._ServiceAccountProtocol {
16 | public let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier?
17 | @_HashableExistential
18 | public var credential: (any CoreMI._ServiceCredentialProtocol)?
19 |
20 | public init(
21 | serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier?,
22 | credential: (any CoreMI._ServiceCredentialProtocol)?
23 | ) {
24 | self.serviceVendorIdentifier = serviceVendorIdentifier
25 | self.credential = credential
26 | }
27 | }
28 | }
29 |
30 | // MARK: - Deprecated
31 |
32 | @available(*, deprecated)
33 | public typealias _MIServiceAccount = CoreMI._ServiceAccountProtocol
34 | @available(*, deprecated)
35 | public typealias _AnyMIServiceAccount = CoreMI._AnyServiceAccount
36 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Service/CoreMI._ServiceClientProtocol.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swallow
7 |
8 | extension CoreMI {
9 | /// A client for an AI/ML service.
10 | public protocol _ServiceClientProtocol: PersistentlyRepresentableType {
11 | /// A global filespace as provisioned by the service.
12 | ///
13 | /// For e.g. to represent all the files in an OpenAI/Gemini project.
14 | func _globalFileSpace() -> any CoreMI._ServiceProvisionedFileSpace
15 |
16 | init(account: (any CoreMI._ServiceAccountProtocol)?) async throws
17 | }
18 |
19 | public enum _ServiceClientError: Error {
20 | case incompatibleVendor(CoreMI._ServiceVendorIdentifier)
21 | case invalidCredential((any CoreMI._ServiceCredentialProtocol)?)
22 |
23 | public static var invalidCredential: Self {
24 | Self.invalidCredential(nil)
25 | }
26 | }
27 | }
28 |
29 | // MARK: - Deprecated
30 |
31 | @available(*, deprecated)
32 | public typealias _MIService = CoreMI._ServiceClientProtocol
33 | @available(*, deprecated)
34 | public typealias _MIServiceError = CoreMI._ServiceClientError
35 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Service/CoreMI._ServiceCredentialProtocol.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swift
7 |
8 | extension CoreMI {
9 | public protocol _ServiceCredentialProtocol: Codable, Hashable, Sendable {
10 | var credentialType: CoreMI._ServiceCredentialTypeIdentifier { get }
11 | }
12 | }
13 |
14 | // MARK: - Conformees
15 |
16 | extension CoreMI._ServiceCredentialTypes {
17 | public struct APIKeyCredential: CoreMI._ServiceCredentialProtocol {
18 | public var credentialType: CoreMI._ServiceCredentialTypeIdentifier {
19 | CoreMI._ServiceCredentialTypeIdentifier.apiKey
20 | }
21 |
22 | public let apiKey: String
23 |
24 | public init(apiKey: String) {
25 | self.apiKey = apiKey
26 | }
27 | }
28 | }
29 |
30 | extension CoreMI._ServiceCredentialTypes {
31 | @HadeanIdentifier("jikok-fafan-nadij-javub")
32 | public struct PlayHTCredential: CoreMI._ServiceCredentialProtocol {
33 | public var credentialType: CoreMI._ServiceCredentialTypeIdentifier {
34 | .custom(Self.self)
35 | }
36 |
37 | public let userID: String
38 | public let apiKey: String
39 |
40 | public init(
41 | userID: String,
42 | apiKey: String
43 | ) {
44 | self.userID = userID
45 | self.apiKey = apiKey
46 | }
47 | }
48 | }
49 |
50 | // MARK: - Deprecated
51 |
52 | @available(*, deprecated, renamed: "CoreMI._ServiceCredentialTypes.APIKeyCredential")
53 | public typealias _MIServiceAPIKeyCredential = CoreMI._ServiceCredentialTypes.APIKeyCredential
54 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/Service/CoreMI._ServiceCredentialTypes.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swift
7 |
8 | extension CoreMI {
9 | public enum _ServiceCredentialTypes {
10 |
11 | }
12 | }
13 |
14 | extension CoreMI {
15 | public enum _ServiceCredentialTypeIdentifier: Codable, Hashable, RawRepresentable, Sendable {
16 | case apiKey
17 | case custom(HadeanIdentifier)
18 |
19 | public var rawValue: String {
20 | switch self {
21 | case .apiKey:
22 | return "apiKey"
23 | case .custom(let id):
24 | return id.description
25 | }
26 | }
27 |
28 | public init?(rawValue: String) {
29 | switch rawValue {
30 | case CoreMI._ServiceCredentialTypeIdentifier.apiKey.rawValue:
31 | self = .apiKey
32 | default:
33 | if let identifier = HadeanIdentifier(rawValue) {
34 | self = .custom(identifier)
35 | } else {
36 | return nil
37 | }
38 | }
39 | }
40 |
41 | public static func custom(_ type: T.Type) -> Self {
42 | return .custom(type.hadeanIdentifier)
43 | }
44 |
45 | public func encode(to encoder: any Encoder) throws {
46 | try rawValue.encode(to: encoder)
47 | }
48 |
49 | public init(from decoder: any Decoder) throws {
50 | self = try Self(rawValue: String(from: decoder)).unwrap()
51 | }
52 | }
53 | }
54 |
55 | // MARK: - Deprecated
56 |
57 | @available(*, deprecated, renamed: "CoreMI._ServiceCredentialTypeIdentifier")
58 | public typealias _MIServiceCredentialType = CoreMI._ServiceCredentialTypeIdentifier
59 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/TTS/SpeechSynthesizers.VoiceName.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swift
7 |
8 | extension SpeechSynthesizers {
9 | public protocol VoiceName: Codable, Hashable, Identifiable {
10 |
11 | }
12 | }
13 |
14 | extension SpeechSynthesizers {
15 | public struct AnyVoiceName: SpeechSynthesizers.VoiceName {
16 | public var id: AnyPersistentIdentifier
17 | public var displayName: String
18 | public var userInfo: UserInfo
19 | }
20 |
21 | public protocol _AnyVoiceNameInitiable {
22 | init(voice: SpeechSynthesizers.AnyVoiceName) throws
23 | }
24 |
25 | public protocol _AnyVoiceNameConvertible {
26 | func __conversion() throws -> SpeechSynthesizers.AnyVoiceName
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/TTS/SpeechSynthesizers.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swift
7 |
8 | public enum SpeechSynthesizers {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/TTS/TTSRequest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Merge
7 | import Swift
8 |
9 | public protocol TTSRequest: CoreMI.Request {
10 |
11 | }
12 |
13 | public struct NaiveTTSRequest: Codable, Hashable, Sendable, TTSRequest {
14 | public let text: String
15 | }
16 |
17 | extension NaiveTTSRequest {
18 | public struct Result {
19 | public let data: Data
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Sources/CoreMI/Intramodular/TTS/TTSRequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Merge
7 | import Swift
8 |
9 | /// A unified interface for a text-to-speech (TTS) service.
10 | public protocol TTSRequestHandling: _MaybeAsyncProtocol {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/CoreMI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import Diagnostics
6 | @_exported import SwallowMacrosClient
7 |
8 | public enum _module {
9 |
10 | }
11 |
12 | // MARK: - Deprecated
13 |
14 | @available(*, deprecated, renamed: "CoreMI.Context")
15 | public typealias MIContext = CoreMI._RequestHandlingContext
16 | @available(*, deprecated, renamed: "ModelIdentifier")
17 | public typealias _MLModelIdentifier = ModelIdentifier
18 | @available(*, deprecated, renamed: "ModelIdentifierConvertible")
19 | public typealias _MLModelIdentifierConvertible = ModelIdentifierConvertible
20 | @available(*, deprecated, renamed: "ModelIdentifier.Provider")
21 | public typealias MLModelProvider = ModelIdentifier.Provider
22 | @available(*, deprecated, renamed: "CoreMI._ServiceCredentialProtocol")
23 | public typealias _MIServiceCredential = CoreMI._ServiceCredentialProtocol
24 |
--------------------------------------------------------------------------------
/Sources/ElevenLabs/Intramodular/API/ElevenLabs.APISpecification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ElevenLabs.APISpecification.ResponseBodies.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/18/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension ElevenLabs.APISpecification {
11 | public enum ResponseBodies {
12 | public struct Voices: Codable {
13 | public let voices: [ElevenLabs.Voice]
14 | }
15 |
16 | public struct VoiceID: Codable {
17 | public let voiceId: String
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Sources/ElevenLabs/Intramodular/ElevenLabs.Voice.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swift
7 |
8 | extension ElevenLabs {
9 | public struct Voice: Hashable, Identifiable, Sendable {
10 | public typealias ID = _TypeAssociatedID
11 |
12 | public let voiceID: String
13 | public let name: String
14 | public let description: String?
15 | public let isOwner: Bool?
16 |
17 | public var id: ID {
18 | ID(rawValue: voiceID)
19 | }
20 |
21 | public init(
22 | voiceID: String,
23 | name: String,
24 | description: String?,
25 | isOwner: Bool?
26 | ) {
27 | self.voiceID = voiceID
28 | self.name = name
29 | self.description = description
30 | self.isOwner = isOwner
31 | }
32 | }
33 | }
34 |
35 | // MARK: - Conformances
36 |
37 | extension ElevenLabs.Voice: Codable {
38 | enum CodingKeys: String, CodingKey {
39 | case voiceID = "voiceId"
40 | case name
41 | case description
42 | case isOwner
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/ElevenLabs/Intramodular/ElevenLabs.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum ElevenLabs {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/ElevenLabs/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import Swallow
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/Groq/Intramodular/Groq.Client.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import Merge
8 | import NetworkKit
9 | import Swallow
10 |
11 | extension Groq {
12 | @RuntimeDiscoverable
13 | public final class Client: HTTPClient, _StaticSwift.Namespace {
14 | public static var persistentTypeRepresentation: some IdentityRepresentation {
15 | CoreMI._ServiceVendorIdentifier._Groq
16 | }
17 |
18 | public let interface: APISpecification
19 | public let session: HTTPSession
20 |
21 | public init(interface: APISpecification, session: HTTPSession) {
22 | self.interface = interface
23 | self.session = session
24 | }
25 |
26 | public convenience init(apiKey: String?) {
27 | self.init(
28 | interface: .init(configuration: .init(apiKey: apiKey)),
29 | session: .shared
30 | )
31 | }
32 | }
33 | }
34 |
35 | extension Groq.Client: CoreMI._ServiceClientProtocol {
36 | public convenience init(
37 | account: (any CoreMI._ServiceAccountProtocol)?
38 | ) async throws {
39 | let account: any CoreMI._ServiceAccountProtocol = try account.unwrap()
40 | let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier = try account.serviceVendorIdentifier.unwrap()
41 |
42 | guard serviceVendorIdentifier == CoreMI._ServiceVendorIdentifier._Groq else {
43 | throw CoreMI._ServiceClientError.incompatibleVendor(serviceVendorIdentifier)
44 | }
45 |
46 | guard let credential = try account.credential as? CoreMI._ServiceCredentialTypes.APIKeyCredential else {
47 | throw CoreMI._ServiceClientError.invalidCredential(try account.credential)
48 | }
49 |
50 | self.init(apiKey: credential.apiKey)
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/Groq/Intramodular/Groq.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 | import LargeLanguageModels
8 | import Swallow
9 |
10 | extension Groq {
11 | public enum Model: String, CaseIterable, Codable, Hashable, Named, Sendable {
12 | case gemma_7b = "gemma-7b-it"
13 | case llama3_8b = "llama3-8b-8192"
14 | case llama3_70b = "llama3-70b-8192"
15 | case mixtral_8x7b = "mixtral-8x7b-32768"
16 |
17 | public var name: String {
18 | switch self {
19 | case .gemma_7b:
20 | return "Gemma 7b"
21 | case .llama3_8b:
22 | return "LLaMA3 8b"
23 | case .llama3_70b:
24 | return "LLaMA3 70b"
25 | case .mixtral_8x7b:
26 | return "Mixtral 8x7b"
27 | }
28 | }
29 | }
30 | }
31 |
32 | // MARK: - Conformances
33 |
34 | extension Groq.Model: CustomStringConvertible {
35 | public var description: String {
36 | rawValue
37 | }
38 | }
39 |
40 | extension Groq.Model: ModelIdentifierRepresentable {
41 | public init(from identifier: ModelIdentifier) throws {
42 | guard identifier.provider == ._Groq, identifier.revision == nil else {
43 | throw Never.Reason.illegal
44 | }
45 |
46 | guard let model = Self(rawValue: identifier.name) else {
47 | throw Never.Reason.unexpected
48 | }
49 |
50 | self = model
51 | }
52 |
53 | public func __conversion() -> ModelIdentifier {
54 | ModelIdentifier(
55 | provider: ._Groq,
56 | name: rawValue,
57 | revision: nil
58 | )
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Sources/Groq/Intramodular/Groq.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Groq {
8 |
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/Sources/Groq/module.swift:
--------------------------------------------------------------------------------
1 |
2 |
3 | @_exported import LargeLanguageModels
4 | @_exported import SwallowMacrosClient
5 |
--------------------------------------------------------------------------------
/Sources/HuggingFace/Intramodular/HuggingFace.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | @available(tvOS 16.0, *)
8 | public enum HuggingFace {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/HuggingFace/Resources/gpt2_tokenizer_config.json:
--------------------------------------------------------------------------------
1 | {
2 | "add_prefix_space": false,
3 | "bos_token": "<|endoftext|>",
4 | "clean_up_tokenization_spaces": true,
5 | "eos_token": "<|endoftext|>",
6 | "model_max_length": 1024,
7 | "tokenizer_class": "GPT2Tokenizer",
8 | "unk_token": "<|endoftext|>"
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Batch.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Jobs.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func startInferenceJob(
14 | urls: [URL],
15 | models: HumeAI.APIModel
16 | ) async throws -> HumeAI.JobID {
17 | let input = HumeAI.APISpecification.RequestBodies.BatchInferenceJobInput(
18 | urls: urls,
19 | models: models,
20 | callback: nil
21 | )
22 | return try await run(\.startInferenceJob, with: input)
23 | }
24 |
25 | public func getJobDetails(
26 | id: String
27 | ) async throws -> HumeAI.Job {
28 | let input = HumeAI.APISpecification.PathInput.ID(
29 | id: id
30 | )
31 | return try await run(\.getJobDetails, with: input)
32 | }
33 |
34 | public func getJobPredictions(
35 | id: String
36 | ) async throws -> [HumeAI.JobPrediction] {
37 | let input = HumeAI.APISpecification.PathInput.ID(
38 | id: id
39 | )
40 | return try await run(\.getJobPredictions, with: input)
41 | }
42 | public func listJobs() async throws -> [HumeAI.Job] {
43 | return try await run(\.listJobs, with: ())
44 | }
45 |
46 | public func getJobArtifacts(id: String) async throws -> [String: String] {
47 | let input = HumeAI.APISpecification.PathInput.ID(id: id)
48 | return try await run(\.getJobArtifacts, with: input)
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Chat.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Chat.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func chat(
14 | messages: [HumeAI.ChatMessage],
15 | model: String,
16 | temperature: Double? = nil
17 | ) async throws -> HumeAI.ChatResponse {
18 | let input = HumeAI.APISpecification.RequestBodies.ChatRequest(
19 | messages: messages.map { .init(role: $0.role, content: $0.content) },
20 | model: model,
21 | temperature: temperature,
22 | maxTokens: nil,
23 | stream: nil
24 | )
25 | return try await run(\.chat, with: input)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-ChatGroups.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client.ChatGroup.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listChatGroups() async throws -> [HumeAI.ChatGroup] {
14 | let response = try await run(\.listChatGroups)
15 | return response.chatGroups.map { chatGroup in
16 | HumeAI.ChatGroup(
17 | id: chatGroup.id,
18 | name: chatGroup.name,
19 | createdOn: chatGroup.createdOn,
20 | modifiedOn: chatGroup.modifiedOn,
21 | chats: chatGroup.chats?.compactMap { chat in
22 | HumeAI.Chat(
23 | id: chat.id,
24 | name: chat.name,
25 | createdOn: chat.createdOn,
26 | modifiedOn: chat.modifiedOn
27 | )
28 | }
29 | )
30 | }
31 | }
32 |
33 | public func getChatGroup(id: String) async throws -> HumeAI.ChatGroup {
34 | let input = HumeAI.APISpecification.PathInput.ID(
35 | id: id
36 | )
37 | return try await run(\.getChatGroup, with: input)
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Chats.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Chats.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listChats() async throws -> [HumeAI.Chat] {
14 | let response = try await run(\.listChats)
15 |
16 | return response.chats
17 | }
18 |
19 | public func listChatEvents(chatId: String) async throws -> [HumeAI.ChatEvent] {
20 | let input = HumeAI.APISpecification.PathInput.ID(
21 | id: chatId
22 | )
23 | let response = try await run(\.listChatEvents, with: input)
24 |
25 | return response.events
26 | }
27 |
28 | public func getChatAudio(chatId: String) async throws -> Data {
29 | let input = HumeAI.APISpecification.PathInput.ID(
30 | id: chatId
31 | )
32 |
33 | return try await run(\.getChatAudio, with: input)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Configs.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Configs.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listConfigs() async throws -> [HumeAI.Config] {
14 | let response = try await run(\.listConfigs)
15 |
16 | return response.configs
17 | }
18 |
19 | public func createConfig(
20 | name: String,
21 | description: String?,
22 | settings: [String: String]
23 | ) async throws -> HumeAI.Config {
24 | let input = HumeAI.APISpecification.RequestBodies.CreateConfigInput(
25 | name: name,
26 | description: description,
27 | settings: settings
28 | )
29 | return try await run(\.createConfig, with: input)
30 | }
31 |
32 | public func deleteConfig(id: String) async throws {
33 | let input = HumeAI.APISpecification.PathInput.ID(
34 | id: id
35 | )
36 |
37 | try await run(\.deleteConfig, with: input)
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Datasets.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Datasets.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listDatasets() async throws -> [HumeAI.Dataset] {
14 | let response = try await run(\.listDatasets)
15 | return response.datasets
16 | }
17 |
18 | public func createDataset(
19 | name: String,
20 | description: String?,
21 | fileIds: [String]
22 | ) async throws -> HumeAI.Dataset {
23 | let input = HumeAI.APISpecification.RequestBodies.CreateDatasetInput(
24 | name: name,
25 | description: description,
26 | fileIds: fileIds
27 | )
28 | return try await run(\.createDataset, with: input)
29 | }
30 |
31 | public func deleteDataset(id: String) async throws {
32 | let input = HumeAI.APISpecification.PathInput.ID(
33 | id: id
34 | )
35 | try await run(\.deleteDataset, with: input)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Files.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Files.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listFiles() async throws -> [HumeAI.File] {
14 | let response = try await run(\.listFiles)
15 | return response.files
16 | }
17 |
18 | public func uploadFile(
19 | data: Data,
20 | name: String,
21 | metadata: [String: String]? = nil
22 | ) async throws -> HumeAI.File {
23 | let input = HumeAI.APISpecification.RequestBodies.UploadFileInput(
24 | file: data,
25 | name: name,
26 | metadata: metadata
27 | )
28 | return try await run(\.uploadFile, with: input)
29 | }
30 |
31 | public func deleteFile(id: String) async throws {
32 | let input = HumeAI.APISpecification.PathInput.ID(
33 | id: id
34 | )
35 | try await run(\.deleteFile, with: input)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Jobs.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Jobs.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func startTrainingJob(
14 | datasetId: String,
15 | name: String,
16 | description: String? = nil,
17 | configuration: [String: String]
18 | ) async throws -> HumeAI.JobID {
19 | let input = HumeAI.APISpecification.RequestBodies.TrainingJobInput(
20 | datasetId: datasetId,
21 | name: name,
22 | description: description,
23 | configuration: configuration
24 | )
25 | return try await run(\.startTrainingJob, with: input)
26 | }
27 |
28 | public func startCustomInferenceJob(
29 | modelId: String,
30 | files: [HumeAI.FileInput],
31 | configuration: [String: String]
32 | ) async throws -> HumeAI.JobID {
33 | let input = HumeAI.APISpecification.RequestBodies.CustomInferenceJobInput(
34 | modelId: modelId,
35 | files: files,
36 | configuration: configuration
37 | )
38 | return try await run(\.startCustomInferenceJob, with: input)
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Models.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Models.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func listModels() async throws -> [HumeAI.Model] {
14 | let response = try await run(\.listModels)
15 | return response.models
16 | }
17 |
18 | public func getModel(
19 | id: String
20 | ) async throws -> HumeAI.Model {
21 | let input = HumeAI.APISpecification.PathInput.ID(id: id)
22 | return try await run(\.getModel, with: input)
23 | }
24 |
25 | public func updateModelName(
26 | id: String,
27 | name: String
28 | ) async throws {
29 | let input = HumeAI.APISpecification.RequestBodies.UpdateModelNameInput(
30 | id: id,
31 | name: name
32 | )
33 | try await run(\.updateModelName, with: input)
34 | }
35 |
36 | public func listModelVersions(
37 | id: String
38 | ) async throws -> [HumeAI.Model.ModelVersion] {
39 | let input = HumeAI.APISpecification.PathInput.ID(
40 | id: id
41 | )
42 | return try await run(\.listModelVersions, with: input)
43 | }
44 |
45 | public func getModelVersion(
46 | id: String,
47 | version: Int
48 | ) async throws -> HumeAI.Model.ModelVersion {
49 | let input = HumeAI.APISpecification.PathInput.IDWithVersion(
50 | id: id,
51 | version: version
52 | )
53 | return try await run(\.getModelVersion, with: input)
54 | }
55 |
56 | public func updateModelDescription(
57 | id: String,
58 | versionId: String,
59 | description: String
60 | ) async throws {
61 | let input = HumeAI.APISpecification.RequestBodies.UpdateModelDescriptionInput(
62 | id: id,
63 | versionId: versionId,
64 | description: description
65 | )
66 | try await run(\.updateModelDescription, with: input)
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.Client-Stream.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Client-Stream.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension HumeAI.Client {
13 | public func streamInference(
14 | id: String,
15 | file: Data,
16 | models: [HumeAI.APIModel],
17 | metadata: [String: String]? = nil
18 | ) async throws -> HumeAI.Job {
19 | let input = HumeAI.APISpecification.RequestBodies.StreamInput(
20 | id: id,
21 | file: file,
22 | models: models,
23 | metadata: metadata
24 | )
25 | return try await run(\.streamInference, with: input)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/HumeAI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Swift
9 |
10 | public enum HumeAI {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Chat.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Chat.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct Chat: Codable {
10 | public let id: String
11 | public let name: String
12 | public let createdOn: Int64
13 | public let modifiedOn: Int64
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.ChatEvent.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.ChatEvent.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct ChatEvent: Codable {
10 | public let id: String
11 | public let chatId: String
12 | public let type: String
13 | public let content: String
14 | public let createdOn: Int64
15 | public let audioUrl: String?
16 | public let metadata: [String: String]?
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.ChatGroup.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.ChatGroup.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct ChatGroup {
10 | public let id: String
11 | public let name: String
12 | public let createdOn: Int64
13 | public let modifiedOn: Int64
14 | public let chats: [Chat]?
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.ChatMessage.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.ChatMessage.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct ChatMessage {
10 | public let role: String
11 | public let content: String
12 |
13 | public init(role: String, content: String) {
14 | self.role = role
15 | self.content = content
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.ChatResponse.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.ChatResponse.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct ChatResponse {
10 | public let id: String
11 | public let created: Int64
12 | public let choices: [Choice]
13 | public let usage: Usage
14 |
15 | public struct Choice {
16 | public let index: Int
17 | public let message: Message
18 | public let finishReason: String?
19 |
20 | public struct Message {
21 | public let role: String
22 | public let content: String
23 | }
24 | }
25 |
26 | public struct Usage {
27 | public let promptTokens: Int
28 | public let completionTokens: Int
29 | public let totalTokens: Int
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Config.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Config.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct Config: Codable {
10 | public let id: String
11 | public let name: String
12 | public let description: String?
13 | public let createdOn: Int64
14 | public let modifiedOn: Int64
15 | public let versions: [ConfigVersion]?
16 |
17 | public struct ConfigVersion: Codable {
18 | public let id: String
19 | public let configId: String
20 | public let description: String?
21 | public let createdOn: Int64
22 | public let modifiedOn: Int64
23 | public let settings: [String: String]
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Dataset.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Dataset.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct Dataset: Codable {
10 | public let id: String
11 | public let name: String
12 | public let description: String?
13 | public let createdOn: Int64
14 | public let modifiedOn: Int64
15 | public let versions: [DatasetVersion]?
16 |
17 | public struct DatasetVersion: Codable {
18 | public let id: String
19 | public let datasetId: String
20 | public let description: String?
21 | public let createdOn: Int64
22 | public let modifiedOn: Int64
23 | public let files: [HumeAI.File]?
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.File.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.File.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct File: Codable {
10 | public let id: String
11 | public let name: String
12 | public let size: Int
13 | public let mimeType: String
14 | public let createdOn: Int64
15 | public let modifiedOn: Int64
16 | public let metadata: [String: String]?
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.FileInput.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.FileInput.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct FileInput: Codable {
10 | public let url: String
11 | public let mimeType: String
12 | public let metadata: [String: String]?
13 |
14 | public init(url: String, mimeType: String, metadata: [String: String]? = nil) {
15 | self.url = url
16 | self.mimeType = mimeType
17 | self.metadata = metadata
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.JobPrediction.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.JobPrediction.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension HumeAI {
11 | public struct JobPrediction: Codable {
12 | public let source: Source
13 | public let results: Results
14 |
15 | public struct Source: Codable {
16 | public let type: String
17 | public let url: String
18 | }
19 |
20 | public struct Results: Codable {
21 | public let predictions: [Prediction]
22 | public let errors: [String]
23 | }
24 |
25 | public struct Prediction: Codable {
26 | public let file: String
27 | public let models: Models
28 | }
29 |
30 | public struct Models: Codable {
31 | public let face: FaceModel?
32 |
33 | public struct FaceModel: Codable {
34 | public let groupedPredictions: [GroupedPrediction]
35 |
36 | enum CodingKeys: String, CodingKey {
37 | case groupedPredictions = "grouped_predictions"
38 | }
39 | }
40 | }
41 |
42 | public struct GroupedPrediction: Codable {
43 | public let id: String
44 | public let predictions: [FacePrediction]
45 | }
46 |
47 | public struct FacePrediction: Codable {
48 | public let frame: Int
49 | public let time: Int
50 | public let prob: Double
51 | public let box: BoundingBox
52 | public let emotions: [Emotion]
53 | }
54 |
55 | public struct BoundingBox: Codable {
56 | public let x: Double
57 | public let y: Double
58 | public let w: Double
59 | public let h: Double
60 | }
61 |
62 | public struct Emotion: Codable {
63 | public let name: String
64 | public let score: Double
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Prompt.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Prompt.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct Prompt: Codable {
10 | public let id: String
11 | public let version: Int
12 | public let versionType: String
13 | public let name: String
14 | public let createdOn: Int64
15 | public let modifiedOn: Int64
16 | public let text: String
17 | public let versionDescription: String?
18 |
19 | public struct PromptVersion: Codable {
20 | public let id: String
21 | public let version: Int
22 | public let versionType: String
23 | public let name: String
24 | public let createdOn: Int64
25 | public let modifiedOn: Int64
26 | public let text: String
27 | public let versionDescription: String?
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Tool.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Tool.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | extension HumeAI {
9 | public struct Tool: Codable {
10 | public let id: String
11 | public let name: String
12 | public let description: String?
13 | public let createdOn: Int64
14 | public let modifiedOn: Int64
15 | public let versions: [ToolVersion]?
16 |
17 | public struct ToolVersion: Codable {
18 | let id: String
19 | let version: Int
20 | let toolId: String?
21 | let description: String?
22 | let createdOn: Int64
23 | let modifiedOn: Int64
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/HumeAI/Intramodular/Models/HumeAI.Voice.swift:
--------------------------------------------------------------------------------
1 | //
2 | // HumeAI.Voice.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension HumeAI {
11 | public struct Voice: Hashable, Codable {
12 | public var id: String
13 | public var name: String
14 | public var baseVoice: String
15 | public var parameterModel: String
16 | public var parameters: Parameters?
17 | public var createdOn: Int64
18 | public var modifiedOn: Int64
19 |
20 | public struct Parameters: Codable, Hashable {
21 | public var gender: Double?
22 | public var articulation: Double?
23 | public var assertiveness: Double?
24 | public var buoyancy: Double?
25 | public var confidence: Double?
26 | public var enthusiasm: Double?
27 | public var nasality: Double?
28 | public var relaxedness: Double?
29 | public var smoothness: Double?
30 | public var tepidity: Double?
31 | public var tightness: Double?
32 | }
33 |
34 | public init(
35 | id: String,
36 | name: String,
37 | baseVoice: String,
38 | parameterModel: String,
39 | parameters: Parameters?,
40 | createdOn: Int64,
41 | modifiedOn: Int64
42 | ) {
43 | self.id = id
44 | self.name = name
45 | self.baseVoice = baseVoice
46 | self.parameterModel = parameterModel
47 | self.parameters = parameters
48 | self.createdOn = createdOn
49 | self.modifiedOn = modifiedOn
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/HumeAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 |
--------------------------------------------------------------------------------
/Sources/Jina/Intramodular/Jina.Client+TextEmbeddingsRequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 |
8 | extension Jina.Client: TextEmbeddingsRequestHandling {
9 |
10 | public var _availableModels: [ModelIdentifier]? {
11 | Jina.Model.allCases.map({ $0.__conversion() })
12 | }
13 |
14 | public func fulfill(
15 | _ request: TextEmbeddingsRequest
16 | ) async throws -> TextEmbeddings {
17 | let model = request.model ?? Jina.Model.embeddingsV2BaseEn.__conversion()
18 | let embeddingModel = try Jina.Model(rawValue: model.name).unwrap()
19 |
20 | let embeddings: Jina.Embeddings = try await createEmbeddings(
21 | for: embeddingModel,
22 | input: request.input,
23 | encodingFormat: nil
24 | )
25 |
26 | let textEmbeddings = embeddings.data.map {
27 | TextEmbeddings.Element(
28 | text: $0.object,
29 | embedding: $0.embedding.float.map { Double($0) },
30 | model: model)
31 | }
32 |
33 | return TextEmbeddings(
34 | model: model,
35 | data: textEmbeddings
36 | )
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Sources/Jina/Intramodular/Jina.Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension Jina {
8 | public struct Embeddings: Codable, Hashable, Sendable {
9 | public let model: String
10 | public let object: String
11 | public let data: [EmbeddingData]
12 | public let usage: Usage
13 | }
14 | }
15 |
16 | extension Jina.Embeddings {
17 | public struct EmbeddingData: Codable, Hashable, Sendable {
18 | public let object: String
19 | public let embedding: Embedding
20 | public let index: Int
21 | }
22 |
23 | public struct Embedding: Codable, Hashable, Sendable {
24 | public let float: [Float]
25 | }
26 | }
27 |
28 | extension Jina.Embeddings {
29 | public struct Usage: Codable, Hashable, Sendable {
30 | public let promptTokens: Int
31 | public let totalTokens: Int
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Sources/Jina/Intramodular/Jina.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Jina {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/Jina/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/AbstractLLM.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | public enum AbstractLLM {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Chat/AbstractLLM.ChatCompletion.StopReason.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | extension AbstractLLM.ChatCompletion {
8 | @frozen
9 | public struct StopReason: Codable, Hashable, Sendable {
10 | public enum StopReasonType: Codable, CaseIterable, Hashable, Sendable {
11 | case endTurn
12 | case maxTokens
13 | case stopSequence
14 | }
15 |
16 | public let type: StopReasonType?
17 |
18 | public init(type: StopReasonType? = nil) {
19 | self.type = type
20 | }
21 | }
22 | }
23 |
24 | extension AbstractLLM.ChatCompletion.StopReason {
25 | public static var endTurn: Self {
26 | Self(type: .endTurn)
27 | }
28 |
29 | public static var maxTokens: Self {
30 | Self(type: .maxTokens)
31 | }
32 |
33 | public static var stopSequence: Self {
34 | Self(type: .stopSequence)
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Function Calling/AbstractLLM.ChatFunctionDefinition.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swallow
7 |
8 | extension AbstractLLM {
9 | public struct ChatFunctionDefinition: Codable, Hashable, Identifiable, Sendable {
10 | public typealias ID = _TypeAssociatedID
11 |
12 | public let id: ID
13 | public var name: AbstractLLM.ChatFunction.Name
14 | public var context: String
15 | public var parameters: JSONSchema
16 |
17 | public init(
18 | id: AnyPersistentIdentifier? = nil,
19 | name: AbstractLLM.ChatFunction.Name,
20 | context: String,
21 | parameters: JSONSchema
22 | ) {
23 | self.id = id.map({ ID(rawValue: $0) }) ?? ID(rawValue: AnyPersistentIdentifier(rawValue: UUID()))
24 | self.name = name
25 | self.context = context
26 | self.parameters = parameters
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Function Calling/AbstractLLM.ChatFunctionExecuting.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Compute
6 | import Foundation
7 | import Swallow
8 |
9 | /// A type that asynchronously handles function calls.
10 | ///
11 | /// This type is **WIP**.
12 | public protocol __AbstractLLM_ChatFunctionExecuting {
13 | func execute(
14 | _ call: AbstractLLM.ChatFunctionCall
15 | ) async throws -> AbstractLLM.ResultOfFunctionCall
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Function Calling/AbstractLLM.ResultOfFunctionCall.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import CoreMI
7 | import Swallow
8 |
9 | extension AbstractLLM {
10 | /// The developer-supplied result of a function that you passed to an LLM.
11 | ///
12 | /// This is distinct from a _function call_.
13 | public struct ResultOfFunctionCall: Codable, Hashable, Sendable {
14 | public let functionID: AnyPersistentIdentifier?
15 | public let name: AbstractLLM.ChatFunction.Name
16 | public let result: FunctionResult
17 |
18 | public var debugDescription: String {
19 | ""
20 | }
21 |
22 | public init(
23 | functionID: AnyPersistentIdentifier?,
24 | name: AbstractLLM.ChatFunction.Name,
25 | result: FunctionResult
26 | ) {
27 | self.functionID = functionID
28 | self.name = name
29 | self.result = result
30 | }
31 | }
32 | }
33 |
34 | // MARK: - Auxiliary
35 |
36 | extension AbstractLLM.ResultOfFunctionCall {
37 | public struct FunctionResult: Codable, CustomStringConvertible, Hashable, Sendable {
38 | public let rawValue: String
39 |
40 | public var description: String {
41 | rawValue
42 | }
43 |
44 | public init(rawValue: String) {
45 | self.rawValue = rawValue
46 | }
47 |
48 | public func __conversion() throws -> T {
49 | let result: Any
50 |
51 | switch T.self {
52 | case String.self:
53 | result = rawValue
54 | default:
55 | TODO.unimplemented
56 | }
57 |
58 | return try cast(result)
59 | }
60 | }
61 | }
62 |
63 | // MARK: - Deprecated
64 |
65 | extension AbstractLLM {
66 | @available(*, deprecated, renamed: "AbstractLLM.ResultOfFunctionCall")
67 | public typealias ChatFunctionInvocation = ResultOfFunctionCall
68 | }
69 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Text/AbstractLLM.TextCompletion.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Compute
6 | import Foundation
7 | import Swallow
8 |
9 | extension AbstractLLM {
10 | public struct TextCompletion: Completion {
11 | public static var knownCompletionType: AbstractLLM.CompletionType? {
12 | .text
13 | }
14 |
15 | public let prefix: PromptLiteral
16 | public let text: String
17 |
18 | public init(
19 | prefix: PromptLiteral,
20 | text: String
21 | ) {
22 | self.prefix = prefix
23 | self.text = text
24 | }
25 |
26 | public var description: String {
27 | text.description
28 | }
29 | }
30 | }
31 |
32 | // MARK: - Conformances
33 |
34 | extension AbstractLLM.TextCompletion: Partializable {
35 | public typealias Partial = Self
36 |
37 | public mutating func coalesceInPlace(
38 | with partial: Partial
39 | ) throws {
40 | fatalError(.unexpected)
41 | }
42 |
43 | public static func coalesce(
44 | _ partials: some Sequence
45 | ) throws -> Self {
46 | fatalError(.unexpected)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Text/AbstractLLM.TextCompletionParameters.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | extension AbstractLLM {
9 | public struct TextCompletionParameters: CompletionParameters {
10 | public var tokenLimit: TokenLimit
11 | public var temperatureOrTopP: TemperatureOrTopP? = .temperature(1)
12 | public var stops: [String]?
13 |
14 | public init(
15 | tokenLimit: AbstractLLM.TokenLimit,
16 | temperatureOrTopP: AbstractLLM.TemperatureOrTopP? = nil,
17 | stops: [String]? = nil
18 | ) {
19 | self.tokenLimit = tokenLimit
20 | self.temperatureOrTopP = temperatureOrTopP
21 | self.stops = stops
22 | }
23 |
24 | public init(
25 | tokenLimit: AbstractLLM.TokenLimit,
26 | temperature: Double?,
27 | stops: [String]?
28 | ) {
29 | self.tokenLimit = tokenLimit
30 | self.temperatureOrTopP = temperature.map({ .temperature($0) })
31 | self.stops = stops
32 | }
33 | }
34 | }
35 |
36 | // MARK: - Conformances
37 |
38 | extension AbstractLLM.TextCompletionParameters: ExpressibleByNilLiteral {
39 | public init(nilLiteral: ()) {
40 | self.init(
41 | tokenLimit: .max,
42 | temperatureOrTopP: nil,
43 | stops: nil
44 | )
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/LLMs/Text/AbstractLLM.TextPrompt.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Foundation
7 | import Swallow
8 |
9 | extension AbstractLLM {
10 | public struct TextPrompt: AbstractLLM.Prompt, Codable, Hashable, Sendable {
11 | public typealias CompletionParameters = AbstractLLM.TextCompletionParameters
12 | public typealias Completion = AbstractLLM.TextCompletion
13 |
14 | public static var knownCompletionType: AbstractLLM.CompletionType? {
15 | .text
16 | }
17 |
18 | @_UnsafelySerialized
19 | public var prefix: any PromptLiteralConvertible
20 | public var context: PromptContextValues
21 |
22 | public init(
23 | prefix: PromptLiteral,
24 | context: PromptContextValues = .init()
25 | ) {
26 | self.prefix = prefix
27 | self.context = context
28 | }
29 |
30 | @_disfavoredOverload
31 | public init(
32 | prefix: any PromptLiteralConvertible,
33 | context: PromptContextValues = .init()
34 | ) {
35 | self.prefix = PromptLiteral(_lazy: prefix)
36 | self.context = context
37 | }
38 | }
39 | }
40 |
41 | // MARK: - Conformances
42 |
43 | extension AbstractLLM.TextPrompt: CustomDebugStringConvertible {
44 | public var debugDescription: String {
45 | PromptLiteral(_lazy: prefix).debugDescription
46 | }
47 | }
48 |
49 | extension AbstractLLM.TextPrompt: ExpressibleByStringLiteral {
50 | public init(stringLiteral value: String) {
51 | self.init(prefix: PromptLiteral(stringLiteral: value))
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/AbstractLLM._AnyPromptCompletionConfigurationType.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swallow
6 |
7 | extension AbstractLLM {
8 | @_spi(Internal)
9 | public protocol _AnyPromptCompletionConfigurationType: Sendable {
10 | var temperatureOrTopP: AbstractLLM.TemperatureOrTopP? { get }
11 | var stops: [String] { get }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/PromptLiteral-Initializers.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import FoundationX
6 | import Swallow
7 | @_spi(Internal) import SwiftUIX
8 |
9 | #if os(iOS) || os(macOS) || os(tvOS) || os(visionOS) || os(watchOS)
10 | extension PromptLiteral {
11 | init(
12 | _imageOrImageURL image: Either
13 | ) throws {
14 | let payload: PromptLiteral.StringInterpolation.Component.Payload
15 |
16 | switch image {
17 | case .left(let image):
18 | payload = .image(.image(image))
19 | case .right(let imageURL):
20 | payload = .image(.url(imageURL as URL))
21 | }
22 |
23 | self.init(stringInterpolation: .init(payload: payload))
24 |
25 | if _isDebugAssertConfiguration {
26 | let isEmpty = try self.isEmpty
27 |
28 | assert(!isEmpty)
29 | }
30 | }
31 |
32 | public init(
33 | imageURL url: URL
34 | ) throws {
35 | try self.init(_imageOrImageURL: .right(url))
36 | }
37 |
38 | public init(
39 | imageURL url: String
40 | ) throws {
41 | try self.init(imageURL: URL(string: url).unwrap())
42 | }
43 |
44 | public init(
45 | image: SwiftUIX._AnyImage
46 | ) throws {
47 | try self.init(_imageOrImageURL: .left(image))
48 | }
49 |
50 | public init(image: SwiftUIX.AppKitOrUIKitImage) throws {
51 | try self.init(image: SwiftUIX._AnyImage(image))
52 | }
53 |
54 | public init(
55 | image: SwiftUIX._AnyImage.Name
56 | ) throws {
57 | try self.init(image: _AnyImage(named: image))
58 | }
59 |
60 | public init(
61 | image: String,
62 | in bundle: Bundle?
63 | ) throws {
64 | try self.init(
65 | image: try AppKitOrUIKitImage(named: .bundleResource(image, in: bundle)).unwrap()
66 | )
67 | }
68 | }
69 | #endif
70 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/PromptLiteralError.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Diagnostics
6 | import Swallow
7 |
8 | public enum PromptLiteralError: Error {
9 | case failedToReduceToPrompt(for: AbstractLLM.CompletionType?)
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/PromptLiteralTokenizer.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swallow
6 |
7 | /// A tokenizer for prompt matter.
8 | ///
9 | /// The reason this exists along with `TextTokenizer` from `Cataphyl` is because `PromptLiteral` is future-proofed for multimodal prompt matter.
10 | public protocol PromptLiteralTokenizer {
11 | associatedtype Token: Hashable
12 | associatedtype Output: Collection where Output.Element == Token
13 |
14 | func encode(_ input: PromptLiteral) throws -> Output
15 | func decode(_ tokens: Output) throws -> PromptLiteral
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/_PromptLiteralEncodingContainer.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | /// A type capable of encoding a `PromptLiteral` into itself.
9 | ///
10 | /// This is a useful interface for 3rd party models to adopt to support conversion _from_ `PromptLiteral`.
11 | ///
12 | /// This is a key protocol for performing a `PromptLiteral` -> `SomeModelProvider.ChatMessageType` conversion.
13 | public protocol _PromptLiteralEncodingContainer {
14 | mutating func encode(
15 | _ degenerate: PromptLiteral._Degenerate.Component
16 | ) async throws
17 | }
18 |
19 | // MARK: - Supplementary
20 |
21 | extension PromptLiteral {
22 | /// Encode this literal into an encoding container.
23 | public func _encode(
24 | to container: inout Container
25 | ) async throws {
26 | let degenerate = try _degenerate()
27 |
28 | for component in degenerate.components {
29 | try await container.encode(component)
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Prompt Literal/_opaque_DynamicPromptVariable.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swallow
6 |
7 | public protocol _opaque_DynamicPromptVariable: PromptLiteralConvertible {
8 | associatedtype ResolvedValue
9 |
10 | var _runtimeResolvedValue: ResolvedValue? { get }
11 | var _isEmpty: Bool { get throws }
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Text Embeddings/LLMRequestHandlingError.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Diagnostics
6 | import Swallow
7 |
8 | public enum LLMRequestHandlingError: _ErrorX {
9 | case unsupportedPromptType(Metatype)
10 | case _catchAll(AnyError)
11 |
12 | public static func unsupportedPromptType(_ type: any AbstractLLM.Prompt.Type) -> Self {
13 | .unsupportedPromptType(Metatype(type))
14 | }
15 |
16 | public init?(_catchAll error: AnyError) throws {
17 | self = ._catchAll(error)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Text Embeddings/SingleTextEmbedding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 | import Swallow
8 |
9 | @HadeanIdentifier("dapup-numuz-koluh-goduv")
10 | public struct SingleTextEmbedding: Hashable, Sendable {
11 | public let text: String
12 | public let embedding: _RawTextEmbedding
13 | public let model: ModelIdentifier
14 |
15 | public init(
16 | text: String,
17 | embedding: _RawTextEmbedding,
18 | model: ModelIdentifier
19 | ) {
20 | self.text = text
21 | self.embedding = embedding
22 | self.model = model
23 | }
24 |
25 | public init(
26 | text: String,
27 | embedding: _RawTextEmbedding.RawValue,
28 | model: ModelIdentifier
29 | ) {
30 | self.init(
31 | text: text,
32 | embedding: .init(rawValue: embedding),
33 | model: model
34 | )
35 | }
36 | }
37 |
38 | // MARK: - Conformances
39 |
40 | extension SingleTextEmbedding: Codable {
41 | public enum CodingKeys: CodingKey {
42 | case text
43 | case embedding
44 | case model
45 | }
46 |
47 | public init(from decoder: Decoder) throws {
48 | let container = try decoder.container(keyedBy: CodingKeys.self)
49 |
50 | self.text = try container.decode(forKey: .text)
51 | self.embedding = try container.decode(forKey: .embedding)
52 | self.model = try container.decode(forKey: .model)
53 | }
54 |
55 | public func encode(to encoder: Encoder) throws {
56 | var container = encoder.container(keyedBy: CodingKeys.self)
57 |
58 | try container.encode(text, forKey: .text)
59 | try container.encode(embedding, forKey: .embedding)
60 | try container.encode(model, forKey: .model)
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Text Embeddings/TextEmbeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 | import Swallow
8 |
9 | /// A type that represents an array of text+embedding pairs.
10 | ///
11 | /// Text embeddings are vector representations of text.
12 | ///
13 | /// You can produce text embeddings by using a text embedding model (for e.g. OpenAI's `text-embedding-ada-002`).
14 | public struct TextEmbeddings: Codable, HadeanIdentifiable, Hashable, Sendable {
15 | public typealias Element = SingleTextEmbedding
16 |
17 | public static var hadeanIdentifier: HadeanIdentifier {
18 | "junur-tutuz-zarik-ninab"
19 | }
20 |
21 | public let data: [SingleTextEmbedding]
22 | public let model: ModelIdentifier
23 |
24 | public init(
25 | model: ModelIdentifier,
26 | data: [SingleTextEmbedding]
27 | ) {
28 | self.model = model
29 | self.data = data
30 | }
31 | }
32 |
33 | extension TextEmbeddings {
34 | public func appending(
35 | contentsOf other: TextEmbeddings
36 | ) -> Self {
37 | assert(model == other.model)
38 |
39 | return .init(
40 | model: model,
41 | data: data.appending(contentsOf: other.data)
42 | )
43 | }
44 | }
45 |
46 | // MARK: - Conformances
47 |
48 | extension TextEmbeddings: RandomAccessCollection {
49 | public var startIndex: Int {
50 | data.startIndex
51 | }
52 |
53 | public var endIndex: Int {
54 | data.endIndex
55 | }
56 |
57 | public subscript(_ index: Int) -> Element {
58 | data[index]
59 | }
60 |
61 | public func makeIterator() -> AnyIterator {
62 | data.makeIterator().eraseToAnyIterator()
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Text Embeddings/_RawTextEmbedding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Accelerate
6 | import CorePersistence
7 | import CoreTransferable
8 | import Swallow
9 |
10 | /// A type that represents the embedding of a single text.
11 | ///
12 | /// It is essentially just a wrapper around `Array` for now, but will expand to support various different forms of storage (including quantized representations).
13 | @frozen
14 | public struct _RawTextEmbedding: Hashable, Sendable {
15 | public typealias RawValue = [Double]
16 |
17 | public let rawValue: RawValue
18 |
19 | public init(rawValue: RawValue) {
20 | self.rawValue = rawValue
21 | }
22 | }
23 |
24 | // MARK: - Conformees
25 |
26 | extension _RawTextEmbedding: Codable {
27 | @inlinable
28 | public init(from decoder: Decoder) throws {
29 | let container = try decoder.singleValueContainer()
30 |
31 | self.rawValue = try vDSP.floatToDouble(container.decode([Float].self))
32 | }
33 |
34 | @inlinable
35 | public func encode(to encoder: Encoder) throws {
36 | var container = encoder.singleValueContainer()
37 |
38 | try container.encode(vDSP.doubleToFloat(rawValue))
39 | }
40 | }
41 |
42 | extension _RawTextEmbedding: CustomStringConvertible {
43 | public var description: String {
44 | var result = rawValue
45 | .map({ $0.formatted(toDecimalPlaces: 3) })
46 | .joined(separator: ", ")
47 |
48 | result = "[" + result + "]"
49 |
50 | return result
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/Intramodular/Text Embeddings/_StopwordsMap.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | public struct _StopwordsMap {
9 | private let rawValue: [ISO639LanguageCode: Set]
10 |
11 | private init(rawValue: [ISO639LanguageCode: Set]) {
12 | self.rawValue = rawValue
13 | }
14 |
15 | public subscript(_ language: ISO639LanguageCode) -> Set {
16 | get throws {
17 | try rawValue[language].unwrap()
18 | }
19 | }
20 | }
21 |
22 | extension _StopwordsMap {
23 | public static let shared: Self = {
24 | do {
25 | return try Self.load()
26 | } catch {
27 | assertionFailure()
28 |
29 | return .init(rawValue: [:])
30 | }
31 | }()
32 |
33 | private static func load() throws -> Self {
34 | let filename = "stopwords-iso"
35 |
36 | let url = try Bundle.module.url(forResource: filename, withExtension: "json").unwrap()
37 | let data = try Data(contentsOf: url)
38 | let stopwords = try JSONDecoder().decode([String: [String]].self, from: data)
39 |
40 | return .init(
41 | rawValue: try stopwords
42 | .mapKeys {
43 | try ISO639LanguageCode(rawValue: $0.uppercased()).unwrap()
44 | }
45 | .mapValues {
46 | Set($0)
47 | }
48 | )
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Sources/LargeLanguageModels/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import CoreMI
6 | @_exported import Diagnostics
7 | @_exported import Merge
8 | @_exported import Swallow
9 | @_exported import SwiftDI
10 |
11 | import CorePersistence
12 |
13 | public enum _module {
14 | public static func initialize() {
15 | _HadeanSwiftTypeRegistry.register(TextEmbeddings.self)
16 | _HadeanSwiftTypeRegistry.register(TextEmbeddings.Element.self)
17 | }
18 | }
19 |
20 | extension TaskDependencyValues {
21 | public var llm: (any LLMRequestHandling)? {
22 | get {
23 | self[_OptionalTaskDependencyKey.self]
24 | } set {
25 | self[_OptionalTaskDependencyKey.self] = newValue
26 | }
27 | }
28 |
29 | public var embedding: (any TextEmbeddingsRequestHandling)? {
30 | get {
31 | self[_OptionalTaskDependencyKey.self]
32 | } set {
33 | self[_OptionalTaskDependencyKey.self] = newValue
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/API/Mistral.APISpecification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import FoundationX
7 | import Swallow
8 |
9 | extension Mistral.APISpecification.ResponseBodies {
10 | public struct ChatCompletion: Codable, Hashable, Sendable {
11 | public struct Choice: Codable, Hashable, Sendable {
12 | public enum FinishReason: String, Codable, Hashable, Sendable {
13 | case stop = "stop"
14 | case length = "length"
15 | case modelLength = "model_length"
16 | }
17 |
18 | public let index: Int
19 | public let message: Mistral.ChatMessage
20 | public let finishReason: FinishReason
21 | }
22 |
23 | public struct Usage: Codable, Hashable, Sendable {
24 | public let promptTokens: Int
25 | public let completionTokens: Int
26 | public let totalTokens: Int
27 | }
28 |
29 | public var id: String
30 | public var object: String
31 | public var created: Date
32 | public var model: String
33 | public var choices: [Choice]
34 | public let usage: Usage
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Mistral.Client+TextEmbeddingsRequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 |
8 | extension Mistral.Client: TextEmbeddingsRequestHandling {
9 |
10 | public func fulfill(
11 | _ request: TextEmbeddingsRequest
12 | ) async throws -> TextEmbeddings {
13 | let model = Mistral.Model.mistral_embed.__conversion()
14 |
15 | let embeddings: Mistral.Embeddings = try await createEmbeddings(for: request.input)
16 | let textEmbeddings = embeddings.data.map {
17 | TextEmbeddings.Element(
18 | text: $0.object,
19 | embedding: $0.embedding,
20 | model: model)
21 | }
22 |
23 | return TextEmbeddings(
24 | model: model,
25 | data: textEmbeddings
26 | )
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Mistral.Client.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import Merge
8 | import NetworkKit
9 | import Swallow
10 |
11 | extension Mistral {
12 | @RuntimeDiscoverable
13 | public final class Client: HTTPClient, _StaticSwift.Namespace {
14 | public static var persistentTypeRepresentation: some IdentityRepresentation {
15 | CoreMI._ServiceVendorIdentifier._Mistral
16 | }
17 |
18 | public let interface: APISpecification
19 | public let session: HTTPSession
20 |
21 | public init(interface: APISpecification, session: HTTPSession) {
22 | self.interface = interface
23 | self.session = session
24 | }
25 |
26 | public convenience init(apiKey: String?) {
27 | self.init(
28 | interface: .init(configuration: .init(apiKey: apiKey)),
29 | session: .shared
30 | )
31 | }
32 | }
33 | }
34 |
35 | extension Mistral.Client: CoreMI._ServiceClientProtocol {
36 | public convenience init(
37 | account: (any CoreMI._ServiceAccountProtocol)?
38 | ) async throws {
39 | let account: any CoreMI._ServiceAccountProtocol = try account.unwrap()
40 | let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier = try account.serviceVendorIdentifier.unwrap()
41 |
42 | guard serviceVendorIdentifier == CoreMI._ServiceVendorIdentifier._Mistral else {
43 | throw CoreMI._ServiceClientError.incompatibleVendor(serviceVendorIdentifier)
44 | }
45 |
46 | guard let credential = try account.credential as? CoreMI._ServiceCredentialTypes.APIKeyCredential else {
47 | throw CoreMI._ServiceClientError.invalidCredential(try account.credential)
48 | }
49 |
50 | self.init(apiKey: credential.apiKey)
51 | }
52 | }
53 |
54 | extension Mistral.Client {
55 | public func createEmbeddings(
56 | for input: [String]
57 | ) async throws -> Mistral.Embeddings {
58 | try await run(\.createEmbeddings, with: .init(input: input))
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Mistral.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 | import LargeLanguageModels
8 | import Swallow
9 |
10 | extension Mistral {
11 | public enum Model: String, CaseIterable, Codable, Hashable, Named, Sendable {
12 | case mistral_tiny = "mistral-tiny"
13 | case mistral_small = "mistral-small"
14 | case mistral_medium = "mistral-medium"
15 | case mistral_embed = "mistral-embed"
16 |
17 | public var name: String {
18 | switch self {
19 | case .mistral_tiny:
20 | return "Tiny"
21 | case .mistral_small:
22 | return "Small"
23 | case .mistral_medium:
24 | return "Medium"
25 | case .mistral_embed:
26 | return "Embed"
27 | }
28 | }
29 | }
30 | }
31 |
32 | // MARK: - Conformances
33 |
34 | extension Mistral.Model: CustomStringConvertible {
35 | public var description: String {
36 | rawValue
37 | }
38 | }
39 |
40 | extension Mistral.Model: ModelIdentifierRepresentable {
41 | public init(from identifier: ModelIdentifier) throws {
42 | guard identifier.provider == ._Mistral, identifier.revision == nil else {
43 | throw Never.Reason.illegal
44 | }
45 |
46 | guard let model = Self(rawValue: identifier.name) else {
47 | throw Never.Reason.unexpected
48 | }
49 |
50 | self = model
51 | }
52 |
53 | public func __conversion() -> ModelIdentifier {
54 | ModelIdentifier(
55 | provider: ._Mistral,
56 | name: rawValue,
57 | revision: nil
58 | )
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Mistral.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Mistral {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Models/Mistral.ChatMessage.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension Mistral {
8 | public struct ChatMessage: Codable, Hashable, Sendable {
9 | public enum Role: String, Codable, Hashable, Sendable {
10 | case system
11 | case user
12 | case assistant
13 | }
14 |
15 | public var role: Role
16 | public var content: String
17 |
18 | public init(role: Role, content: String) {
19 | self.role = role
20 | self.content = content
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/Mistral/Intramodular/Models/Mistral.Embedding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension Mistral {
8 | public struct Embeddings: Codable, Hashable, Sendable {
9 | public let id: String
10 | public let object: String
11 | public let data: [EmbeddingData]
12 | public let model: String
13 | public let usage: Usage
14 | }
15 | }
16 |
17 | extension Mistral.Embeddings {
18 | public struct EmbeddingData: Codable, Hashable, Sendable {
19 | public let object: String
20 | public let embedding: [Double]
21 | public let index: Int
22 | }
23 | }
24 |
25 | extension Mistral.Embeddings {
26 | public struct Usage: Codable, Hashable, Sendable {
27 | public let promptTokens: Int
28 | public let totalTokens: Int
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Sources/Mistral/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/API/NeetsAI.APISpecification.RequestBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.APISpecification.RequestBodies.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | extension NeetsAI.APISpecification {
9 | enum RequestBodies {
10 | struct TTSInput: Codable {
11 | let params: TTSParams
12 | let text: String
13 | let voiceId: String
14 |
15 | struct TTSParams: Codable {
16 | let model: String
17 | let temperature: Double
18 | let diffusionIterations: Int
19 |
20 | private enum CodingKeys: String, CodingKey {
21 | case model
22 | case temperature
23 | case diffusionIterations = "diffusion_iterations"
24 | }
25 | }
26 |
27 | private enum CodingKeys: String, CodingKey {
28 | case params
29 | case text
30 | case voiceId = "voice_id"
31 | }
32 | }
33 |
34 | struct ChatInput: Codable {
35 | let messages: [NeetsAI.ChatMessage]
36 | let model: String
37 | }
38 | }
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/API/NeetsAI.APISpecification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.APISpecification.ResponseBodies.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension NeetsAI.APISpecification {
11 | enum ResponseBodies {
12 | typealias ChatCompletion = NeetsAI.ChatCompletion
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/Models/NeetsAI.ChatMessage.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.ChatMessage.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension NeetsAI {
11 | public struct ChatMessage: Codable, Hashable {
12 | public let role: String
13 | public let content: String
14 | public let toolCalls: [String]?
15 |
16 | private enum CodingKeys: String, CodingKey {
17 | case role
18 | case content
19 | case toolCalls
20 | }
21 | }
22 |
23 | public struct ChatCompletion: Codable {
24 | public let id: String
25 | public let object: String
26 | public let created: Int
27 | public let model: String
28 | public let choices: [Choice]
29 | public let usage: Usage
30 |
31 | public struct Choice: Codable {
32 | public let index: Int
33 | public let message: ChatMessage
34 | public let logprobs: String?
35 | public let finishReason: String?
36 | public let stopReason: String?
37 |
38 | private enum CodingKeys: String, CodingKey {
39 | case index
40 | case message
41 | case logprobs
42 | case finishReason
43 | case stopReason
44 | }
45 | }
46 |
47 | public struct Usage: Codable {
48 | public let promptTokens: Int
49 | public let totalTokens: Int
50 | public let completionTokens: Int
51 |
52 | private enum CodingKeys: String, CodingKey {
53 | case promptTokens
54 | case totalTokens
55 | case completionTokens
56 | }
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/Models/NeetsAI.Voice.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.Voice.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension NeetsAI {
11 | public struct Voice: Codable, Hashable {
12 | public let id: String
13 | public let title: String?
14 | public let aliasOf: String?
15 | public let supportedModels: [String]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/NeetsAI.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.Model.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import CoreMI
9 | import CorePersistence
10 | import Foundation
11 | import Swift
12 |
13 | extension NeetsAI {
14 | public enum Model: String, Codable, Sendable {
15 | case arDiff50k = "ar-diff-50k"
16 | case styleDiff500 = "style-diff-500"
17 | case vits = "vits"
18 | case mistralai = "mistralai/Mixtral-8X7B-Instruct-v0.1"
19 | }
20 | }
21 |
22 | // MARK: - Model Conformances
23 |
24 | extension NeetsAI.Model: CustomStringConvertible {
25 | public var description: String {
26 | rawValue
27 | }
28 | }
29 |
30 | extension NeetsAI.Model: ModelIdentifierRepresentable {
31 | public init(from identifier: ModelIdentifier) throws {
32 | guard identifier.provider == ._NeetsAI, identifier.revision == nil else {
33 | throw Never.Reason.illegal
34 | }
35 |
36 | guard let model = Self(rawValue: identifier.name) else {
37 | throw Never.Reason.unexpected
38 | }
39 |
40 | self = model
41 | }
42 |
43 | public func __conversion() throws -> ModelIdentifier {
44 | ModelIdentifier(
45 | provider: ._NeetsAI,
46 | name: rawValue,
47 | revision: nil
48 | )
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/Intramodular/NeetsAI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // NeetsAI.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Swift
9 |
10 | public enum NeetsAI {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/NeetsAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 |
--------------------------------------------------------------------------------
/Sources/Ollama/Intramodular/Ollama.APISpecification+Responses.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Merge
7 | import NetworkKit
8 |
9 | extension Ollama.APISpecification.ResponseBodies {
10 | public struct GenerateCompletion: Codable, Hashable, Sendable {
11 | public let model: Ollama.Model.ID
12 | public let createdAt: Date
13 | public let response: String
14 | public let context: [Int]?
15 |
16 | public let done: Bool
17 |
18 | public let totalDuration: Int?
19 | public let loadDuration: Int?
20 | public let promptEvalCount: Int?
21 | public let promptEvalDuration: Int?
22 | public let evalCount: Int?
23 | public let evalDuration: Int?
24 | }
25 |
26 | public struct GenerateChatCompletion: Codable, Hashable, Sendable {
27 | public let model: Ollama.Model.ID
28 | public let createdAt: Date
29 | public let message: Ollama.ChatMessage?
30 |
31 | public let done: Bool
32 |
33 | public let totalDuration: Int?
34 | public let loadDuration: Int?
35 | public let promptEvalCount: Int?
36 | public let promptEvalDuration: Int?
37 | public let evalCount: Int?
38 | public let evalDuration: Int?
39 | }
40 |
41 | public struct GetModels: Codable, Hashable, Sendable {
42 | public let models: [Ollama.Model]
43 | }
44 |
45 | public struct GetModelInfo: Codable, Hashable, Sendable {
46 | public let modelfile: String
47 | public let parameters: String?
48 | public let template: String?
49 | public let license: String?
50 | public var details: Details?
51 |
52 | public struct Details: Codable, Hashable, Sendable {
53 | public var format: String?
54 | public var families: String?
55 | public var parameterSize: String?
56 | public var quantizationLevel: String?
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/Sources/Ollama/Intramodular/Ollama.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import LargeLanguageModels
7 | import Merge
8 | import NetworkKit
9 |
10 | extension Ollama {
11 | public struct Model: Codable, Hashable, Identifiable, Named, Sendable {
12 | public typealias ID = _TypeAssociatedID
13 |
14 | public let name: String
15 | public let digest: String
16 | public let size: Int
17 | public let modifiedAt: Date
18 |
19 | public var id: ID {
20 | ID(rawValue: name)
21 | }
22 |
23 | public init(
24 | name: String,
25 | digest: String,
26 | size: Int,
27 | modifiedAt: Date
28 | ) {
29 | self.name = name
30 | self.digest = digest
31 | self.size = size
32 | self.modifiedAt = modifiedAt
33 | }
34 | }
35 | }
36 |
37 | // MARK: - Conformances
38 |
39 | extension Ollama.Model: CustomStringConvertible {
40 | public var description: String {
41 | name
42 | }
43 | }
44 |
45 | extension Ollama.Model: ModelIdentifierConvertible {
46 | public func __conversion() throws -> ModelIdentifier {
47 | ModelIdentifier(
48 | provider: ._Ollama,
49 | name: self.name,
50 | revision: nil
51 | )
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/Sources/Ollama/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import Swallow
7 | @_exported import SwallowMacrosClient
8 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular (WIP)/OpenAI.ChatFunctionHandler.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Diagnostics
7 | import Swift
8 |
9 | extension OpenAI {
10 | public protocol ChatFunctionHandler: Initiable {
11 | associatedtype Result: Codable & Hashable
12 |
13 | var name: String { get }
14 |
15 | init()
16 |
17 | func perform() throws -> Result
18 | }
19 |
20 | public protocol ChatFunctionResult: Codable, Hashable, Sendable {
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Client/OpenAI.Client+CoreMI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 |
8 | extension OpenAI.Client: CoreMI._ServiceClientProtocol {
9 | public convenience init(
10 | account: (any CoreMI._ServiceAccountProtocol)?
11 | ) async throws {
12 | let account: any CoreMI._ServiceAccountProtocol = try account.unwrap()
13 | let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier = try account.serviceVendorIdentifier.unwrap()
14 |
15 | guard serviceVendorIdentifier == CoreMI._ServiceVendorIdentifier._OpenAI else {
16 | throw CoreMI._ServiceClientError.incompatibleVendor(serviceVendorIdentifier)
17 | }
18 |
19 | guard let credential = try account.credential as? CoreMI._ServiceCredentialTypes.APIKeyCredential else {
20 | throw CoreMI._ServiceClientError.invalidCredential(try account.credential)
21 | }
22 |
23 | self.init(apiKey: credential.apiKey)
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Client/OpenAI.Client+TextEmbeddingsRequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 |
8 | extension OpenAI.Client: TextEmbeddingsRequestHandling {
9 | public func fulfill(
10 | _ request: TextEmbeddingsRequest
11 | ) async throws -> TextEmbeddings {
12 | guard !request.input.isEmpty else {
13 | return TextEmbeddings(
14 | model: .init(from: OpenAI.Model.Embedding.ada),
15 | data: []
16 | )
17 | }
18 |
19 | let model: ModelIdentifier = request.model ?? ModelIdentifier(from: OpenAI.Model.Embedding.ada)
20 | let embeddingModel = try OpenAI.Model.Embedding(rawValue: model.name).unwrap()
21 |
22 | let embeddings = try await createEmbeddings(
23 | model: embeddingModel,
24 | for: request.input
25 | ).data
26 |
27 | try _tryAssert(request.input.count == embeddings.count)
28 |
29 | return TextEmbeddings(
30 | model: .init(from: OpenAI.Model.Embedding.ada),
31 | data: request.input.zip(embeddings).map {
32 | TextEmbeddings.Element(
33 | text: $0,
34 | embedding: $1.embedding,
35 | model: model
36 | )
37 | }
38 | )
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Client/OpenAI.Client-Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI.Client {
9 | public func createEmbeddings(
10 | model: OpenAI.Model.Embedding,
11 | for input: [String]
12 | ) async throws -> OpenAI.APISpecification.ResponseBodies.CreateEmbedding {
13 | try await run(\.createEmbeddings, with: .init(model: model, input: input))
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Client/OpenAI.Client-Image.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Swallow
7 |
8 | extension OpenAI.Client {
9 | /// The format in which the generated images are returned.
10 | public enum ImageResponseFormat: String, Codable, CaseIterable {
11 | /// URLs are only valid for 60 minutes after the image has been generated.
12 | case ephemeralURL = "url"
13 | case base64JSON
14 | }
15 |
16 | /// Create an image using DALL-E.
17 | ///
18 | /// The maximum length for the prompt is `1000` characters for `dall-e-2` and `4000` characters for `dall-e-3`.
19 | public func createImage(
20 | prompt: String,
21 | responseFormat: ImageResponseFormat = .ephemeralURL,
22 | numberOfImages: Int = 1,
23 | quality: OpenAI.Image.Quality = .standard,
24 | size: OpenAI.Image.Size = .w1024h1024,
25 | style: OpenAI.Image.Style = .vivid,
26 | user: String? = nil
27 | ) async throws -> OpenAI.List {
28 | let requestBody = OpenAI.APISpecification.RequestBodies.CreateImage(
29 | prompt: prompt,
30 | model: .dalle3,
31 | responseFormat: responseFormat,
32 | numberOfImages: numberOfImages,
33 | quality: quality,
34 | size: size,
35 | style: style,
36 | user: user
37 | )
38 |
39 | let response = try await run(\.createImage, with: requestBody)
40 |
41 | return response
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Client/OpenAI.Client-Speech.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 |
6 | import Foundation
7 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/API Specification/OpenAI.APISpecification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import NetworkKit
7 |
8 | extension OpenAI.APISpecification {
9 | public enum ResponseBodies {
10 |
11 | }
12 | }
13 |
14 | extension OpenAI.APISpecification.ResponseBodies {
15 | public final class CreateEmbedding: OpenAI.List, @unchecked Sendable {
16 | private enum CodingKeys: String, CodingKey {
17 | case model
18 | case usage
19 | }
20 |
21 | public let model: OpenAI.Model.Embedding
22 | public let usage: OpenAI.Usage
23 |
24 | public required init(from decoder: Decoder) throws {
25 | let container = try decoder.container(keyedBy: CodingKeys.self)
26 |
27 | self.model = try container.decode(forKey: .model)
28 | self.usage = try container.decode(forKey: .usage)
29 |
30 | try super.init(from: decoder)
31 |
32 | self.data = self.data.sorted(by: \.index)
33 | }
34 |
35 | public override func encode(to encoder: Encoder) throws {
36 | try super.encode(to: encoder)
37 |
38 | var container = encoder.container(keyedBy: CodingKeys.self)
39 |
40 | try container.encode(model, forKey: .model)
41 | try container.encode(usage, forKey: .usage)
42 | }
43 | }
44 |
45 | struct CreateChatCompletion: Codable, Hashable, Sendable {
46 | public let message: OpenAI.ChatMessage
47 | }
48 |
49 | struct CreateTranscription: Codable, Hashable, Sendable {
50 | let language: String?
51 | let duration: Double?
52 | let text: String
53 | let words: [OpenAI.AudioTranscription.Word]?
54 | let segments: [OpenAI.AudioTranscription.TranscriptionSegment]?
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Miscellaneous/Tiktoken/Tiktoken.Encoding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import LargeLanguageModels
7 | import Swallow
8 |
9 | extension Tiktoken {
10 | public class Encoding {
11 | typealias Ranks = [[UInt8]: Int]
12 |
13 | private let name: String
14 | private let regex: NSRegularExpression // Regex
15 | private let mergeableRanks: [[UInt8]: Int]
16 | private let specialTokens: [String: Int]
17 | private let maxValueToken: Int
18 |
19 | private let coreBPE: CoreBPE
20 |
21 | init(
22 | name: String,
23 | regex: NSRegularExpression,
24 | mergeableRanks: [[UInt8]: Int],
25 | specialTokens: [String: Int],
26 | explicitNVocab: Int? = nil
27 | ) {
28 | self.name = name
29 | self.regex = regex
30 | self.mergeableRanks = mergeableRanks
31 | self.specialTokens = specialTokens
32 | self.maxValueToken = max(mergeableRanks.values.max() ?? 0, specialTokens.values.max() ?? 0)
33 |
34 | let decoder = mergeableRanks.inverted
35 |
36 | self.coreBPE = .init(encoder: mergeableRanks, decoder: decoder, regexTls: [regex])
37 | }
38 | }
39 | }
40 |
41 | extension Tiktoken.Encoding {
42 | public func encode(_ text: String) -> [Int] {
43 | coreBPE.encodeOrdinaryNative(text: text)
44 | }
45 |
46 | public func decode(_ value: [Int]) -> String {
47 | coreBPE.decodeNative(tokens: value)
48 | }
49 | }
50 |
51 | extension Tiktoken.Encoding.Ranks {
52 | var inverted: [Int: [UInt8]] {
53 | reduce(into: [:], { $0[$1.value] = $1.key })
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Miscellaneous/Tiktoken/Tiktoken.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | public enum Tiktoken {
9 | public static func encoding(
10 | for model: OpenAI.Model
11 | ) async throws -> Encoding? {
12 | guard let vocabulary = model.bytePairEncodingVocabulary else {
13 | return nil
14 | }
15 |
16 | let encoder = try await loadRanks(vocabulary)
17 |
18 | let regex = try NSRegularExpression(pattern: vocabulary.pattern)
19 |
20 | let encoding = Encoding(
21 | name: model.rawValue,
22 | regex: regex,
23 | mergeableRanks: encoder,
24 | specialTokens: vocabulary.specialTokens
25 | )
26 |
27 | return encoding
28 | }
29 |
30 | public static func loadRanks(
31 | _ vocabulary: BPEVocabulary
32 | ) async throws -> [[UInt8]: Int] {
33 | if ["gpt2", "gpt3"].contains(vocabulary.name) {
34 | return await TokenizerResources.dataGymToMergeableBPERanks(vocabularyBPEFile: vocabulary.url)
35 | } else {
36 | return try await TokenizerResources.loadTiktokenBPE(url: vocabulary.url)
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Miscellaneous/Tiktoken/_VocabularyFileDecoder.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | struct _VocabularyFileDecoder {
9 | func decode(
10 | _ data: Data
11 | ) -> [[UInt8]: Int] {
12 | guard let decoded = String(data: data, encoding: .utf8) else {
13 | return [:]
14 | }
15 |
16 | var result: [[UInt8]: Int] = .init()
17 |
18 | decoded.split(separator: "\n").forEach {
19 | let lineSplit = $0.split(separator: " ")
20 |
21 | guard
22 | let first = lineSplit.first,
23 | let key = try? String(from: String(first), using: .base64),
24 | let value = lineSplit.last
25 | else {
26 | return
27 | }
28 |
29 | result[key.utf16AsUInt8Array] = Int(value)
30 | }
31 |
32 | return result
33 | }
34 | }
35 |
36 | // MARK: - Helpers
37 |
38 | extension String {
39 | fileprivate var utf16AsUInt8Array: [UInt8] {
40 | var bytes: [UInt8] = []
41 | bytes.reserveCapacity(utf16.count * 2)
42 |
43 | for codeUnit in utf16 {
44 | let highByte = UInt8(codeUnit >> 8)
45 | let lowByte = UInt8(codeUnit & 0xFF)
46 | if highByte != 0 { bytes.append(highByte) }
47 | bytes.append(lowByte)
48 | }
49 |
50 | return bytes
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.AssistantFile.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI {
9 | public final class AssistantFile: OpenAI.Object {
10 | private enum CodingKeys: String, CodingKey {
11 | case id
12 | case createdAt = "created_at"
13 | case assistantID = "assistant_id"
14 | }
15 |
16 | public struct DeletionStatus: Decodable {
17 | public let id: String
18 | public let object: String
19 | public let deleted: Bool
20 | }
21 |
22 | let id: String
23 | let createdAt: Int
24 | let assistantID: String
25 |
26 | public required init(from decoder: Decoder) throws {
27 | let container = try decoder.container(keyedBy: CodingKeys.self)
28 |
29 | self.id = try container.decode(forKey: .id)
30 | self.createdAt = try container.decode(forKey: .createdAt)
31 | self.assistantID = try container.decode(forKey: .assistantID)
32 |
33 | try super.init(from: decoder)
34 | }
35 |
36 | public override func encode(to encoder: Encoder) throws {
37 | try super.encode(to: encoder)
38 |
39 | var container = encoder.container(keyedBy: CodingKeys.self)
40 |
41 | try container.encode(id, forKey: .id)
42 | try container.encode(createdAt, forKey: .createdAt)
43 | try container.encode(assistantID, forKey: .assistantID)
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.ChatFunctionDefinition.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Diagnostics
7 | import LargeLanguageModels
8 | import Swallow
9 |
10 | extension OpenAI {
11 | public struct ToolName: Codable, Hashable, RawRepresentable, Sendable {
12 | public let rawValue: String
13 |
14 | public init(rawValue: String) {
15 | self.rawValue = rawValue
16 | }
17 |
18 | public init(from decoder: any Decoder) throws {
19 | rawValue = try String(from: decoder)
20 | }
21 |
22 | public func encode(to encoder: any Encoder) throws {
23 | try rawValue.encode(to: encoder)
24 | }
25 | }
26 |
27 | public struct ChatFunctionDefinition: Codable, Hashable, Sendable {
28 | public let name: OpenAI.ToolName
29 | public let description: String
30 | public let parameters: JSONSchema
31 |
32 | public init(
33 | name: OpenAI.ToolName,
34 | description: String,
35 | parameters: JSONSchema
36 | ) {
37 | self.name = name
38 | self.description = description
39 | self.parameters = parameters
40 | }
41 |
42 | public init(
43 | name: String,
44 | description: String,
45 | parameters: JSONSchema
46 | ) {
47 | self.init(
48 | name: OpenAI.ToolName(
49 | rawValue: name
50 | ),
51 | description: description,
52 | parameters: parameters
53 | )
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.ChatRole.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import Diagnostics
7 | import LargeLanguageModels
8 | import Swallow
9 |
10 | extension OpenAI {
11 | public enum ChatRole: String, Codable, Hashable, Sendable {
12 | case system
13 | case user
14 | case assistant
15 | case function
16 |
17 | public init(
18 | from role: AbstractLLM.ChatRole
19 | ) {
20 | switch role {
21 | case .system:
22 | self = .system
23 | case .user:
24 | self = .user
25 | case .assistant:
26 | self = .assistant
27 | case .other(.function):
28 | self = .function
29 | }
30 | }
31 |
32 | public func __conversion() throws -> AbstractLLM.ChatRole {
33 | switch self {
34 | case .system:
35 | return .system
36 | case .user:
37 | return .user
38 | case .assistant:
39 | return .assistant
40 | case .function:
41 | return .other(.function)
42 | }
43 | }
44 | }
45 | }
46 |
47 | // MARK: - Supplementary
48 |
49 | extension OpenAI.ChatMessage {
50 | public typealias Role = OpenAI.ChatRole
51 | }
52 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.Embedding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI {
9 | public final class Embedding: OpenAI.Object, @unchecked Sendable {
10 | private enum CodingKeys: String, CodingKey {
11 | case embedding
12 | case index
13 | }
14 |
15 | public let embedding: [Double]
16 | public let index: Int
17 |
18 | public required init(from decoder: Decoder) throws {
19 | let container = try decoder.container(keyedBy: CodingKeys.self)
20 |
21 | self.embedding = try container.decode(forKey: .embedding)
22 | self.index = try container.decode(forKey: .index)
23 |
24 | try super.init(from: decoder)
25 | }
26 |
27 | public override func encode(to encoder: Encoder) throws {
28 | try super.encode(to: encoder)
29 |
30 | var container = encoder.container(keyedBy: CodingKeys.self)
31 |
32 | try container.encode(embedding, forKey: .embedding)
33 | try container.encode(index, forKey: .index)
34 | }
35 | }
36 | }
37 |
38 | // MARK: - Conformances
39 |
40 | extension OpenAI.Embedding: Hashable {
41 | public func hash(into hasher: inout Hasher) {
42 | hasher.combine(embedding)
43 | hasher.combine(index)
44 | }
45 |
46 | public static func == (lhs: OpenAI.Embedding, rhs: OpenAI.Embedding) -> Bool {
47 | lhs.embedding == rhs.embedding && lhs.index == rhs.index
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.Model-Latest.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | extension OpenAI.Model {
8 | public static var gpt_3_5: Self {
9 | .chat(.gpt_3_5_turbo)
10 | }
11 |
12 | public static var gpt_4: Self {
13 | .chat(.gpt_4)
14 | }
15 |
16 | public static var gpt_4o: Self {
17 | .chat(.gpt_4o)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.Speech.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI {
9 | public final class Speech: OpenAI.Object, @unchecked Sendable {
10 | public let data: Data
11 |
12 | public required init(from decoder: Decoder) throws {
13 | let container = try decoder.container(keyedBy: CodingKeys.self)
14 |
15 | self.data = try container.decode(forKey: .data)
16 |
17 | try super.init(from: decoder)
18 | }
19 |
20 | public init(data: Data) {
21 | self.data = data
22 | super.init(type: .speech)
23 | }
24 |
25 | enum CodingKeys: CodingKey {
26 | case data
27 | }
28 | }
29 | }
30 |
31 | extension OpenAI.Speech {
32 | /// Encapsulates the voices available for audio generation.
33 | ///
34 | /// To get aquinted with each of the voices and listen to the samples visit:
35 | /// [OpenAI Text-to-Speech – Voice Options](https://platform.openai.com/docs/guides/text-to-speech/voice-options)
36 | public enum Voice: String, Codable, CaseIterable {
37 | case alloy
38 | case echo
39 | case fable
40 | case onyx
41 | case nova
42 | case shimmer
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.Thread.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI {
9 | public final class Thread: OpenAI.Object, @unchecked Sendable {
10 | public typealias ID = _TypeAssociatedID
11 |
12 | private enum CodingKeys: String, CodingKey {
13 | case id
14 | case createdAt
15 | case metadata
16 | }
17 |
18 | public let id: ID
19 | public let createdAt: Int
20 | public let metadata: [String: String]
21 |
22 | public required init(from decoder: Decoder) throws {
23 | let container = try decoder.container(keyedBy: CodingKeys.self)
24 |
25 | self.id = try container.decode(forKey: .id)
26 | self.createdAt = try container.decode(forKey: .createdAt)
27 | self.metadata = try container.decode(forKey: .metadata)
28 |
29 | try super.init(from: decoder)
30 | }
31 |
32 | public override func encode(to encoder: Encoder) throws {
33 | try super.encode(to: encoder)
34 |
35 | var container = encoder.container(keyedBy: CodingKeys.self)
36 |
37 | try container.encode(id, forKey: .id)
38 | try container.encode(createdAt, forKey: .createdAt)
39 | try container.encode(metadata, forKey: .metadata)
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/Models/OpenAI.Voice.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import NetworkKit
6 | import Swift
7 |
8 | extension OpenAI.Client {
9 | public func createSpeech(
10 | model: OpenAI.Model,
11 | text: String,
12 | voice: OpenAI.Speech.Voice = .alloy,
13 | speed: Double?
14 | ) async throws -> OpenAI.Speech {
15 | let requestBody = OpenAI.APISpecification.RequestBodies.CreateSpeech(
16 | model: model,
17 | input: text,
18 | voice: voice,
19 | speed: speed
20 | )
21 |
22 | let data = try await run(\.createSpeech, with: requestBody)
23 |
24 | return OpenAI.Speech(data: data)
25 | }
26 |
27 | public func createSpeech(
28 | model: OpenAI.Model.Speech,
29 | text: String,
30 | voice: OpenAI.Speech.Voice = .alloy,
31 | speed: Double?
32 | ) async throws -> OpenAI.Speech {
33 | let requestBody = OpenAI.APISpecification.RequestBodies.CreateSpeech(
34 | model: OpenAI.Model.speech(model),
35 | input: text,
36 | voice: voice,
37 | speed: speed
38 | )
39 |
40 | let data = try await run(\.createSpeech, with: requestBody)
41 |
42 | return OpenAI.Speech(data: data)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/OpenAI.ModelRating.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import FoundationX
6 | import Swallow
7 |
8 | public struct _OpenAI_ModelRating {
9 | public let reasoning: LikertScale5
10 | public let speed: LikertScale5
11 | public let conciseness: LikertScale5
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/OpenAI/Intramodular/OpenAI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swift
7 |
8 | @RuntimeDiscoverable
9 | public enum OpenAI: _StaticSwift.TypeIterableNamespace {
10 | public static var _allNamespaceTypes: [any Any.Type] {
11 | OpenAI.Client.self
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/Sources/OpenAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/Perplexity/Intramodular/Perplexity.APISpecification/Perplexity.APISpecification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import OpenAI
7 |
8 | extension Perplexity.APISpecification.ResponseBodies {
9 | public struct ChatCompletion: Codable, Hashable, Sendable {
10 | public struct Choice: Codable, Hashable, Sendable {
11 | public enum FinishReason: String, Codable, Hashable, Sendable {
12 | case stop
13 | case length
14 | }
15 |
16 | public let index: Int
17 |
18 | /// The message generated by the model.
19 | public let message: Perplexity.ChatMessage
20 |
21 | /// The reason the model stopped generating tokens. Possible values include stop if the model hit a natural stopping point, or length if the maximum number of tokens specified in the request was reached.
22 | public let finishReason: FinishReason
23 |
24 | /// The incrementally streamed next tokens. Only meaningful when stream = true.
25 | public let delta: Perplexity.ChatMessage
26 | }
27 |
28 | public struct Usage: Codable, Hashable, Sendable {
29 | public let promptTokens: Int
30 | public let completionTokens: Int
31 | public let totalTokens: Int
32 | }
33 |
34 | /// An ID generated uniquely for each response.
35 | public var id: String
36 | public var object: String
37 | public var created: Date
38 | public var model: Perplexity.Model
39 | public var choices: [Choice]
40 | public let usage: Usage
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Sources/Perplexity/Intramodular/Perplexity.ChatMessage.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import OpenAI
7 |
8 | extension Perplexity {
9 | public typealias ChatMessage = OpenAI.ChatMessage
10 | }
11 |
--------------------------------------------------------------------------------
/Sources/Perplexity/Intramodular/Perplexity.Client.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import Merge
8 | import NetworkKit
9 | import Swallow
10 |
11 | extension Perplexity {
12 | @RuntimeDiscoverable
13 | public final class Client: HTTPClient, _StaticSwift.Namespace {
14 | public static var persistentTypeRepresentation: some IdentityRepresentation {
15 | CoreMI._ServiceVendorIdentifier._Perplexity
16 | }
17 |
18 | public let interface: APISpecification
19 | public let session: HTTPSession
20 |
21 | public init(interface: APISpecification, session: HTTPSession) {
22 | self.interface = interface
23 | self.session = session
24 | }
25 |
26 | public convenience init(apiKey: String?) {
27 | self.init(
28 | interface: .init(configuration: .init(apiKey: apiKey)),
29 | session: .shared
30 | )
31 | }
32 | }
33 | }
34 |
35 | extension Perplexity.Client: CoreMI._ServiceClientProtocol {
36 | public convenience init(
37 | account: (any CoreMI._ServiceAccountProtocol)?
38 | ) async throws {
39 | let account: any CoreMI._ServiceAccountProtocol = try account.unwrap()
40 | let serviceVendorIdentifier: CoreMI._ServiceVendorIdentifier = try account.serviceVendorIdentifier.unwrap()
41 |
42 | guard serviceVendorIdentifier == CoreMI._ServiceVendorIdentifier._Perplexity else {
43 | throw CoreMI._ServiceClientError.incompatibleVendor(serviceVendorIdentifier)
44 | }
45 |
46 | guard let credential = try account.credential as? CoreMI._ServiceCredentialTypes.APIKeyCredential else {
47 | throw CoreMI._ServiceClientError.invalidCredential(try account.credential)
48 | }
49 |
50 | self.init(apiKey: credential.apiKey)
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/Perplexity/Intramodular/Perplexity.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum Perplexity {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/Perplexity/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | import Swift
7 |
--------------------------------------------------------------------------------
/Sources/PlayHT/Intramodular/API/PlayHT.APISpeicification.ResponseBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // PlayHT.APISpeicification.ResponseBodies.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension PlayHT.APISpecification {
11 | public enum ResponseBodies {
12 | public struct Voices: Codable {
13 | public let voices: [PlayHT.Voice]
14 |
15 | public init(from decoder: Decoder) throws {
16 | if let container: SingleValueDecodingContainer = try? decoder.singleValueContainer(),
17 | let voices: [PlayHT.Voice] = try? container.decode([PlayHT.Voice].self) {
18 | self.voices = voices
19 | } else {
20 | let container = try decoder.container(keyedBy: CodingKeys.self)
21 | self.voices = try container.decode([PlayHT.Voice].self, forKey: .voices)
22 | }
23 | }
24 |
25 | private enum CodingKeys: String, CodingKey {
26 | case voices
27 | }
28 | }
29 |
30 | public struct ClonedVoiceOutput: Codable {
31 | public let id: String
32 | public let name: String
33 | public let status: String
34 | }
35 |
36 | public struct TextToSpeechResponse: Codable {
37 | public let description: String
38 | public let method: String
39 | public let href: String
40 | public let contentType: String
41 | public let rel: String
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/PlayHT/Intramodular/Models/PlayHT.OutputSettings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // PlayHT.OutputSettings.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | import Swift
9 |
10 | extension PlayHT {
11 | public struct OutputSettings: Codable, Hashable {
12 | public let quality: Quality
13 | public let format: OutputFormat
14 | public let sampleRate: Int
15 |
16 | public init(
17 | quality: Quality = .medium,
18 | format: OutputFormat = .mp3,
19 | sampleRate: Int = 48000
20 | ) {
21 | self.quality = quality
22 | self.format = format
23 | self.sampleRate = sampleRate
24 | }
25 |
26 | public static let `default` = OutputSettings()
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/PlayHT/Intramodular/Models/PlayHT.VoiceSettings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // PlayHT.VoiceSettings.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | extension PlayHT {
9 | public struct VoiceSettings: Codable, Hashable {
10 | public var speed: Double
11 | public var temperature: Double
12 | public var voiceGuidance: Double
13 | public var styleGuidance: Double
14 | public var textGuidance: Double
15 |
16 | public init(
17 | speed: Double = 1.0,
18 | temperature: Double = 1.0,
19 | voiceGuidance: Double = 3.0,
20 | styleGuidance: Double = 15.0,
21 | textGuidance: Double = 1.5
22 | ) {
23 | self.speed = max(0.1, min(5.0, speed))
24 | self.temperature = max(0, min(2.0, temperature))
25 | self.voiceGuidance = max(1, min(6.0, voiceGuidance))
26 | self.styleGuidance = max(1, min(30.0, styleGuidance))
27 | self.textGuidance = max(1, min(2.0, textGuidance))
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Sources/PlayHT/Intramodular/PlayHT.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // PlayHT.Model.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | import CoreMI
9 | import CorePersistence
10 | import Foundation
11 | import Swift
12 |
13 | extension PlayHT {
14 | public enum Model: String, Codable, Sendable {
15 |
16 | case playHT2 = "PlayHT2.0"
17 |
18 | case playHT1 = "PlayHT1.0"
19 |
20 | case playHT2Turbo = "PlayHT2.0-turbo"
21 | }
22 | }
23 |
24 | // MARK: - Conformances
25 |
26 | extension PlayHT.Model: CustomStringConvertible {
27 | public var description: String {
28 | rawValue
29 | }
30 | }
31 |
32 | extension PlayHT.Model: ModelIdentifierRepresentable {
33 | public init(from identifier: ModelIdentifier) throws {
34 | guard identifier.provider == ._PlayHT, identifier.revision == nil else {
35 | throw Never.Reason.illegal
36 | }
37 |
38 | guard let model = Self(rawValue: identifier.name) else {
39 | throw Never.Reason.unexpected
40 | }
41 |
42 | self = model
43 | }
44 |
45 | public func __conversion() -> ModelIdentifier {
46 | ModelIdentifier(
47 | provider: ._PlayHT,
48 | name: rawValue,
49 | revision: nil
50 | )
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Sources/PlayHT/Intramodular/PlayHT.swift:
--------------------------------------------------------------------------------
1 | //
2 | // PlayHT.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | import Swift
9 |
10 | public enum PlayHT {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/PlayHT/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import Swallow
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/Rime/Intramodular/API/Rime.APISpecification.RequestBodies.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Rime.APISpecification.RequestBodies.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/21/24.
6 | //
7 |
8 | import NetworkKit
9 | import SwiftAPI
10 | import Merge
11 |
12 | extension Rime.APISpecification {
13 | enum RequestBodies {
14 |
15 | }
16 | }
17 |
18 | extension Rime.APISpecification.RequestBodies {
19 | struct TextToSpeechInput: Codable {
20 | fileprivate enum CodingKeys: String, CodingKey {
21 | case speaker
22 | case text
23 | case modelID = "modelId"
24 | }
25 |
26 | let speaker: String
27 | let text: String
28 | let modelID: String
29 |
30 | init(
31 | speaker: String,
32 | text: String,
33 | modelID: String
34 | ) {
35 | self.speaker = speaker
36 | self.text = text
37 | self.modelID = modelID
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Sources/Rime/Intramodular/Models/Rime.Voice.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Rime.Voice.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/21/24.
6 | //
7 |
8 | import Foundation
9 | import Swallow
10 |
11 | extension Rime {
12 | public struct Voice: Hashable {
13 | public let name: String
14 | public let age: String?
15 | public let country: String?
16 | public let region: String?
17 | public let demographic: String?
18 | public let genre: [String]?
19 | }
20 | }
21 |
22 | // MARK: - Conformances
23 |
24 | extension Rime.Voice: Codable {
25 | enum CodingKeys: CodingKey {
26 | case name
27 | case age
28 | case country
29 | case region
30 | case demographic
31 | case genre
32 | }
33 |
34 | public init(
35 | from decoder: any Decoder
36 | ) throws {
37 | let container: KeyedDecodingContainer = try decoder.container(keyedBy: Rime.Voice.CodingKeys.self)
38 |
39 | self.name = try container.decode(String.self, forKey: Rime.Voice.CodingKeys.name)
40 | self.age = try container.decodeIfPresent(String.self, forKey: Rime.Voice.CodingKeys.age)
41 | self.country = try container.decodeIfPresent(String.self, forKey: Rime.Voice.CodingKeys.country)
42 | self.region = try container.decodeIfPresent(String.self, forKey: Rime.Voice.CodingKeys.region)
43 | self.demographic = try container.decodeIfPresent(String.self, forKey: Rime.Voice.CodingKeys.demographic)
44 | self.genre = try container.decodeIfPresent([String].self, forKey: Rime.Voice.CodingKeys.genre)
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Sources/Rime/Intramodular/Rime.Client.OutputAudioType.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Rime.OutputAudioType.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import Swift
9 |
10 | extension Rime.Client {
11 | public enum StreamOutputAudioType {
12 | case MP3
13 | case PCM
14 | case MULAW
15 | }
16 |
17 | public enum OutputAudioType {
18 | case MP3
19 | case WAV
20 | case OGG
21 | case MULAW
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/Rime/Intramodular/Rime.Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Rime.Model.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/21/24.
6 | //
7 |
8 | import CoreMI
9 | import CorePersistence
10 | import Foundation
11 | import Swift
12 |
13 | extension Rime {
14 | public enum Model: String, Codable, Sendable {
15 | case mist = "mist"
16 | case v1 = "v1"
17 | }
18 | }
19 |
20 | // MARK: - Conformances
21 |
22 | extension Rime.Model: CustomStringConvertible {
23 | public var description: String {
24 | rawValue
25 | }
26 | }
27 |
28 | extension Rime.Model: ModelIdentifierRepresentable {
29 | public init(from identifier: ModelIdentifier) throws {
30 | guard identifier.provider == ._Rime, identifier.revision == nil else {
31 | throw Never.Reason.illegal
32 | }
33 |
34 | guard let model = Self(rawValue: identifier.name) else {
35 | throw Never.Reason.unexpected
36 | }
37 |
38 | self = model
39 | }
40 |
41 | public func __conversion() throws -> ModelIdentifier {
42 | ModelIdentifier(
43 | provider: ._Rime,
44 | name: rawValue,
45 | revision: nil
46 | )
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Sources/Rime/Intramodular/Rime.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Rime.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/21/24.
6 | //
7 |
8 | import Swift
9 |
10 | public enum Rime {
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/Sources/Rime/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/21/24.
6 | //
7 |
8 | @_exported import Swallow
9 | @_exported import SwallowMacrosClient
10 |
--------------------------------------------------------------------------------
/Sources/TogetherAI/Intramodular/TogetherAI.Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension TogetherAI {
8 | public struct Embeddings: Codable, Hashable, Sendable {
9 | public let model: String
10 | public let object: String
11 | public let data: [EmbeddingData]
12 | }
13 | }
14 |
15 | extension TogetherAI.Embeddings {
16 | public struct EmbeddingData: Codable, Hashable, Sendable {
17 | public let object: String
18 | public let embedding: [Float]
19 | public let index: Int
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Sources/TogetherAI/Intramodular/TogetherAI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum TogetherAI {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/TogetherAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/VoyageAI/Intramodular/VoyageAI.Client+TextEmbeddingsRequestHandling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CoreMI
6 | import CorePersistence
7 |
8 | extension VoyageAI.Client: TextEmbeddingsRequestHandling {
9 |
10 | public var _availableModels: [ModelIdentifier]? {
11 | VoyageAI.Model.allCases.map({ $0.__conversion() })
12 | }
13 |
14 | public func fulfill(
15 | _ request: TextEmbeddingsRequest
16 | ) async throws -> TextEmbeddings {
17 | let model = request.model ?? VoyageAI.Model.voyage2.__conversion()
18 | let embeddingModel = try VoyageAI.Model(rawValue: model.name).unwrap()
19 |
20 | let embeddings: VoyageAI.Embeddings = try await createEmbeddings(
21 | for: embeddingModel,
22 | input: request.input
23 | )
24 |
25 | let textEmbeddings = embeddings.data.map {
26 | TextEmbeddings.Element(
27 | text: $0.object,
28 | embedding: $0.embedding.map { Double($0) },
29 | model: model)
30 | }
31 |
32 | return TextEmbeddings(
33 | model: model,
34 | data: textEmbeddings
35 | )
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Sources/VoyageAI/Intramodular/VoyageAI.Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 |
7 | extension VoyageAI {
8 | public struct Embeddings: Codable, Hashable, Sendable {
9 | public let model: String
10 | public let object: String
11 | public let data: [EmbeddingData]
12 | public let usage: Usage
13 | }
14 | }
15 |
16 | extension VoyageAI.Embeddings {
17 | public struct EmbeddingData: Codable, Hashable, Sendable {
18 | public let object: String
19 | public let embedding: [Float]
20 | public let index: Int
21 | }
22 | }
23 |
24 | extension VoyageAI.Embeddings {
25 | public struct Usage: Codable, Hashable, Sendable {
26 | public let totalTokens: Int
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Sources/VoyageAI/Intramodular/VoyageAI.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Swift
6 |
7 | public enum VoyageAI {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/VoyageAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import LargeLanguageModels
6 | @_exported import SwallowMacrosClient
7 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.FineTuningExample.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.FineTuningExample.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 |
9 | extension _Gemini {
10 | public struct FineTuningExample: Codable {
11 | public let textInput: String
12 | public let output: String
13 |
14 | private enum CodingKeys: String, CodingKey {
15 | case textInput = "text_input"
16 | case output
17 | }
18 |
19 | public init(textInput: String, output: String) {
20 | self.textInput = textInput
21 | self.output = output
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.FineTuningExamples.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.FineTuningExamples.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | extension _Gemini {
9 | public struct FineTuningExamples: Codable {
10 | public let examples: [FineTuningExample]
11 |
12 | public init(examples: [FineTuningExample]) {
13 | self.examples = examples
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.Hyperparameters.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.Hyperparameters.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 |
9 | extension _Gemini {
10 | public struct Hyperparameters: Codable {
11 | public let batchSize: Int
12 | public let learningRate: Double
13 | public let epochCount: Int
14 |
15 | private enum CodingKeys: String, CodingKey {
16 | case batchSize = "batch_size"
17 | case learningRate = "learning_rate"
18 | case epochCount = "epoch_count"
19 | }
20 |
21 | public init(
22 | batchSize: Int = 2,
23 | learningRate: Double = 0.001,
24 | epochCount: Int = 5
25 | ) {
26 | self.batchSize = batchSize
27 | self.learningRate = learningRate
28 | self.epochCount = epochCount
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.TrainingData.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.TrainingData.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | extension _Gemini {
9 | public struct TrainingData: Codable {
10 | public let examples: FineTuningExamples
11 |
12 | public init(examples: FineTuningExamples) {
13 | self.examples = examples
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.TunedModel.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.TuningModel.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | // FIXME: - Break Apart
9 |
10 | extension _Gemini {
11 | public struct TunedModel: Codable {
12 | public let name: String
13 | public let displayName: String
14 | public let baseModel: String
15 | public let state: State
16 | public let createTime: String
17 | public let updateTime: String
18 |
19 | public enum State: String, Codable {
20 | case stateUnspecified = "STATE_UNSPECIFIED"
21 | case creating = "CREATING"
22 | case active = "ACTIVE"
23 | case failed = "FAILED"
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.TuningConfig.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.TuningConfig.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension _Gemini {
11 | public struct TuningConfig: Codable {
12 | public let displayName: String
13 | public let baseModel: String
14 | public let tuningTask: TuningTask
15 |
16 | public init(
17 | displayName: String,
18 | baseModel: _Gemini.Model,
19 | tuningTask: TuningTask
20 | ) {
21 | self.displayName = displayName
22 | self.baseModel = "models/" + baseModel.rawValue + "-001-tuning"
23 | self.tuningTask = tuningTask
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/Fine Tuning/_Gemini.TuningTask.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.TuningTask.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension _Gemini {
11 | public struct TuningTask: Codable {
12 | public let hyperparameters: Hyperparameters
13 | public let trainingData: TrainingData
14 |
15 | public init(
16 | hyperparameters: Hyperparameters,
17 | trainingData: TrainingData
18 | ) {
19 | self.hyperparameters = hyperparameters
20 | self.trainingData = trainingData
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/_Gemini.File.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.File.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/11/24.
6 | //
7 |
8 | import CorePersistence
9 | import Foundation
10 |
11 | extension _Gemini {
12 | public struct File: Codable, Hashable, Identifiable {
13 | @HadeanIdentifier("gupuj-nutuh-fabom-luhub")
14 | public struct ID: Codable, Hashable, Sendable {
15 | public let name: _Gemini.File.Name
16 | public let uri: URL
17 | }
18 |
19 | public let createTime: String?
20 | public let expirationTime: String?
21 | public let mimeType: String?
22 | public let name: _Gemini.File.Name
23 | public let sha256Hash: String?
24 | public let sizeBytes: String?
25 | public let state: State
26 | public let updateTime: String?
27 | public let uri: URL
28 | public let videoMetadata: VideoMetadata?
29 |
30 | public var id: _Gemini.File.ID {
31 | _Gemini.File.ID(name: name, uri: uri)
32 | }
33 | }
34 |
35 | public struct FileList: Codable, Hashable {
36 | public let files: [_Gemini.File]?
37 | // A token that can be sent as a pageToken into a subsequent files.list call.
38 | public let nextPageToken: String?
39 | }
40 | }
41 |
42 | extension _Gemini.File {
43 | public enum State: String, Codable {
44 | case processing = "PROCESSING"
45 | case active = "ACTIVE"
46 | }
47 |
48 | public struct VideoMetadata: Codable, Hashable {
49 | public let videoDuration: String
50 | }
51 |
52 | public struct Name: Codable, RawRepresentable, Hashable, Sendable {
53 | public let rawValue: String
54 |
55 | public init(rawValue: String) {
56 | self.rawValue = rawValue
57 | }
58 |
59 | public init(from decoder: any Decoder) throws {
60 | rawValue = try String(from: decoder)
61 | }
62 |
63 | public func encode(to encoder: any Encoder) throws {
64 | try rawValue.encode(to: encoder)
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/_Gemini.GoogleSearchRetrieval.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.GoogleSearchRetrieval.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension _Gemini {
11 | public struct GoogleSearchRetrieval: Codable {
12 | private enum CodingKeys: String, CodingKey {
13 | case dynamicRetrievalConfiguration = "dynamic_retrieval_config"
14 | }
15 |
16 | public let dynamicRetrievalConfiguration: DynamicRetrievalConfiguration
17 |
18 | public init(dynamicRetrievalConfiguration: DynamicRetrievalConfiguration) {
19 | self.dynamicRetrievalConfiguration = dynamicRetrievalConfiguration
20 | }
21 | }
22 |
23 | public struct DynamicRetrievalConfiguration: Codable {
24 | private enum CodingKeys: String, CodingKey {
25 | case mode
26 | case dynamicThreshold = "dynamic_threshold"
27 | }
28 |
29 | public let mode: String
30 | public let dynamicThreshold: Double
31 |
32 | public init(
33 | mode: String = "MODE_DYNAMIC",
34 | dynamicThreshold: Double
35 | ) {
36 | self.mode = mode
37 | self.dynamicThreshold = dynamicThreshold
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/Models/_Gemini.Message.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.Message.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/13/24.
6 | //
7 |
8 | import Foundation
9 |
10 | extension _Gemini {
11 | public struct Message: Codable {
12 | public let role: Role
13 | public let content: String
14 |
15 | public init(role: Role, content: String) {
16 | self.role = role
17 | self.content = content
18 | }
19 | internal func toRequestContent() -> _Gemini.APISpecification.RequestBodies.Content {
20 | .init(role: role.rawValue, parts: [.text(content)])
21 | }
22 | }
23 |
24 | public enum Role: String, Codable {
25 | case user = "user"
26 | case system = "system"
27 | case assistant = "assistant"
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/_Gemini.Client+CodeExecution.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Foundation
6 | import Swallow
7 |
8 | extension _Gemini.Client {
9 | public func generateContentWithCodeExecution(
10 | messages: [_Gemini.Message],
11 | model: _Gemini.Model,
12 | toolConfig: _Gemini.ToolConfiguration? = nil,
13 | configuration: _Gemini.GenerationConfiguration? = nil
14 | ) async throws -> _Gemini.Content {
15 | let contents = messages.filter { $0.role != .system }.map { message in
16 | _Gemini.APISpecification.RequestBodies.Content(
17 | role: message.role.rawValue,
18 | parts: [.text(message.content)]
19 | )
20 | }
21 |
22 | let systemInstruction = messages.first { $0.role == .system }.map { message in
23 | _Gemini.APISpecification.RequestBodies.Content(
24 | role: message.role.rawValue,
25 | parts: [.text(message.content)]
26 | )
27 | }
28 |
29 | let tool = _Gemini.Tool(codeExecutionEnabled: true)
30 | let input = _Gemini.APISpecification.RequestBodies.GenerateContentInput(
31 | model: model,
32 | requestBody: .init(
33 | contents: contents,
34 | generationConfig: configuration,
35 | tools: [tool],
36 | toolConfiguration: toolConfig,
37 | systemInstruction: systemInstruction
38 | )
39 | )
40 |
41 | let response = try await run(\.generateContent, with: input)
42 |
43 | let content = try _Gemini.Content(apiResponse: response)
44 |
45 | return content
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/_Gemini.Client+Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini..swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | extension _Gemini.Client {
9 | public func generateEmbedding(
10 | text: String,
11 | model: _Gemini.Model = .text_embedding_004
12 | ) async throws -> [Double] {
13 | let content = _Gemini.APISpecification.RequestBodies.Content(
14 | role: "user",
15 | parts: [.text(text)]
16 | )
17 |
18 | let input = _Gemini.APISpecification.RequestBodies.EmbeddingInput(
19 | model: model,
20 | content: content
21 | )
22 |
23 | let response = try await run(\.generateEmbedding, with: input)
24 |
25 | return response.embedding.values
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/_Gemini.Client+FunctionCalling.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.Client+FunctionCalling.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/13/24.
6 | //
7 |
8 | extension _Gemini.Client {
9 | public func generateContentWithFunctions(
10 | messages: [_Gemini.Message],
11 | functions: [_Gemini.FunctionDefinition],
12 | model: _Gemini.Model,
13 | functionConfig: _Gemini.FunctionCallingConfiguration = .init(mode: .auto)
14 | ) async throws -> _Gemini.Content {
15 | let contents = messages.filter { $0.role != .system }.map { message in
16 | _Gemini.APISpecification.RequestBodies.Content(
17 | role: message.role.rawValue,
18 | parts: [.text(message.content)]
19 | )
20 | }
21 |
22 | let systemInstruction = messages.first { $0.role == .system }.map { message in
23 | _Gemini.APISpecification.RequestBodies.Content(
24 | role: message.role.rawValue,
25 | parts: [.text(message.content)]
26 | )
27 | }
28 |
29 | let tool = _Gemini.Tool(functionDeclarations: functions)
30 | let input = _Gemini.APISpecification.RequestBodies.GenerateContentInput(
31 | model: model,
32 | requestBody: .init(
33 | contents: contents,
34 | tools: [tool],
35 | toolConfiguration: _Gemini.ToolConfiguration(functionCallingConfig: functionConfig),
36 | systemInstruction: systemInstruction
37 | )
38 | )
39 |
40 | let response = try await run(\.generateContent, with: input)
41 |
42 | return try _Gemini.Content(apiResponse: response)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/_Gemini.Client+Grounding.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _Gemini.Client+Grounding.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/13/24.
6 | //
7 |
8 | extension _Gemini.Client {
9 | public func generateContentWithGrounding(
10 | messages: [_Gemini.Message],
11 | model: _Gemini.Model,
12 | dynamicThreshold: Double = 0.3
13 | ) async throws -> _Gemini.Content {
14 | let contents = messages.filter { $0.role != .system }.map { message in
15 | _Gemini.APISpecification.RequestBodies.Content(
16 | role: message.role.rawValue,
17 | parts: [.text(message.content)]
18 | )
19 | }
20 |
21 | let systemInstruction = messages.first { $0.role == .system }.map { message in
22 | _Gemini.APISpecification.RequestBodies.Content(
23 | role: message.role.rawValue,
24 | parts: [.text(message.content)]
25 | )
26 | }
27 |
28 | let tool = _Gemini.Tool(
29 | googleSearchRetrieval: .init(
30 | dynamicRetrievalConfiguration: .init(
31 | mode: "MODE_DYNAMIC",
32 | dynamicThreshold: dynamicThreshold
33 | )
34 | )
35 | )
36 |
37 | let input = _Gemini.APISpecification.RequestBodies.GenerateContentInput(
38 | model: model,
39 | requestBody: .init(
40 | contents: contents,
41 | tools: [tool],
42 | toolConfiguration: nil,
43 | systemInstruction: systemInstruction
44 | )
45 | )
46 |
47 | let response = try await run(\.generateContent, with: input)
48 |
49 | return try _Gemini.Content(apiResponse: response)
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Sources/_Gemini/Intramodular/_Gemini.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 |
7 | public enum _Gemini {
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Sources/_Gemini/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | @_exported import CoreMI
6 | @_exported import LargeLanguageModels
7 |
--------------------------------------------------------------------------------
/Tests/Anthropic/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Anthropic
6 | import LargeLanguageModels
7 | import XCTest
8 |
9 | public var ANTHROPIC_API_KEY: String {
10 | ""
11 | }
12 |
13 | public var client: Anthropic.Client {
14 | Anthropic.Client(apiKey: ANTHROPIC_API_KEY)
15 | }
16 |
--------------------------------------------------------------------------------
/Tests/Cohere/Intramodular/EmbeddingsTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Cohere
7 | import XCTest
8 |
9 | final class EmbeddingsTests: XCTestCase {
10 |
11 | func testTextEmbeddings() async {
12 | let textInput = ["Cat", "Dog"]
13 | do {
14 | let embeddings = try await client.createEmbeddings(
15 | for: .embedEnglishV2,
16 | texts: textInput,
17 | inputType: .classification,
18 | embeddingTypes: nil,
19 | truncate: nil
20 | )
21 |
22 | let embeddingsData = embeddings.embeddings
23 | XCTAssertTrue(!embeddingsData.isEmpty)
24 | } catch {
25 | print(error)
26 | XCTFail(error.localizedDescription)
27 | }
28 | }
29 |
30 | func testTextEmbeddingsRequestHandling() async {
31 | let embeddingsClient: any TextEmbeddingsRequestHandling = client
32 |
33 | let textInput = ["Cat", "Dog"]
34 | let request = TextEmbeddingsRequest(
35 | input: textInput,
36 | model: Cohere.Model.embedEnglishV2.__conversion()
37 | )
38 |
39 | do {
40 | let embeddings = try await embeddingsClient.fulfill(request)
41 | let embeddingsData = embeddings.data
42 | XCTAssertTrue(!embeddingsData.isEmpty)
43 | } catch {
44 | print(error)
45 | XCTFail(error.localizedDescription)
46 | }
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Tests/Cohere/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Cohere
6 |
7 | public var COHERE_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: Cohere.Client {
12 | Cohere.Client(apiKey: COHERE_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/ElevenLabs/Instramodular/SpeechTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import ElevenLabs
6 | import XCTest
7 |
8 | final class SpeechTests: XCTestCase {
9 |
10 | func testCreateSpeech() async throws {
11 |
12 | let text = "In a quiet, unassuming village nestled deep in a lush, verdant valley, young Elara leads a simple life, dreaming of adventure beyond the horizon. Her village is filled with ancient folklore and tales of mystical relics, but none capture her imagination like the legend of the Enchanted Amulet—a powerful artifact said to grant its bearer the ability to control time."
13 |
14 | let voiceID = "4v7HtLWqY9rpQ7Cg2GT4"
15 |
16 | let voiceSettings: ElevenLabs.VoiceSettings = .init(
17 | stability: 0.5,
18 | similarityBoost: 0.75,
19 | styleExaggeration: 0,
20 | speakerBoost: true)
21 |
22 | let model = ElevenLabs.Model.EnglishV1
23 |
24 | let speechData = try await client.speech(
25 | for: text,
26 | voiceID: voiceID,
27 | voiceSettings: voiceSettings,
28 | model: model
29 | )
30 |
31 | XCTAssertFalse(speechData.isEmpty, "speechData should not be empty")
32 |
33 | _ = speechData
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Tests/ElevenLabs/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import ElevenLabs
6 |
7 | public var ELEVENLABS_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: ElevenLabs.Client {
12 | let client = ElevenLabs.Client(apiKey: ELEVENLABS_API_KEY)
13 |
14 | return client
15 | }
16 |
--------------------------------------------------------------------------------
/Tests/Groq/Intramodular/CompletionTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Groq
7 | import XCTest
8 |
9 | final class CompletionTests: XCTestCase {
10 |
11 | let llm: any LLMRequestHandling = client
12 |
13 | func testChatCompletionsMixtral8x7b() async throws {
14 | let result = try await resultForModel(Groq.Model.mixtral_8x7b)
15 | print(result) // "Hello! How can I assist you today?"
16 | }
17 |
18 | func testChatCompletionsGemma7b() async throws {
19 | let result = try await resultForModel(Groq.Model.gemma_7b)
20 | print(result) // "Hello! How can I assist you today?"
21 | }
22 |
23 | func testChatCompletionsLlama3_70b() async throws {
24 | let result = try await resultForModel(Groq.Model.llama3_70b)
25 | print(result) // "Hello! How can I assist you today?"
26 | }
27 |
28 | func testChatCompletionsLlama3_8b() async throws {
29 | let result = try await resultForModel(Groq.Model.llama3_8b)
30 | print(result) // "Hello! How can I assist you today?"
31 | }
32 |
33 | private func resultForModel(_ model: Groq.Model) async throws -> String {
34 |
35 | let messages: [AbstractLLM.ChatMessage] = [
36 | AbstractLLM.ChatMessage(
37 | role: .system,
38 | body: "You are an extremely intelligent assistant."
39 | ),
40 | AbstractLLM.ChatMessage(
41 | role: .user,
42 | body: "Sup?"
43 | )
44 | ]
45 |
46 | let result: String = try await llm.complete(
47 | messages,
48 | model: model,
49 | as: String.self
50 | )
51 |
52 | return result
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Tests/Groq/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Groq
6 |
7 | public var GROQ_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: Groq.Client {
12 | Groq.Client(apiKey: GROQ_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Batch.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Batch.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientBatchTests: XCTestCase {
12 | func testStartInferenceJob() async throws {
13 | let job = try await client.startInferenceJob(
14 | urls: [URL(string: "https://hume-tutorials.s3.amazonaws.com/faces.zip")!],
15 | models: .burst()
16 | )
17 | XCTAssertNotNil(job)
18 | }
19 |
20 | func testGetJobDetails() async throws {
21 | let job = try await client.getJobDetails(id: "424ddd20-b604-435b-abb0-712f1fe9303b")
22 | XCTAssertNotNil(job)
23 | }
24 |
25 | func testListJobs() async throws {
26 | let jobs = try await client.listJobs()
27 | XCTAssertNotNil(jobs)
28 | }
29 |
30 | func testGetJobPredictions() async throws {
31 | let predictions = try await client.getJobPredictions(id: "424ddd20-b604-435b-abb0-712f1fe9303b")
32 | XCTAssertNotNil(predictions)
33 | }
34 |
35 | func testGetJobArtifacts() async throws {
36 | //Get the artifacts ZIP of a completed inference job.
37 |
38 | print("Needs Implementation")
39 | XCTFail("Not implemented")
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Chat.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Chat.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientChatTests: XCTestCase {
12 |
13 | func testListChats() async throws {
14 | let chats = try await client.listChats()
15 | XCTAssertNotNil(chats)
16 | }
17 |
18 | func testListChatEvents() async throws {
19 | let events = try await client.listChatEvents(chatId: "test-id")
20 | XCTAssertNotNil(events)
21 | }
22 |
23 | func testGetChatAudio() async throws {
24 | let audio = try await client.getChatAudio(chatId: "test-id")
25 | XCTAssertNotNil(audio)
26 | }
27 |
28 | func testChat() async throws {
29 | let response = try await client.chat(
30 | messages: [.init(
31 | role: "user",
32 | content: "Hello"
33 | )],
34 | model: "test-model"
35 | )
36 | XCTAssertNotNil(response)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/ChatGroup.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ChatGroup.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientChatGroupTests: XCTestCase {
12 |
13 | func testListChatGroups() async throws {
14 | let groups = try await client.listChatGroups()
15 | XCTAssertNotNil(groups)
16 | }
17 |
18 | func testGetChatGroup() async throws {
19 | let group = try await client.getChatGroup(id: "test-id")
20 | XCTAssertNotNil(group)
21 | }
22 |
23 | func testListChatGroupEvents() async throws {
24 | print("Needs Implementation")
25 | XCTFail("Not implemented")
26 | }
27 |
28 | func testGetChatGroupAudio() async throws {
29 | print("Needs Implementation")
30 | XCTFail("Not implemented")
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Config.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Config.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientConfigTests: XCTestCase {
12 |
13 | func testListConfigs() async throws {
14 | let configs = try await client.listConfigs()
15 | XCTAssertNotNil(configs)
16 | }
17 |
18 | func testCreateConfig() async throws {
19 | let config = try await client.createConfig(name: "Test Config", description: "Test Description", settings: ["key": "value"])
20 | XCTAssertEqual(config.name, "Test Config")
21 | }
22 |
23 | func testDeleteConfig() async throws {
24 | try await client.deleteConfig(id: "test-id")
25 | }
26 |
27 | func testListConfigVersions() async throws {
28 | print("Needs Implementation")
29 | XCTFail("Not implemented")
30 | }
31 |
32 | func testCreateConfigVersion() async throws {
33 | print("Needs Implementation")
34 | XCTFail("Not implemented")
35 | }
36 |
37 | func testGetConfigVersion() async throws {
38 | print("Needs Implementation")
39 | XCTFail("Not implemented")
40 | }
41 |
42 | func testDeleteConfigVersion() async throws {
43 | print("Needs Implementation")
44 | XCTFail("Not implemented")
45 | }
46 |
47 | func testUpdateConfigName() async throws {
48 | print("Needs Implementation")
49 | XCTFail("Not implemented")
50 | }
51 |
52 | func testUpdateConfigDescription() async throws {
53 | print("Needs Implementation")
54 | XCTFail("Not implemented")
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Dataset.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Dataset.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientDatasetTests: XCTestCase {
12 |
13 | func testListDatasets() async throws {
14 | let datasets = try await client.listDatasets()
15 | XCTAssertNotNil(datasets)
16 | }
17 |
18 | func testCreateDataset() async throws {
19 | let dataset = try await client.createDataset(name: "Test Dataset", description: "Test Description", fileIds: ["test-id"])
20 | XCTAssertNotNil(dataset)
21 | }
22 |
23 | func testDeleteDataset() async throws {
24 | try await client.deleteDataset(id: "test-id")
25 | }
26 |
27 | func testGetDataset() async throws {
28 | print("Needs Implementation")
29 | XCTFail("Not implemented")
30 | }
31 |
32 | func testCreateDatasetVersion() async throws {
33 | print("Needs Implementation")
34 | XCTFail("Not implemented")
35 | }
36 |
37 | func testListDatasetVersions() async throws {
38 | print("Needs Implementation")
39 | XCTFail("Not implemented")
40 | }
41 |
42 | func testListDatasetFiles() async throws {
43 | print("Needs Implementation")
44 | XCTFail("Not implemented")
45 | }
46 |
47 | func testGetDatasetVersion() async throws {
48 | print("Needs Implementation")
49 | XCTFail("Not implemented")
50 | }
51 |
52 | func testListDatasetVersionFiles() async throws {
53 | print("Needs Implementation")
54 | XCTFail("Not implemented")
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/File.swift:
--------------------------------------------------------------------------------
1 | //
2 | // File.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientFileTests: XCTestCase {
12 |
13 | func testListFiles() async throws {
14 | let files = try await client.listFiles()
15 | XCTAssertNotNil(files)
16 | }
17 |
18 | func testUploadFile() async throws {
19 | let file = try await client.uploadFile(data: Data(), name: "test.txt")
20 | XCTAssertNotNil(file)
21 | }
22 |
23 | func testDeleteFile() async throws {
24 | try await client.deleteFile(id: "test-id")
25 | }
26 |
27 | func testGetFile() async throws {
28 | print("Needs Implementation")
29 | XCTFail("Not implemented")
30 | }
31 |
32 | func testUpdateFileName() async throws {
33 | print("Needs Implementation")
34 | XCTFail("Not implemented")
35 | }
36 |
37 | func testGetFilePredictions() async throws {
38 | print("Needs Implementation")
39 | XCTFail("Not implemented")
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Model.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Model.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientModelTests: XCTestCase {
12 |
13 | func testListModels() async throws {
14 | let models = try await client.listModels()
15 | XCTAssertNotNil(models)
16 |
17 | if let model = models.first {
18 | XCTAssertNotNil(model.id)
19 | XCTAssertNotNil(model.name)
20 | XCTAssertNotNil(model.latestVersion)
21 | }
22 | }
23 |
24 | func testGetModel() async throws {
25 | let model = try await client.getModel(id: "test-id")
26 | XCTAssertNotNil(model)
27 | XCTAssertNotNil(model.latestVersion)
28 | }
29 |
30 | func testUpdateModelName() async throws {
31 | let model = try await client.updateModelName(
32 | id: "test-id",
33 | name: "Updated Name"
34 | )
35 | }
36 |
37 | func testListModelVersions() async throws {
38 | let versions = try await client.listModelVersions(id: "test-id")
39 | XCTAssertNotNil(versions)
40 |
41 | if let version = versions.first {
42 | XCTAssertNotNil(version.id)
43 | XCTAssertNotNil(version.modelId)
44 | XCTAssertNotNil(version.version)
45 | }
46 | }
47 |
48 | func testGetModelVersion() async throws {
49 | let version = try await client.getModelVersion(
50 | id: "test-id",
51 | version: 1
52 | )
53 | XCTAssertNotNil(version)
54 | XCTAssertNotNil(version.modelId)
55 | }
56 |
57 | func testUpdateModelDescription() async throws {
58 | let version = try await client.updateModelDescription(
59 | id: "test-id",
60 | versionId: "version-id",
61 | description: "Updated Description"
62 | )
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Tests/HumeAI/Intramodular/Stream.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Stream.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/25/24.
6 | //
7 |
8 | import XCTest
9 | @testable import HumeAI
10 |
11 | final class HumeAIClientStreamTests: XCTestCase {
12 |
13 | func testStreamInference() async throws {
14 | let job = try await client.streamInference(
15 | id: "test-id",
16 | file: Data(),
17 | models: [.language()]
18 | )
19 | XCTAssertNotNil(job)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Tests/HumeAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import HumeAI
9 |
10 | let HUMEAI_API_KEY = ""
11 |
12 | var client = HumeAI.Client(
13 | apiKey: HUMEAI_API_KEY
14 | )
15 |
--------------------------------------------------------------------------------
/Tests/Jina/Intramodular/EmbeddingsTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Jina
7 | import XCTest
8 |
9 | final class EmbeddingsTests: XCTestCase {
10 |
11 | func testTextEmbeddings() async {
12 | let textInput = ["Hello", "World"]
13 | do {
14 | let embeddings = try await client.createEmbeddings(
15 | for: .embeddingsV2BaseEn,
16 | input: textInput,
17 | encodingFormat: nil
18 | )
19 |
20 | let embeddingsData = embeddings.data
21 | XCTAssertTrue(!embeddingsData.isEmpty)
22 | XCTAssertTrue(embeddingsData.first!.object == "embedding")
23 | } catch {
24 | print(error)
25 | XCTFail(error.localizedDescription)
26 | }
27 | }
28 |
29 | func testTextEmbeddingsRequestHandling() async {
30 | let embeddingsClient: any TextEmbeddingsRequestHandling = client
31 |
32 | let textInput = ["Hello", "World"]
33 | let request = TextEmbeddingsRequest(
34 | input: textInput,
35 | model: Jina.Model.embeddingsV2SmallEn.__conversion()
36 | )
37 |
38 | do {
39 | let embeddings = try await embeddingsClient.fulfill(request)
40 | let embeddingsData = embeddings.data
41 | XCTAssertTrue(!embeddingsData.isEmpty)
42 | } catch {
43 | print(error)
44 | XCTFail(error.localizedDescription)
45 | }
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Tests/Jina/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Jina
6 |
7 | public var JINA_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: Jina.Client {
12 | Jina.Client(apiKey: JINA_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/LargeLanguageModels/Intramodular/PromptLiteralTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import XCTest
8 |
9 | final class PromptLiteralTests: XCTestCase {
10 | func testEncoding() throws {
11 | let literal = PromptLiteral("Hello, World!")
12 | let encoder = JSONEncoder()
13 |
14 | XCTAssertNoThrow(try encoder.encode(literal))
15 | }
16 |
17 | func testContextEncoding() throws {
18 | var literal = PromptLiteral("Hello, World!")
19 |
20 | literal.stringInterpolation._sharedContext.role = .allowed([.chat(.assistant)])
21 |
22 | let coder = HadeanTopLevelCoder(coder: .json)
23 |
24 | XCTAssertNoThrow(try coder.encode(literal))
25 |
26 | let data = try coder.encode(literal)
27 | let decoded = try coder.decode(PromptLiteral.self, from: data)
28 |
29 | XCTAssert(literal == decoded)
30 | }
31 |
32 | func testConcatenation() throws {
33 | let lhs = PromptLiteral("Hello, ")
34 | let rhs = PromptLiteral("World!")
35 |
36 | XCTAssert((lhs + rhs) == PromptLiteral("Hello, World!"))
37 |
38 | let threeHellos = PromptLiteral.concatenate(separator: " ") {
39 | lhs
40 | lhs
41 | lhs
42 | }
43 |
44 | XCTAssert(threeHellos == PromptLiteral("Hello, Hello, Hello, "))
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Tests/LargeLanguageModels/main.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Swallow
7 | import XCTest
8 |
9 | final class LargeLanguageModelsTests: XCTestCase {
10 |
11 | }
12 |
13 | var openAIKey: String {
14 | fatalError(.unimplemented)
15 | }
16 |
--------------------------------------------------------------------------------
/Tests/Mistral/Intramodular/EmbeddingsTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import Groq
7 | import XCTest
8 | import Mistral
9 |
10 | final class EmbeddingsTests: XCTestCase {
11 |
12 | func testTextEmbeddings() async {
13 | let textInput = ["Hello", "World"]
14 | do {
15 | let embeddings = try await client.createEmbeddings(for: textInput)
16 | let embeddingsData = embeddings.data
17 | XCTAssertTrue(!embeddingsData.isEmpty)
18 | XCTAssertTrue(embeddingsData.first!.object == "embedding")
19 | } catch {
20 | print(error)
21 | XCTFail(error.localizedDescription)
22 | }
23 | }
24 |
25 | func testTextEmbeddingsRequestHandling() async {
26 | let embeddingsClient: any TextEmbeddingsRequestHandling = client
27 |
28 | let textInput = ["Hello", "World"]
29 | let request = TextEmbeddingsRequest(
30 | input: textInput,
31 | model: Mistral.Model.mistral_embed.__conversion()
32 | )
33 |
34 | do {
35 | let embeddings = try await embeddingsClient.fulfill(request)
36 | let embeddingsData = embeddings.data
37 | XCTAssertTrue(!embeddingsData.isEmpty)
38 | } catch {
39 | print(error)
40 | XCTFail(error.localizedDescription)
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Tests/Mistral/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Mistral
6 |
7 | public var MISTRAL_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: Mistral.Client {
12 | Mistral.Client(apiKey: MISTRAL_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/NeetsAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/22/24.
6 | //
7 |
8 | import NeetsAI
9 |
10 | public var NEETSAI_API_KEY: String {
11 | ""
12 | }
13 |
14 | public var client: NeetsAI.Client {
15 | let client = NeetsAI.Client(
16 | apiKey: NEETSAI_API_KEY
17 | )
18 |
19 | return client
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/Tests/OpenAI/Intramodular/DALL_E_Tests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import OpenAI
6 | import XCTest
7 |
8 | final class DalleTests: XCTestCase {
9 | func testGeneratingOneImage() async throws {
10 | let result = try await client.createImage(
11 | prompt: "a kitten playing with yarn"
12 | )
13 |
14 | _ = result
15 | }
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/Tests/OpenAI/Intramodular/TranscriptionTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import CorePersistence
6 | import LargeLanguageModels
7 | import NetworkKit
8 | import OpenAI
9 | import XCTest
10 |
11 | final class TranscriptionTests: XCTestCase {
12 | @MainActor
13 | func testTranscription() async throws {
14 | let transcription = try await client.createTranscription(
15 | audioFile: "https://replicate.delivery/mgxm/e5159b1b-508a-4be4-b892-e1eb47850bdc/OSR_uk_000_0050_8k.wav",
16 | prompt: nil,
17 | model: .whisper_1,
18 | timestampGranularities: [.word]
19 | )
20 |
21 | print(transcription.text)
22 | print(transcription.words)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Tests/OpenAI/Intramodular/VectorStoreTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // File.swift
3 | //
4 | //
5 | // Created by Natasha Murashev on 5/16/24.
6 | //
7 |
8 | import OpenAI
9 | import XCTest
10 |
11 | final class VectorStoreTests: XCTestCase {
12 | func test1CreateVectorStore() async throws {
13 | let result = try await client.createVectorStore(name: nil, fileIDs: nil)
14 |
15 | _ = result
16 | }
17 |
18 | func test2ListVectorStore() async throws {
19 | let result = try await client.listVectorStores()
20 |
21 | _ = result
22 | }
23 |
24 | func test3GetVectorStore() async throws {
25 | let vectorStores = try await client.listVectorStores()
26 | let vectorStoreID = try vectorStores.firstID.unwrap()
27 |
28 | let result = try await client.getVectorStore(vectorStoreID: vectorStoreID)
29 |
30 | _ = result
31 | }
32 |
33 | func test4UpdateVectorStore() async throws {
34 | let vectorStores = try await client.listVectorStores()
35 | let vectorStoreID = try vectorStores.firstID.unwrap()
36 | let newName = "myUpdatedVectorStore"
37 |
38 | let result = try await client.updateVectorStore(
39 | vectorStoreID: vectorStoreID,
40 | name: newName,
41 | expiresAfter: nil,
42 | metadata: ["key" : "value"])
43 |
44 | _ = result
45 | }
46 |
47 | func test5DeleteVectorStore() async throws {
48 | let vectorStores = try await client.listVectorStores()
49 | let vectorStoreID = vectorStores.firstID!
50 |
51 | let result = try await client.deleteVectorStore(vectorStoreID: vectorStoreID)
52 |
53 | _ = result
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Tests/OpenAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import OpenAI
6 |
7 | public var client: OpenAI.Client {
8 | let client = OpenAI.Client(apiKey: nil)
9 |
10 | return client
11 | }
12 |
--------------------------------------------------------------------------------
/Tests/Perplexity/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import Perplexity
6 |
7 | public var PERPLEXITY_API_KEY: String {
8 | "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"
9 | }
10 |
11 | public var client: Perplexity.Client {
12 | Perplexity.Client(apiKey: PERPLEXITY_API_KEY)
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/Tests/PlayHT/Intramodular/SpeechTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SpeechTests.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 11/20/24.
6 | //
7 |
8 | import PlayHT
9 | import XCTest
10 |
11 | final class PlayHTTests: XCTestCase {
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/PlayHT/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import PlayHT
6 |
7 | public var PLAYHT_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var PLAYHT_USER_ID: String {
12 | ""
13 | }
14 |
15 | public var client: PlayHT.Client {
16 | let client = PlayHT.Client(
17 | apiKey: PLAYHT_API_KEY,
18 | userID: PLAYHT_USER_ID
19 | )
20 |
21 | return client
22 | }
23 |
--------------------------------------------------------------------------------
/Tests/TogetherAI/Intramodular/EmbeddingsTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import VoyageAI
7 | import XCTest
8 |
9 | final class EmbeddingsTests: XCTestCase {
10 |
11 | func testTextEmbeddings() async {
12 | let textInput = "Our solar system orbits the Milky Way galaxy at about 515,000 mph"
13 | do {
14 | let embeddings = try await client.createEmbeddings(
15 | for: .togetherM2Bert80M2KRetrieval,
16 | input: textInput
17 | )
18 |
19 | let embeddingsData = embeddings.data
20 | XCTAssertTrue(!embeddingsData.isEmpty)
21 | XCTAssertTrue(embeddingsData.first!.object == "embedding")
22 | } catch {
23 | print(error)
24 | XCTFail(error.localizedDescription)
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Tests/TogetherAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import TogetherAI
6 |
7 | public var TOGETHERAI_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: TogetherAI.Client {
12 | TogetherAI.Client(apiKey: TOGETHERAI_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/VoyageAI/Intramodular/EmbeddingsTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import LargeLanguageModels
6 | import VoyageAI
7 | import XCTest
8 |
9 | final class EmbeddingsTests: XCTestCase {
10 |
11 | func testTextEmbeddings() async {
12 | let textInput = ["Cat", "Dog"]
13 | do {
14 | let embeddings = try await client.createEmbeddings(
15 | for: .voyageLarge2,
16 | input: textInput
17 | )
18 |
19 | let embeddingsData = embeddings.data
20 | XCTAssertTrue(!embeddingsData.isEmpty)
21 | XCTAssertTrue(embeddingsData.first!.object == "embedding")
22 | } catch {
23 | print(error)
24 | XCTFail(error.localizedDescription)
25 | }
26 | }
27 |
28 | func testTextEmbeddingsRequestHandling() async {
29 | let embeddingsClient: any TextEmbeddingsRequestHandling = client
30 |
31 | let textInput = ["Cat", "Dog"]
32 | let request = TextEmbeddingsRequest(
33 | input: textInput,
34 | model: VoyageAI.Model.voyage2.__conversion()
35 | )
36 |
37 | do {
38 | let embeddings = try await embeddingsClient.fulfill(request)
39 | let embeddingsData = embeddings.data
40 | XCTAssertTrue(!embeddingsData.isEmpty)
41 | } catch {
42 | print(error)
43 | XCTFail(error.localizedDescription)
44 | }
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/Tests/VoyageAI/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Vatsal Manot
3 | //
4 |
5 | import VoyageAI
6 |
7 | public var VOYAGEAI_API_KEY: String {
8 | ""
9 | }
10 |
11 | public var client: VoyageAI.Client {
12 | VoyageAI.Client(apiKey: VOYAGEAI_API_KEY)
13 | }
14 |
--------------------------------------------------------------------------------
/Tests/_Gemini/Intramodular/_GeminiTests+Embeddings.swift:
--------------------------------------------------------------------------------
1 | //
2 | // _GeminiTests+Embeddings.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/18/24.
6 | //
7 |
8 | import Testing
9 | import Foundation
10 | import _Gemini
11 | import AI
12 |
13 | @Suite struct _GeminiEmbeddingTests {
14 | @Test func testGenerateEmbedding() async throws {
15 | let text = "What is the meaning of life?"
16 |
17 | let embedding = try await client.generateEmbedding(text: text)
18 |
19 | // Basic validation checks
20 | #expect(!embedding.isEmpty, "Embedding should not be empty")
21 | #expect(embedding.count > 0, "Embedding should have multiple dimensions")
22 |
23 | // Validate embedding values are within expected range
24 | for value in embedding {
25 | #expect(value >= -1.0 && value <= 1.0, "Embedding values should be normalized between -1 and 1")
26 | }
27 |
28 | // Print some basic statistics
29 | let sum = embedding.reduce(0, +)
30 | let average = sum / Double(embedding.count)
31 | print("Embedding statistics:")
32 | print("- Dimensions:", embedding.count)
33 | print("- Average value:", average)
34 | print("- First few values:", Array(embedding.prefix(5)))
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Tests/_Gemini/module.swift:
--------------------------------------------------------------------------------
1 | //
2 | // module.swift
3 | // AI
4 | //
5 | // Created by Jared Davidson on 12/11/24.
6 | //
7 |
8 | import AI
9 | @testable import _Gemini
10 |
11 | public var GEMINI_API_KEY: String {
12 | // Add your API key here or load from environment
13 | ""
14 | }
15 |
16 | public var client: _Gemini.Client {
17 | _Gemini.Client(apiKey: GEMINI_API_KEY)
18 | }
19 |
--------------------------------------------------------------------------------