Skip to content

Commit 09ae642

Browse files
authored
Add resolveResource method to ResourceHost interface with documentation (#1818)
1 parent 0ff18d9 commit 09ae642

7 files changed

Lines changed: 122 additions & 8 deletions

File tree

docs/public/genaiscript.d.ts

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/src/content/docs/reference/scripts/fetch.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ llmstxt:
3636
- Plain text: `await host.fetch("https://...", { convert: "text" })`
3737
3838
39+
The `host.resolveResource` function resolves URLs to downloadable resources.
40+
Example: `const result = await host.resolveResource("https://github.com/user/repo/blob/main/file.txt")`.
41+
Returns an object with `uri` and `files` containing resolved content.
42+
43+
3944
For APIs requiring keys, store them securely using the `secrets` object.
4045
hash: f3a5f552bc57beda0a132687a5130a24709d8d15d6a4f40bc962b717210d1351
4146

@@ -82,6 +87,30 @@ const md = await host.fetch("https://...", { convert: "markdown" })
8287
const md = await host.fetch("https://...", { convert: "text" })
8388
```
8489

90+
## `host.resolveResource`
91+
92+
Use `host.resolveResource` to resolve and download resources from URLs. This function handles various URL schemes and protocols,
93+
and can resolve GitHub blob URLs to raw content, among other transformations.
94+
95+
```ts
96+
const result = await host.resolveResource("https://github.com/microsoft/genaiscript/blob/main/docs/public/images/favicon.png")
97+
if (result) {
98+
console.log(`Resolved URI: ${result.uri}`)
99+
for (const file of result.files) {
100+
console.log(`File: ${file.filename}`)
101+
if (file.content) {
102+
console.log(`Binary content: ${file.content.length} bytes`)
103+
} else if (file.text) {
104+
console.log(`Text content: ${file.text.length} characters`)
105+
}
106+
}
107+
}
108+
```
109+
110+
The function returns an object with:
111+
- `uri`: The resolved URL as a URL object
112+
- `files`: An array of resolved files with their content
113+
85114
## Secrets
86115

87116
If the API you are querying requires an API key, you can use the [secrets](/genaiscript/reference/scripts/secrets) object to store the key.

examples/action/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
|name|description|required|default|
1010
|----|-----------|--------|-------|
1111
| `files` | Files to process, separated by semi columns (;). | false | |
12-
| `debug` | Enable debug logging (https://microsoft.github.io/genaiscript/reference/scripts/logging/). | false | |
12+
| `debug` | Enable [debug logging](https://microsoft.github.io/genaiscript/reference/scripts/logging/). | false | |
1313
| `model_alias` | A YAML-like list of model aliases and model id: `translation: github:openai/gpt-4o` | false | |
1414
| `openai_api_key` | OpenAI API key | false | |
1515
| `openai_api_base` | OpenAI API base URL | false | |
@@ -22,7 +22,7 @@
2222
| `azure_ai_inference_api_endpoint` | Azure Serverless OpenAI endpoint | false | |
2323
| `azure_ai_inference_api_version` | Azure Serverless OpenAI API version | false | |
2424
| `azure_ai_inference_api_credentials` | Azure Serverless OpenAI API credentials type | false | |
25-
| `github_token` | GitHub token with `models: read` permission at least (https://microsoft.github.io/genaiscript/reference/github-actions/#github-models-permissions). | false | |
25+
| `github_token` | GitHub token with [models: read](https://microsoft.github.io/genaiscript/reference/github-actions/#github-models-permissions) permission at least. | false | |
2626

2727
## Outputs
2828

examples/action/action.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ inputs:
66
description: "Files to process, separated by semi columns (;). "
77
required: false
88
debug:
9-
description: Enable debug logging
10-
(https://microsoft.github.io/genaiscript/reference/scripts/logging/).
9+
description: Enable [debug
10+
logging](https://microsoft.github.io/genaiscript/reference/scripts/logging/).
1111
required: false
1212
model_alias:
1313
description: "A YAML-like list of model aliases and model id: `translation:
@@ -51,9 +51,9 @@ inputs:
5151
description: Azure Serverless OpenAI API credentials type
5252
required: false
5353
github_token:
54-
description: "GitHub token with `models: read` permission at least
55-
(https://microsoft.github.io/genaiscript/reference/github-actions/#github\
56-
-models-permissions)."
54+
description: "GitHub token with [models:
55+
read](https://microsoft.github.io/genaiscript/reference/github-actions/#g\
56+
ithub-models-permissions) permission at least."
5757
required: false
5858
outputs:
5959
text:

