-
Notifications
You must be signed in to change notification settings - Fork 309
test(samples/js): add Responses web service sample and integration coverage #671
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
Open
MaanavD
wants to merge
11
commits into
main
Choose a base branch
from
agents/update-responses-api-sdk-vision-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
e1ad530
feat(sdk/js): add vision support, list(), and missing types to Respon…
MaanavD e831369
fix(sdk/js): address PR review comments
MaanavD e092c2b
fix(sdk/js): address second round of PR review comments
MaanavD 6cb68ba
Merge remote-tracking branch 'origin/main' into agents/update-respons…
MaanavD 88f0a0d
fix(sdk/js): address latest responses API review feedback
MaanavD a707ee4
feat(sdk/js): add responses FFI fallback
MaanavD edf1db7
refactor(sdk/js): focus responses PR on web service usage
MaanavD aba3b03
test(sdk/js): use external responses web service
MaanavD 092d4c4
fix(samples/js): use FoundryLocalManager for setup; OpenAI SDK for re…
MaanavD 719d25f
fix: use baseUrl in responsesWebService integration test fetch calls
MaanavD 785399f
docs: add Responses web service sample README
MaanavD 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
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 |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| // ------------------------------------------------------------------------- | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
| // ------------------------------------------------------------------------- | ||
|
|
||
| import * as path from 'path'; | ||
| import { promises as fsPromises } from 'fs'; | ||
| import type { InputImageContent } from '../types.js'; | ||
|
|
||
| const MEDIA_TYPE_MAP: Record<string, string> = { | ||
| '.png': 'image/png', | ||
|
apsonawane marked this conversation as resolved.
Outdated
|
||
| '.jpg': 'image/jpeg', | ||
| '.jpeg': 'image/jpeg', | ||
| '.gif': 'image/gif', | ||
| '.webp': 'image/webp', | ||
| '.bmp': 'image/bmp', | ||
| }; | ||
|
|
||
| /** | ||
| * Options for `createImageContentFromFile`. | ||
| */ | ||
| export interface ImageContentOptions { | ||
| /** Detail level hint for the model. */ | ||
| detail?: 'low' | 'high' | 'auto'; | ||
| /** | ||
| * If set, the longest dimension of the image will be scaled down to this value | ||
| * (preserving aspect ratio) before encoding. Must be a finite positive integer. | ||
| * Requires the `sharp` package to be installed as an optional peer dependency | ||
| * (`npm install sharp`). If `sharp` is not available, a warning is printed and | ||
| * the original image is used unresized. | ||
| */ | ||
| maxDimension?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Creates an `InputImageContent` part by reading an image file from disk. | ||
| * The file is base64-encoded and embedded directly in the content part. | ||
| * | ||
| * The second argument accepts either an `ImageContentOptions` object or a shorthand | ||
| * detail string (`'low' | 'high' | 'auto'`) for convenience. | ||
| * | ||
| * @param filePath - Absolute or relative path to the image file. | ||
| * @param options - Optional `ImageContentOptions`, or a shorthand detail string. | ||
| * @returns A `Promise<InputImageContent>` with base64-encoded image data. | ||
| * @throws If the file does not exist, the extension is unsupported, or `maxDimension` | ||
| * is not a finite positive integer. | ||
| */ | ||
| export async function createImageContentFromFile( | ||
| filePath: string, | ||
| options?: ImageContentOptions | 'low' | 'high' | 'auto' | ||
| ): Promise<InputImageContent> { | ||
| // Support the shorthand signature: createImageContentFromFile(path, detail?) | ||
| const opts: ImageContentOptions = typeof options === 'string' | ||
| ? { detail: options } | ||
| : (options ?? {}); | ||
|
|
||
| if (opts.maxDimension !== undefined) { | ||
| if (!Number.isFinite(opts.maxDimension) || !Number.isInteger(opts.maxDimension) || opts.maxDimension <= 0) { | ||
| throw new Error(`Invalid maxDimension: ${opts.maxDimension}. Expected a finite positive integer.`); | ||
| } | ||
| } | ||
|
|
||
| const ext = path.extname(filePath).toLowerCase(); | ||
| const mediaType = MEDIA_TYPE_MAP[ext]; | ||
| if (!mediaType) { | ||
| throw new Error( | ||
| `Unsupported image format: ${ext}. Supported formats: ${Object.keys(MEDIA_TYPE_MAP).join(', ')}` | ||
| ); | ||
| } | ||
|
|
||
| let dataBuffer: Buffer; | ||
| try { | ||
| dataBuffer = await fsPromises.readFile(filePath) as Buffer; | ||
| } catch (err: any) { | ||
| if (err.code === 'ENOENT') { | ||
| throw new Error(`Image file not found: ${filePath}`); | ||
| } | ||
| throw err; | ||
| } | ||
|
|
||
| let finalMediaType = mediaType; | ||
| if (opts.maxDimension !== undefined) { | ||
|
MaanavD marked this conversation as resolved.
Outdated
|
||
| const resized = await resizeImage(dataBuffer, opts.maxDimension, mediaType); | ||
| dataBuffer = resized.buffer; | ||
| finalMediaType = resized.mediaType; | ||
| } | ||
|
|
||
| const content: InputImageContent = { | ||
| type: 'input_image', | ||
| image_data: dataBuffer.toString('base64'), | ||
| media_type: finalMediaType, | ||
| }; | ||
| if (opts.detail !== undefined) { | ||
| content.detail = opts.detail; | ||
| } | ||
| return content; | ||
| } | ||
|
|
||
| /** | ||
| * Creates an `InputImageContent` part from a URL. | ||
| * The server will infer the media type from the URL. | ||
| * | ||
| * @param url - Public URL pointing to the image. | ||
| * @param detail - Optional detail level hint for the model ('low' | 'high' | 'auto'). | ||
| * @returns An `InputImageContent` object with the image URL. | ||
| */ | ||
| export function createImageContentFromUrl(url: string, detail?: 'low' | 'high' | 'auto'): InputImageContent { | ||
| const content: InputImageContent = { | ||
| type: 'input_image', | ||
| image_url: url, | ||
| // media_type intentionally omitted — server infers from URL | ||
| }; | ||
| if (detail !== undefined) { | ||
| content.detail = detail; | ||
| } | ||
| return content; | ||
| } | ||
|
|
||
| /** | ||
| * Attempts to resize image data to fit within `maxDimension` on the longest side. | ||
| * Requires the optional `sharp` peer dependency. Falls back to original data with a | ||
| * warning if `sharp` is not available. | ||
| * Returns both the (possibly resized) buffer and the media type. | ||
| */ | ||
| async function resizeImage(data: Buffer, maxDimension: number, fallbackMediaType: string): Promise<{ buffer: Buffer; mediaType: string }> { | ||
| let sharp: any; | ||
| try { | ||
| // Dynamic import so sharp remains a soft/optional peer dep. | ||
| // eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
| // @ts-ignore — sharp is an optional peer dependency | ||
| sharp = (await import('sharp')).default; | ||
| } catch { | ||
| console.warn( | ||
| `[foundry-local] createImageContentFromFile: maxDimension=${maxDimension} requires the ` + | ||
| `"sharp" package (npm install sharp). Image will be used unresized.` | ||
| ); | ||
| return { buffer: data, mediaType: fallbackMediaType }; | ||
| } | ||
|
|
||
| const metadata = await sharp(data).metadata(); | ||
| const { width = 0, height = 0, format } = metadata; | ||
| // Map sharp format names back to MIME types; fall back to the original type | ||
| const formatToMime: Record<string, string> = { | ||
| png: 'image/png', jpeg: 'image/jpeg', gif: 'image/gif', | ||
| webp: 'image/webp', bmp: 'image/bmp', | ||
| }; | ||
| const mediaType = (format && formatToMime[format]) ?? fallbackMediaType; | ||
|
|
||
| if (Math.max(width, height) <= maxDimension) { | ||
| return { buffer: data, mediaType }; | ||
| } | ||
|
|
||
| const resizedBuffer: Buffer = await sharp(data) | ||
| .resize({ width: maxDimension, height: maxDimension, fit: 'inside', withoutEnlargement: true }) | ||
| .toBuffer(); | ||
|
|
||
| return { buffer: resizedBuffer, mediaType }; | ||
| } | ||
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.