-
Notifications
You must be signed in to change notification settings - Fork 5
Add text and image document support for Ballerina OpenAI model provider #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SasinduDilshara
merged 22 commits into
ballerina-platform:main
from
SasinduDilshara:add-image-documents
Jul 26, 2025
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
8ff53fd
[Automated] Update the toml files
SasinduDilshara 94757fc
[Automated] Update the toml files
SasinduDilshara a8e2ae3
Add image content support for openai
SasinduDilshara 27eddfd
Update chat creation method to reduce tokens
SasinduDilshara f947fe7
[Automated] Update the toml files
SasinduDilshara ee07402
Remove file content part temporary
SasinduDilshara cf8c19e
Merge branch 'main' of https://github.com/ballerina-platform/module-b…
SasinduDilshara 1807dbd
[Automated] Update the toml files
SasinduDilshara 9fdb083
[Automated] Update the toml files
SasinduDilshara 524f08a
[Automated] Update the toml files
SasinduDilshara ef0c78e
[Automated] Update the toml files
SasinduDilshara e06cadf
[Automated] Update the toml files
SasinduDilshara 49ac72f
[Automated] Update the toml files
SasinduDilshara 74c0687
[Automated] Update the toml files
SasinduDilshara 108b757
[Automated] Update the toml files
SasinduDilshara 5a47e1d
[Automated] Update the toml files
SasinduDilshara 16f235b
Add image document support
SasinduDilshara cbcbfbd
Refactor provider utils
SasinduDilshara 5e4d812
Update comments in test service
SasinduDilshara 29a03c5
Merge branch 'main' of https://github.com/ballerina-platform/module-b…
SasinduDilshara 03a4979
[Automated] Update the toml files
SasinduDilshara 03c7523
Update test utils file
SasinduDilshara File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||
|---|---|---|---|---|
|
|
@@ -15,13 +15,20 @@ | |||
| // under the License. | ||||
|
|
||||
| import ballerina/ai; | ||||
| import ballerina/constraint; | ||||
| import ballerina/lang.array; | ||||
| import ballerinax/openai.chat; | ||||
|
|
||||
| type ResponseSchema record {| | ||||
| map<json> schema; | ||||
| boolean isOriginallyJsonObject = true; | ||||
| |}; | ||||
|
|
||||
| type DocumentContentPart TextContentPart|ImageContentPart; | ||||
|
|
||||
| type TextContentPart chat:ChatCompletionRequestMessageContentPartText; | ||||
| type ImageContentPart chat:ChatCompletionRequestMessageContentPartImage; | ||||
|
|
||||
| const JSON_CONVERSION_ERROR = "FromJsonStringError"; | ||||
| const CONVERSION_ERROR = "ConversionError"; | ||||
| const ERROR_MESSAGE = "Error occurred while attempting to parse the response from the " + | ||||
|
|
@@ -95,34 +102,95 @@ isolated function getGetResultsTool(map<json> parameters) returns chat:ChatCompl | |||
| } | ||||
| ]; | ||||
|
|
||||
| isolated function generateChatCreationContent(ai:Prompt prompt) returns string|ai:Error { | ||||
| isolated function generateChatCreationContent(ai:Prompt prompt) | ||||
| returns DocumentContentPart[]|ai:Error { | ||||
| string[] & readonly strings = prompt.strings; | ||||
| anydata[] insertions = prompt.insertions; | ||||
| string promptStr = strings[0]; | ||||
| DocumentContentPart[] contentParts = []; | ||||
| string accumulatedTextContent = ""; | ||||
|
|
||||
| if strings.length() > 0 { | ||||
| accumulatedTextContent += strings[0]; | ||||
| } | ||||
|
|
||||
| foreach int i in 0 ..< insertions.length() { | ||||
| string str = strings[i + 1]; | ||||
| anydata insertion = insertions[i]; | ||||
| string str = strings[i + 1]; | ||||
|
|
||||
| if insertion is ai:TextDocument { | ||||
| promptStr += insertion.content + " " + str; | ||||
| continue; | ||||
| if insertion is ai:Document { | ||||
| addTextContentPart(buildTextContentPart(accumulatedTextContent), contentParts); | ||||
| accumulatedTextContent = ""; | ||||
| check addDocumentContentPart(insertion, contentParts); | ||||
| } else if insertion is ai:Document[] { | ||||
| addTextContentPart(buildTextContentPart(accumulatedTextContent), contentParts); | ||||
| accumulatedTextContent = ""; | ||||
| foreach ai:Document doc in insertion { | ||||
| check addDocumentContentPart(doc, contentParts); | ||||
| } | ||||
| } else { | ||||
| accumulatedTextContent += insertion.toString(); | ||||
| } | ||||
| accumulatedTextContent += str; | ||||
| } | ||||
|
|
||||
| if insertion is ai:TextDocument[] { | ||||
| foreach ai:TextDocument doc in insertion { | ||||
| promptStr += doc.content + " "; | ||||
| } | ||||
| promptStr += str; | ||||
| continue; | ||||
| addTextContentPart(buildTextContentPart(accumulatedTextContent), contentParts); | ||||
| return contentParts; | ||||
| } | ||||
|
|
||||
| isolated function addDocumentContentPart(ai:Document doc, DocumentContentPart[] contentParts) returns ai:Error? { | ||||
| if doc is ai:TextDocument { | ||||
| return addTextContentPart(buildTextContentPart(doc.content), contentParts); | ||||
| } else if doc is ai:ImageDocument { | ||||
| return contentParts.push(check buildImageContentPart(doc)); | ||||
| } | ||||
|
|
||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||
| return error ai:Error("Only text and image documents are supported."); | ||||
| } | ||||
|
|
||||
| isolated function addTextContentPart(TextContentPart? contentPart, DocumentContentPart[] contentParts) { | ||||
| if contentPart is TextContentPart { | ||||
| return contentParts.push(contentPart); | ||||
| } | ||||
| } | ||||
|
|
||||
| isolated function buildTextContentPart(string content) returns TextContentPart? { | ||||
| if content.length() == 0 { | ||||
| return; | ||||
| } | ||||
|
|
||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||
| return { | ||||
| 'type: "text", | ||||
| text: content | ||||
| }; | ||||
| } | ||||
|
|
||||
| isolated function buildImageContentPart(ai:ImageDocument doc) returns ImageContentPart|ai:Error => | ||||
| { | ||||
| 'type: "image_url", | ||||
| image_url: { | ||||
| url: check buildImageUrl(doc.content, doc.metadata?.mimeType) | ||||
| } | ||||
| }; | ||||
|
|
||||
| if insertion is ai:Document { | ||||
| return error ai:Error("Only Text Documents are currently supported."); | ||||
| isolated function buildImageUrl(ai:Url|byte[] content, string? mimeType) returns string|ai:Error { | ||||
| if content is ai:Url { | ||||
| ai:Url|constraint:Error validationRes = constraint:validate(content); | ||||
| if validationRes is error { | ||||
| return error(validationRes.message(), validationRes.cause()); | ||||
| } | ||||
| return content; | ||||
| } | ||||
|
|
||||
| return string `data:${mimeType ?: "image/*"};base64,${check getBase64EncodedString(content)}`; | ||||
| } | ||||
|
|
||||
| promptStr += insertion.toString() + str; | ||||
| isolated function getBase64EncodedString(byte[] content) returns string|ai:Error { | ||||
| string|error binaryContent = array:toBase64(content); | ||||
| if binaryContent is error { | ||||
| return error("Failed to convert byte array to string: " + binaryContent.message() + ", " + | ||||
| binaryContent.detail().toBalString()); | ||||
| } | ||||
| return promptStr.trim(); | ||||
| return binaryContent; | ||||
| } | ||||
|
|
||||
| isolated function handleParseResponseError(error chatResponseError) returns error { | ||||
|
|
@@ -135,7 +203,7 @@ isolated function handleParseResponseError(error chatResponseError) returns erro | |||
|
|
||||
| isolated function generateLlmResponse(chat:Client llmClient, OPEN_AI_MODEL_NAMES modelType, | ||||
| ai:Prompt prompt, typedesc<json> expectedResponseTypedesc) returns anydata|ai:Error { | ||||
| string content = check generateChatCreationContent(prompt); | ||||
| DocumentContentPart[] content = check generateChatCreationContent(prompt); | ||||
| ResponseSchema ResponseSchema = check getExpectedResponseSchema(expectedResponseTypedesc); | ||||
| chat:ChatCompletionTool[]|error tools = getGetResultsTool(ResponseSchema.schema); | ||||
| if tools is error { | ||||
|
|
@@ -157,7 +225,7 @@ isolated function generateLlmResponse(chat:Client llmClient, OPEN_AI_MODEL_NAMES | |||
| chat:CreateChatCompletionResponse|error response = | ||||
| llmClient->/chat/completions.post(request); | ||||
| if response is error { | ||||
| return error("LLM call failed: " + response.message()); | ||||
| return error("LLM call failed: " + response.message(), detail = response.detail(), cause = response.cause()); | ||||
SasinduDilshara marked this conversation as resolved.
Show resolved
Hide resolved
|
||||
| } | ||||
|
|
||||
| chat:CreateChatCompletionResponse_choices[] choices = response.choices; | ||||
|
|
||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.