packages/core/src/promptcontext.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { createCache } from "./cache.js";
3333
import { genaiscriptDebug } from "./debug.js";
3434
import { resolveLanguageModelConfigurations } from "./config.js";
3535
import { deleteUndefinedValues } from "./cleaners.js";
36+
import { tryResolveResource } from "./resources.js";
3637
import type {
3738
ExpansionVariables,
3839
LanguageModelProviderInfo,
@@ -263,6 +264,7 @@ export async function createPromptContext(
263264
publishResource: async (name, content, options) =>
264265
await runtimeHost.resources.publishResource(name, content, options),
265266
resources: async () => await runtimeHost.resources.resources(),
267+
resolveResource: async (url) => await tryResolveResource(url, { trace }),
266268
fetch: (url, options) => fetch(url, { ...(options || {}), trace }),
267269
fetchText: (url, options) => fetchText(url, { ...(options || {}), trace }),
268270
resolveLanguageModel: async (modelId) => {

packages/core/src/types.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,11 @@ export type ChatToolChoice =
368368
name: string;
369369
};
370370

371-
export interface ModelOptions extends ModelConnectionOptions, ModelTemplateOptions, CacheOptions, RetryOptions {
371+
export interface ModelOptions
372+
extends ModelConnectionOptions,
373+
ModelTemplateOptions,
374+
CacheOptions,
375+
RetryOptions {
372376
/**
373377
* Temperature to use. Higher temperature means more hallucination/creativity.
374378
* Range 0.0-2.0.
@@ -5068,6 +5072,13 @@ export interface ResourceHost {
50685072
* List available resource references
50695073
*/
50705074
resources(): Promise<ResourceReference[]>;
5075+
5076+
/**
5077+
* Tries to resolve a resource from a URL.
5078+
* @param url - The URL to resolve.
5079+
* @returns A promise that resolves to an object containing the parsed URI and resolved files, or undefined if resolution fails.
5080+
*/
5081+
resolveResource(url: string): Promise<{ uri: URL; files: WorkspaceFile[] } | undefined>;
50715082
}
50725083

50735084
export interface UserInterfaceHost {
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Sample script demonstrating the use of host.resolveResource
2+
// This resolves a URL to access resources and their content
3+
4+
script({
5+
title: "Resource Resolution Example",
6+
description: "Demonstrates using host.resolveResource to fetch and process remote resources",
7+
group: "Samples",
8+
})
9+
10+
// URL to resolve - using GitHub favicon as an example
11+
const url = "https://github.com/microsoft/genaiscript/blob/main/docs/public/images/favicon.png"
12+
13+
console.log(`Resolving resource: ${url}`)
14+
15+
try {
16+
// Use host.resolveResource to resolve the URL
17+
const result = await host.resolveResource(url)
18+
19+
if (result) {
20+
console.log(`✅ Successfully resolved resource:`)
21+
console.log(` URI: ${result.uri}`)
22+
console.log(` Files found: ${result.files.length}`)
23+
24+
// Display information about each resolved file
25+
for (const file of result.files) {
26+
console.log(` 📄 File: ${file.filename}`)
27+
console.log(` Content type: ${file.content ? 'binary' : 'text'}`)
28+
29+
if (file.content) {
30+
console.log(` Size: ${file.content.length} bytes`)
31+
console.log(` Content preview: [binary data - ${file.content.slice(0, 20)}...]`)
32+
} else if (file.text) {
33+
console.log(` Size: ${file.text.length} characters`)
34+
console.log(` Content preview: ${file.text.slice(0, 100)}...`)
35+
}
36+
}
37+
38+
// Example of using the resolved content in a prompt
39+
if (result.files.length > 0) {
40+
const file = result.files[0]
41+
if (file.content) {
42+
$`Here's information about the resolved image file:
43+
- URL: ${result.uri}
44+
- Filename: ${file.filename}
45+
- Size: ${file.content.length} bytes
46+
- Type: Binary image data
47+
48+
This demonstrates how host.resolveResource can fetch and provide access to remote resources
49+
including binary files like images, documents, and other content types.`
50+
}
51+
}
52+
} else {
53+
console.log(`❌ Failed to resolve resource: ${url}`)
54+
$`Could not resolve the resource at ${url}. This might be due to:
55+
- Invalid URL format
56+
- Network connectivity issues
57+
- Unsupported protocol
58+
- Resource not found`
59+
}
60+
} catch (error) {
61+
console.error(`Error resolving resource:`, error)
62+
$`An error occurred while trying to resolve the resource: ${error.message}`
63+
}

0 commit comments

Comments
 (0)