Merge branch 'main' into node24
This commit is contained in:
@@ -16,6 +16,6 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Update the ${{ env.TAG_NAME }} tag
|
- name: Update the ${{ env.TAG_NAME }} tag
|
||||||
uses: actions/publish-action@v0.2.2
|
uses: actions/publish-action@v0.3.0
|
||||||
with:
|
with:
|
||||||
source-tag: ${{ env.TAG_NAME }}
|
source-tag: ${{ env.TAG_NAME }}
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
---
|
||||||
|
name: openai
|
||||||
|
version: 5.11.0
|
||||||
|
type: npm
|
||||||
|
summary: The official TypeScript library for the OpenAI API
|
||||||
|
homepage:
|
||||||
|
license: apache-2.0
|
||||||
|
licenses:
|
||||||
|
- sources: LICENSE
|
||||||
|
text: |2
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2025 OpenAI
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
notices: []
|
||||||
@@ -65,6 +65,9 @@ steps:
|
|||||||
var3: |
|
var3: |
|
||||||
Lorem Ipsum
|
Lorem Ipsum
|
||||||
Hello World
|
Hello World
|
||||||
|
file_input: |
|
||||||
|
var4: ./path/to/long-text.txt
|
||||||
|
var5: ./path/to/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Simple prompt.yml example
|
#### Simple prompt.yml example
|
||||||
@@ -116,7 +119,9 @@ jsonSchema: |-
|
|||||||
```
|
```
|
||||||
|
|
||||||
Variables in prompt.yml files are templated using `{{variable}}` format and are
|
Variables in prompt.yml files are templated using `{{variable}}` format and are
|
||||||
supplied via the `input` parameter in YAML format.
|
supplied via the `input` parameter in YAML format. Additionally, you can
|
||||||
|
provide file-based variables via `file_input`, where each key maps to a file
|
||||||
|
path.
|
||||||
|
|
||||||
### Using a system prompt file
|
### Using a system prompt file
|
||||||
|
|
||||||
@@ -168,12 +173,24 @@ steps:
|
|||||||
token: ${{ secrets.USER_PAT }}
|
token: ${{ secrets.USER_PAT }}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If you want, you can use separate tokens for the AI inference endpoint
|
||||||
|
and the GitHub MCP server:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
steps:
|
||||||
|
- name: AI Inference with Separate MCP Token
|
||||||
|
id: inference
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
prompt: 'List my open pull requests and create a summary'
|
||||||
|
enable-github-mcp: true
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
github-mcp-token: ${{ secrets.USER_PAT }}
|
||||||
|
```
|
||||||
|
|
||||||
When MCP is enabled, the AI model will have access to GitHub tools and can
|
When MCP is enabled, the AI model will have access to GitHub tools and can
|
||||||
perform actions like searching issues and PRs.
|
perform actions like searching issues and PRs.
|
||||||
|
|
||||||
**Note:** For now, MCP integration cannot be used with the built-in token. You
|
|
||||||
must pass a GitHub PAT into `token:` instead.
|
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
Various inputs are defined in [`action.yml`](action.yml) to let you configure
|
Various inputs are defined in [`action.yml`](action.yml) to let you configure
|
||||||
@@ -185,12 +202,14 @@ the action:
|
|||||||
| `prompt` | The prompt to send to the model | N/A |
|
| `prompt` | The prompt to send to the model | N/A |
|
||||||
| `prompt-file` | Path to a file containing the prompt (supports .txt and .prompt.yml formats). If both `prompt` and `prompt-file` are provided, `prompt-file` takes precedence | `""` |
|
| `prompt-file` | Path to a file containing the prompt (supports .txt and .prompt.yml formats). If both `prompt` and `prompt-file` are provided, `prompt-file` takes precedence | `""` |
|
||||||
| `input` | Template variables in YAML format for .prompt.yml files (e.g., `var1: value1` on separate lines) | `""` |
|
| `input` | Template variables in YAML format for .prompt.yml files (e.g., `var1: value1` on separate lines) | `""` |
|
||||||
|
| `file_input` | Template variables in YAML where values are file paths. The file contents are read and used for templating | `""` |
|
||||||
| `system-prompt` | The system prompt to send to the model | `"You are a helpful assistant"` |
|
| `system-prompt` | The system prompt to send to the model | `"You are a helpful assistant"` |
|
||||||
| `system-prompt-file` | Path to a file containing the system prompt. If both `system-prompt` and `system-prompt-file` are provided, `system-prompt-file` takes precedence | `""` |
|
| `system-prompt-file` | Path to a file containing the system prompt. If both `system-prompt` and `system-prompt-file` are provided, `system-prompt-file` takes precedence | `""` |
|
||||||
| `model` | The model to use for inference. Must be available in the [GitHub Models](https://github.com/marketplace?type=models) catalog | `openai/gpt-4o` |
|
| `model` | The model to use for inference. Must be available in the [GitHub Models](https://github.com/marketplace?type=models) catalog | `openai/gpt-4o` |
|
||||||
| `endpoint` | The endpoint to use for inference. If you're running this as part of an org, you should probably use the org-specific Models endpoint | `https://models.github.ai/inference` |
|
| `endpoint` | The endpoint to use for inference. If you're running this as part of an org, you should probably use the org-specific Models endpoint | `https://models.github.ai/inference` |
|
||||||
| `max-tokens` | The max number of tokens to generate | 200 |
|
| `max-tokens` | The max number of tokens to generate | 200 |
|
||||||
| `enable-github-mcp` | Enable Model Context Protocol integration with GitHub tools | `false` |
|
| `enable-github-mcp` | Enable Model Context Protocol integration with GitHub tools | `false` |
|
||||||
|
| `github-mcp-token` | Token to use for GitHub MCP server (defaults to the main token if not specified). Use a separate PAT for tighter security | `""` |
|
||||||
|
|
||||||
## Outputs
|
## Outputs
|
||||||
|
|
||||||
|
|||||||
+332
-124
@@ -2,17 +2,15 @@ import {vi, type MockedFunction, beforeEach, expect, describe, it} from 'vitest'
|
|||||||
import * as core from '../__fixtures__/core.js'
|
import * as core from '../__fixtures__/core.js'
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const mockPost = vi.fn() as MockedFunction<any>
|
const mockCreate = vi.fn() as MockedFunction<any>
|
||||||
const mockPath = vi.fn(() => ({post: mockPost}))
|
const mockCompletions = {create: mockCreate}
|
||||||
const mockClient = vi.fn(() => ({path: mockPath}))
|
const mockChat = {completions: mockCompletions}
|
||||||
|
const mockOpenAIClient = vi.fn(() => ({
|
||||||
vi.mock('@azure-rest/ai-inference', () => ({
|
chat: mockChat,
|
||||||
default: mockClient,
|
|
||||||
isUnexpected: vi.fn(() => false),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('@azure/core-auth', () => ({
|
vi.mock('openai', () => ({
|
||||||
AzureKeyCredential: vi.fn(),
|
default: mockOpenAIClient,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
@@ -29,8 +27,8 @@ const {simpleInference, mcpInference} = await import('../src/inference.js')
|
|||||||
describe('inference.ts', () => {
|
describe('inference.ts', () => {
|
||||||
const mockRequest = {
|
const mockRequest = {
|
||||||
messages: [
|
messages: [
|
||||||
{role: 'system', content: 'You are a test assistant'},
|
{role: 'system' as const, content: 'You are a test assistant'},
|
||||||
{role: 'user', content: 'Hello, AI!'},
|
{role: 'user' as const, content: 'Hello, AI!'},
|
||||||
],
|
],
|
||||||
modelName: 'gpt-4',
|
modelName: 'gpt-4',
|
||||||
maxTokens: 100,
|
maxTokens: 100,
|
||||||
@@ -45,18 +43,16 @@ describe('inference.ts', () => {
|
|||||||
describe('simpleInference', () => {
|
describe('simpleInference', () => {
|
||||||
it('performs simple inference without tools', async () => {
|
it('performs simple inference without tools', async () => {
|
||||||
const mockResponse = {
|
const mockResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Hello, user!',
|
||||||
content: 'Hello, user!',
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValue(mockResponse)
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
const result = await simpleInference(mockRequest)
|
const result = await simpleInference(mockRequest)
|
||||||
|
|
||||||
@@ -65,44 +61,83 @@ describe('inference.ts', () => {
|
|||||||
expect(core.info).toHaveBeenCalledWith('Model response: Hello, user!')
|
expect(core.info).toHaveBeenCalledWith('Model response: Hello, user!')
|
||||||
|
|
||||||
// Verify the request structure
|
// Verify the request structure
|
||||||
expect(mockPost).toHaveBeenCalledWith({
|
expect(mockCreate).toHaveBeenCalledWith({
|
||||||
body: {
|
messages: [
|
||||||
messages: [
|
{
|
||||||
{
|
role: 'system',
|
||||||
role: 'system',
|
content: 'You are a test assistant',
|
||||||
content: 'You are a test assistant',
|
},
|
||||||
},
|
{
|
||||||
{
|
role: 'user',
|
||||||
role: 'user',
|
content: 'Hello, AI!',
|
||||||
content: 'Hello, AI!',
|
},
|
||||||
},
|
],
|
||||||
],
|
max_tokens: 100,
|
||||||
max_tokens: 100,
|
model: 'gpt-4',
|
||||||
model: 'gpt-4',
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('handles null response content', async () => {
|
it('handles null response content', async () => {
|
||||||
const mockResponse = {
|
const mockResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: null,
|
||||||
content: null,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValue(mockResponse)
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
const result = await simpleInference(mockRequest)
|
const result = await simpleInference(mockRequest)
|
||||||
|
|
||||||
expect(result).toBeNull()
|
expect(result).toBeNull()
|
||||||
expect(core.info).toHaveBeenCalledWith('Model response: No response content')
|
expect(core.info).toHaveBeenCalledWith('Model response: No response content')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('includes response format when specified', async () => {
|
||||||
|
const requestWithResponseFormat = {
|
||||||
|
...mockRequest,
|
||||||
|
responseFormat: {
|
||||||
|
type: 'json_schema' as const,
|
||||||
|
json_schema: {type: 'object'},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: '{"result": "success"}',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
|
const result = await simpleInference(requestWithResponseFormat)
|
||||||
|
|
||||||
|
expect(result).toBe('{"result": "success"}')
|
||||||
|
|
||||||
|
// Verify response format was included in the request
|
||||||
|
expect(mockCreate).toHaveBeenCalledWith({
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: 'system',
|
||||||
|
content: 'You are a test assistant',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content: 'Hello, AI!',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
max_tokens: 100,
|
||||||
|
model: 'gpt-4',
|
||||||
|
response_format: requestWithResponseFormat.responseFormat,
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('mcpInference', () => {
|
describe('mcpInference', () => {
|
||||||
@@ -123,19 +158,17 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
it('performs inference without tool calls', async () => {
|
it('performs inference without tool calls', async () => {
|
||||||
const mockResponse = {
|
const mockResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Hello, user!',
|
||||||
content: 'Hello, user!',
|
tool_calls: null,
|
||||||
tool_calls: null,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValue(mockResponse)
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
const result = await mcpInference(mockRequest, mockMcpClient)
|
const result = await mcpInference(mockRequest, mockMcpClient)
|
||||||
|
|
||||||
@@ -146,12 +179,13 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
// The MCP inference loop will always add the assistant message, even when there are no tool calls
|
// The MCP inference loop will always add the assistant message, even when there are no tool calls
|
||||||
// So we don't check the exact messages, just that tools were included
|
// So we don't check the exact messages, just that tools were included
|
||||||
expect(mockPost).toHaveBeenCalledTimes(1)
|
expect(mockCreate).toHaveBeenCalledTimes(1)
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const callArgs = mockPost.mock.calls[0][0] as any
|
const callArgs = mockCreate.mock.calls[0][0] as any
|
||||||
expect(callArgs.body.tools).toEqual(mockMcpClient.tools)
|
expect(callArgs.tools).toEqual(mockMcpClient.tools)
|
||||||
expect(callArgs.body.model).toBe('gpt-4')
|
expect(callArgs.response_format).toBeUndefined()
|
||||||
expect(callArgs.body.max_tokens).toBe(100)
|
expect(callArgs.model).toBe('gpt-4')
|
||||||
|
expect(callArgs.max_tokens).toBe(100)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('executes tool calls and continues conversation', async () => {
|
it('executes tool calls and continues conversation', async () => {
|
||||||
@@ -176,33 +210,29 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
// First response with tool calls
|
// First response with tool calls
|
||||||
const firstResponse = {
|
const firstResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'I need to use a tool.',
|
||||||
content: 'I need to use a tool.',
|
tool_calls: toolCalls,
|
||||||
tool_calls: toolCalls,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
// Second response after tool execution
|
// Second response after tool execution
|
||||||
const secondResponse = {
|
const secondResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Here is the final answer.',
|
||||||
content: 'Here is the final answer.',
|
tool_calls: null,
|
||||||
tool_calls: null,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValueOnce(firstResponse).mockResolvedValueOnce(secondResponse)
|
mockCreate.mockResolvedValueOnce(firstResponse).mockResolvedValueOnce(secondResponse)
|
||||||
|
|
||||||
mockExecuteToolCalls.mockResolvedValue(toolResults)
|
mockExecuteToolCalls.mockResolvedValue(toolResults)
|
||||||
|
|
||||||
@@ -210,15 +240,15 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
expect(result).toBe('Here is the final answer.')
|
expect(result).toBe('Here is the final answer.')
|
||||||
expect(mockExecuteToolCalls).toHaveBeenCalledWith(mockMcpClient.client, toolCalls)
|
expect(mockExecuteToolCalls).toHaveBeenCalledWith(mockMcpClient.client, toolCalls)
|
||||||
expect(mockPost).toHaveBeenCalledTimes(2)
|
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||||
|
|
||||||
// Verify the second call includes the conversation history
|
// Verify the second call includes the conversation history
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const secondCall = mockPost.mock.calls[1][0] as any
|
const secondCall = mockCreate.mock.calls[1][0] as any
|
||||||
expect(secondCall.body.messages).toHaveLength(5) // system, user, assistant, tool, assistant
|
expect(secondCall.messages).toHaveLength(5) // system, user, assistant, tool, assistant
|
||||||
expect(secondCall.body.messages[2].role).toBe('assistant')
|
expect(secondCall.messages[2].role).toBe('assistant')
|
||||||
expect(secondCall.body.messages[2].tool_calls).toEqual(toolCalls)
|
expect(secondCall.messages[2].tool_calls).toEqual(toolCalls)
|
||||||
expect(secondCall.body.messages[3]).toEqual(toolResults[0])
|
expect(secondCall.messages[3]).toEqual(toolResults[0])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('handles maximum iteration limit', async () => {
|
it('handles maximum iteration limit', async () => {
|
||||||
@@ -243,43 +273,39 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
// Always respond with tool calls to trigger infinite loop
|
// Always respond with tool calls to trigger infinite loop
|
||||||
const responseWithToolCalls = {
|
const responseWithToolCalls = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Using tool again.',
|
||||||
content: 'Using tool again.',
|
tool_calls: toolCalls,
|
||||||
tool_calls: toolCalls,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValue(responseWithToolCalls)
|
mockCreate.mockResolvedValue(responseWithToolCalls)
|
||||||
mockExecuteToolCalls.mockResolvedValue(toolResults)
|
mockExecuteToolCalls.mockResolvedValue(toolResults)
|
||||||
|
|
||||||
const result = await mcpInference(mockRequest, mockMcpClient)
|
const result = await mcpInference(mockRequest, mockMcpClient)
|
||||||
|
|
||||||
expect(mockPost).toHaveBeenCalledTimes(5) // Max iterations reached
|
expect(mockCreate).toHaveBeenCalledTimes(5) // Max iterations reached
|
||||||
expect(core.warning).toHaveBeenCalledWith('GitHub MCP inference loop exceeded maximum iterations (5)')
|
expect(core.warning).toHaveBeenCalledWith('GitHub MCP inference loop exceeded maximum iterations (5)')
|
||||||
expect(result).toBe('Using tool again.') // Last assistant message
|
expect(result).toBe('Using tool again.') // Last assistant message
|
||||||
})
|
})
|
||||||
|
|
||||||
it('handles empty tool calls array', async () => {
|
it('handles empty tool calls array', async () => {
|
||||||
const mockResponse = {
|
const mockResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Hello, user!',
|
||||||
content: 'Hello, user!',
|
tool_calls: [],
|
||||||
tool_calls: [],
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValue(mockResponse)
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
const result = await mcpInference(mockRequest, mockMcpClient)
|
const result = await mcpInference(mockRequest, mockMcpClient)
|
||||||
|
|
||||||
@@ -297,32 +323,28 @@ describe('inference.ts', () => {
|
|||||||
]
|
]
|
||||||
|
|
||||||
const firstResponse = {
|
const firstResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'First message',
|
||||||
content: 'First message',
|
tool_calls: toolCalls,
|
||||||
tool_calls: toolCalls,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
const secondResponse = {
|
const secondResponse = {
|
||||||
body: {
|
choices: [
|
||||||
choices: [
|
{
|
||||||
{
|
message: {
|
||||||
message: {
|
content: 'Second message',
|
||||||
content: 'Second message',
|
tool_calls: toolCalls,
|
||||||
tool_calls: toolCalls,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
},
|
||||||
},
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
mockPost.mockResolvedValueOnce(firstResponse).mockResolvedValue(secondResponse)
|
mockCreate.mockResolvedValueOnce(firstResponse).mockResolvedValue(secondResponse)
|
||||||
|
|
||||||
mockExecuteToolCalls.mockResolvedValue([
|
mockExecuteToolCalls.mockResolvedValue([
|
||||||
{
|
{
|
||||||
@@ -337,5 +359,191 @@ describe('inference.ts', () => {
|
|||||||
|
|
||||||
expect(result).toBe('Second message')
|
expect(result).toBe('Second message')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('makes additional loop with response format when no tool calls are made', async () => {
|
||||||
|
const requestWithResponseFormat = {
|
||||||
|
...mockRequest,
|
||||||
|
responseFormat: {
|
||||||
|
type: 'json_schema' as const,
|
||||||
|
json_schema: {type: 'object'},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// First response without tool calls
|
||||||
|
const firstResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: 'First response',
|
||||||
|
tool_calls: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second response with response format applied
|
||||||
|
const secondResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: '{"result": "formatted response"}',
|
||||||
|
tool_calls: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
mockCreate.mockResolvedValueOnce(firstResponse).mockResolvedValueOnce(secondResponse)
|
||||||
|
|
||||||
|
const result = await mcpInference(requestWithResponseFormat, mockMcpClient)
|
||||||
|
|
||||||
|
expect(result).toBe('{"result": "formatted response"}')
|
||||||
|
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||||
|
expect(core.info).toHaveBeenCalledWith('Making one more MCP loop with the requested response format...')
|
||||||
|
|
||||||
|
// First call should have tools but no response format
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const firstCall = mockCreate.mock.calls[0][0] as any
|
||||||
|
expect(firstCall.tools).toEqual(mockMcpClient.tools)
|
||||||
|
expect(firstCall.response_format).toBeUndefined()
|
||||||
|
|
||||||
|
// Second call should have response format but no tools
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const secondCall = mockCreate.mock.calls[1][0] as any
|
||||||
|
expect(secondCall.tools).toBeUndefined()
|
||||||
|
expect(secondCall.response_format).toEqual(requestWithResponseFormat.responseFormat)
|
||||||
|
|
||||||
|
// Second call should include the user message requesting JSON format
|
||||||
|
expect(secondCall.messages).toHaveLength(5) // system, user, assistant, user, assistant
|
||||||
|
expect(secondCall.messages[3].role).toBe('user')
|
||||||
|
expect(secondCall.messages[3].content).toContain('Please provide your response in the exact')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses response format only on final iteration after tool calls', async () => {
|
||||||
|
const requestWithResponseFormat = {
|
||||||
|
...mockRequest,
|
||||||
|
responseFormat: {
|
||||||
|
type: 'json_schema' as const,
|
||||||
|
json_schema: {type: 'object'},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const toolCalls = [
|
||||||
|
{
|
||||||
|
id: 'call-123',
|
||||||
|
function: {
|
||||||
|
name: 'test-tool',
|
||||||
|
arguments: '{"param": "value"}',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const toolResults = [
|
||||||
|
{
|
||||||
|
tool_call_id: 'call-123',
|
||||||
|
role: 'tool',
|
||||||
|
name: 'test-tool',
|
||||||
|
content: 'Tool result',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
// First response with tool calls
|
||||||
|
const firstResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: 'Using tool',
|
||||||
|
tool_calls: toolCalls,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second response without tool calls, but should trigger final message loop
|
||||||
|
const secondResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: 'Intermediate result',
|
||||||
|
tool_calls: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
// Third response with response format
|
||||||
|
const thirdResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: '{"final": "result"}',
|
||||||
|
tool_calls: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
mockCreate
|
||||||
|
.mockResolvedValueOnce(firstResponse)
|
||||||
|
.mockResolvedValueOnce(secondResponse)
|
||||||
|
.mockResolvedValueOnce(thirdResponse)
|
||||||
|
|
||||||
|
mockExecuteToolCalls.mockResolvedValue(toolResults)
|
||||||
|
|
||||||
|
const result = await mcpInference(requestWithResponseFormat, mockMcpClient)
|
||||||
|
|
||||||
|
expect(result).toBe('{"final": "result"}')
|
||||||
|
expect(mockCreate).toHaveBeenCalledTimes(3)
|
||||||
|
|
||||||
|
// First call: tools but no response format
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const firstCall = mockCreate.mock.calls[0][0] as any
|
||||||
|
expect(firstCall.tools).toEqual(mockMcpClient.tools)
|
||||||
|
expect(firstCall.response_format).toBeUndefined()
|
||||||
|
|
||||||
|
// Second call: tools but no response format (after tool execution)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const secondCall = mockCreate.mock.calls[1][0] as any
|
||||||
|
expect(secondCall.tools).toEqual(mockMcpClient.tools)
|
||||||
|
expect(secondCall.response_format).toBeUndefined()
|
||||||
|
|
||||||
|
// Third call: response format but no tools (final message)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const thirdCall = mockCreate.mock.calls[2][0] as any
|
||||||
|
expect(thirdCall.tools).toBeUndefined()
|
||||||
|
expect(thirdCall.response_format).toEqual(requestWithResponseFormat.responseFormat)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns immediately when response format is set and finalMessage is already true', async () => {
|
||||||
|
const requestWithResponseFormat = {
|
||||||
|
...mockRequest,
|
||||||
|
responseFormat: {
|
||||||
|
type: 'json_schema' as const,
|
||||||
|
json_schema: {type: 'object'},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response without tool calls on what would be the final message iteration
|
||||||
|
const mockResponse = {
|
||||||
|
choices: [
|
||||||
|
{
|
||||||
|
message: {
|
||||||
|
content: '{"immediate": "result"}',
|
||||||
|
tool_calls: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
mockCreate.mockResolvedValue(mockResponse)
|
||||||
|
|
||||||
|
// We need to test a scenario where finalMessage would already be true
|
||||||
|
// This happens when we're already in the final iteration
|
||||||
|
const result = await mcpInference(requestWithResponseFormat, mockMcpClient)
|
||||||
|
|
||||||
|
// The function should make two calls: one normal, then one with response format
|
||||||
|
expect(mockCreate).toHaveBeenCalledTimes(2)
|
||||||
|
expect(result).toBe('{"immediate": "result"}')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -34,6 +34,12 @@ vi.mock('../src/mcp.js', () => ({
|
|||||||
|
|
||||||
vi.mock('@actions/core', () => core)
|
vi.mock('@actions/core', () => core)
|
||||||
|
|
||||||
|
// Mock process.exit to prevent it from actually exiting during tests
|
||||||
|
const mockProcessExit = vi.spyOn(process, 'exit').mockImplementation(() => {
|
||||||
|
// Prevent actual exit, but don't throw - just return
|
||||||
|
return undefined as never
|
||||||
|
})
|
||||||
|
|
||||||
// The module being tested should be imported dynamically. This ensures that the
|
// The module being tested should be imported dynamically. This ensures that the
|
||||||
// mocks are used in place of any actual dependencies.
|
// mocks are used in place of any actual dependencies.
|
||||||
const {run} = await import('../src/main.js')
|
const {run} = await import('../src/main.js')
|
||||||
@@ -41,6 +47,7 @@ const {run} = await import('../src/main.js')
|
|||||||
describe('main.ts - prompt.yml integration', () => {
|
describe('main.ts - prompt.yml integration', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
mockProcessExit.mockClear()
|
||||||
|
|
||||||
// Mock environment variables
|
// Mock environment variables
|
||||||
process.env['GITHUB_TOKEN'] = 'test-token'
|
process.env['GITHUB_TOKEN'] = 'test-token'
|
||||||
@@ -103,8 +110,12 @@ model: openai/gpt-4o
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Expect the run function to complete successfully
|
||||||
await run()
|
await run()
|
||||||
|
|
||||||
|
// Verify process.exit was called with code 0 (success)
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
|
|
||||||
// Verify simpleInference was called with the correct message structure
|
// Verify simpleInference was called with the correct message structure
|
||||||
expect(mockSimpleInference).toHaveBeenCalledWith(
|
expect(mockSimpleInference).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
@@ -130,6 +141,52 @@ model: openai/gpt-4o
|
|||||||
expect(core.setOutput).toHaveBeenCalledWith('response-file', expect.any(String))
|
expect(core.setOutput).toHaveBeenCalledWith('response-file', expect.any(String))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('supports file_input variables to load file contents', async () => {
|
||||||
|
mockExistsSync.mockReturnValue(true)
|
||||||
|
|
||||||
|
// First call: reading the prompt file. Second call: reading file_input referenced file contents.
|
||||||
|
const externalFilePath = 'vars.txt'
|
||||||
|
mockReadFileSync.mockImplementation((path: string) => {
|
||||||
|
if (path === 'test.prompt.yml') {
|
||||||
|
return `messages:\n - role: user\n content: 'Here is the data: {{blob}}'\nmodel: openai/gpt-4o\n`
|
||||||
|
}
|
||||||
|
if (path === externalFilePath) {
|
||||||
|
return 'FILE_CONTENTS'
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
})
|
||||||
|
|
||||||
|
core.getInput.mockImplementation((name: string) => {
|
||||||
|
switch (name) {
|
||||||
|
case 'prompt-file':
|
||||||
|
return 'test.prompt.yml'
|
||||||
|
case 'file_input':
|
||||||
|
return `blob: ${externalFilePath}`
|
||||||
|
case 'model':
|
||||||
|
return 'openai/gpt-4o'
|
||||||
|
case 'max-tokens':
|
||||||
|
return '200'
|
||||||
|
case 'endpoint':
|
||||||
|
return 'https://models.github.ai/inference'
|
||||||
|
case 'enable-github-mcp':
|
||||||
|
return 'false'
|
||||||
|
default:
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
await run()
|
||||||
|
|
||||||
|
expect(mockSimpleInference).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
messages: [{role: 'user', content: 'Here is the data: FILE_CONTENTS'}],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Verify process.exit was called with code 0 (success)
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
|
})
|
||||||
|
|
||||||
it('should fall back to legacy format when not using prompt YAML', async () => {
|
it('should fall back to legacy format when not using prompt YAML', async () => {
|
||||||
mockExistsSync.mockReturnValue(false)
|
mockExistsSync.mockReturnValue(false)
|
||||||
core.getInput.mockImplementation((name: string) => {
|
core.getInput.mockImplementation((name: string) => {
|
||||||
@@ -172,5 +229,8 @@ model: openai/gpt-4o
|
|||||||
token: 'test-token',
|
token: 'test-token',
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Verify process.exit was called with code 0 (success)
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+15
-1
@@ -94,6 +94,12 @@ vi.mock('../src/inference.js', () => ({
|
|||||||
|
|
||||||
vi.mock('@actions/core', () => core)
|
vi.mock('@actions/core', () => core)
|
||||||
|
|
||||||
|
// Mock process.exit to prevent it from actually exiting during tests
|
||||||
|
const mockProcessExit = vi.spyOn(process, 'exit').mockImplementation(() => {
|
||||||
|
// Prevent actual exit, but don't throw - just return
|
||||||
|
return undefined as never
|
||||||
|
})
|
||||||
|
|
||||||
// The module being tested should be imported dynamically. This ensures that the
|
// The module being tested should be imported dynamically. This ensures that the
|
||||||
// mocks are used in place of any actual dependencies.
|
// mocks are used in place of any actual dependencies.
|
||||||
const {run} = await import('../src/main.js')
|
const {run} = await import('../src/main.js')
|
||||||
@@ -102,6 +108,7 @@ describe('main.ts', () => {
|
|||||||
// Reset all mocks before each test
|
// Reset all mocks before each test
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
|
mockProcessExit.mockClear()
|
||||||
|
|
||||||
// Remove any existing GITHUB_TOKEN
|
// Remove any existing GITHUB_TOKEN
|
||||||
delete process.env.GITHUB_TOKEN
|
delete process.env.GITHUB_TOKEN
|
||||||
@@ -121,6 +128,7 @@ describe('main.ts', () => {
|
|||||||
|
|
||||||
expect(core.setOutput).toHaveBeenCalled()
|
expect(core.setOutput).toHaveBeenCalled()
|
||||||
verifyStandardResponse()
|
verifyStandardResponse()
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('Sets a failed status when no prompt is set', async () => {
|
it('Sets a failed status when no prompt is set', async () => {
|
||||||
@@ -131,7 +139,8 @@ describe('main.ts', () => {
|
|||||||
|
|
||||||
await run()
|
await run()
|
||||||
|
|
||||||
expect(core.setFailed).toHaveBeenNthCalledWith(1, 'Neither prompt-file nor prompt was set')
|
expect(core.setFailed).toHaveBeenCalledWith('Neither prompt-file nor prompt was set')
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('uses simple inference when MCP is disabled', async () => {
|
it('uses simple inference when MCP is disabled', async () => {
|
||||||
@@ -157,6 +166,7 @@ describe('main.ts', () => {
|
|||||||
expect(mockConnectToGitHubMCP).not.toHaveBeenCalled()
|
expect(mockConnectToGitHubMCP).not.toHaveBeenCalled()
|
||||||
expect(mockMcpInference).not.toHaveBeenCalled()
|
expect(mockMcpInference).not.toHaveBeenCalled()
|
||||||
verifyStandardResponse()
|
verifyStandardResponse()
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('uses MCP inference when enabled and connection succeeds', async () => {
|
it('uses MCP inference when enabled and connection succeeds', async () => {
|
||||||
@@ -189,6 +199,7 @@ describe('main.ts', () => {
|
|||||||
)
|
)
|
||||||
expect(mockSimpleInference).not.toHaveBeenCalled()
|
expect(mockSimpleInference).not.toHaveBeenCalled()
|
||||||
verifyStandardResponse()
|
verifyStandardResponse()
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('falls back to simple inference when MCP connection fails', async () => {
|
it('falls back to simple inference when MCP connection fails', async () => {
|
||||||
@@ -207,6 +218,7 @@ describe('main.ts', () => {
|
|||||||
expect(mockMcpInference).not.toHaveBeenCalled()
|
expect(mockMcpInference).not.toHaveBeenCalled()
|
||||||
expect(core.warning).toHaveBeenCalledWith('MCP connection failed, falling back to simple inference')
|
expect(core.warning).toHaveBeenCalledWith('MCP connection failed, falling back to simple inference')
|
||||||
verifyStandardResponse()
|
verifyStandardResponse()
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('properly integrates with loadContentFromFileOrInput', async () => {
|
it('properly integrates with loadContentFromFileOrInput', async () => {
|
||||||
@@ -240,6 +252,7 @@ describe('main.ts', () => {
|
|||||||
responseFormat: undefined,
|
responseFormat: undefined,
|
||||||
})
|
})
|
||||||
verifyStandardResponse()
|
verifyStandardResponse()
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('handles non-existent prompt-file with an error', async () => {
|
it('handles non-existent prompt-file with an error', async () => {
|
||||||
@@ -254,5 +267,6 @@ describe('main.ts', () => {
|
|||||||
await run()
|
await run()
|
||||||
|
|
||||||
expect(core.setFailed).toHaveBeenCalledWith(`File for prompt-file was not found: ${promptFile}`)
|
expect(core.setFailed).toHaveBeenCalledWith(`File for prompt-file was not found: ${promptFile}`)
|
||||||
|
expect(mockProcessExit).toHaveBeenCalledWith(1)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import {describe, it, expect} from 'vitest'
|
import {describe, it, expect} from 'vitest'
|
||||||
import * as path from 'path'
|
import * as path from 'path'
|
||||||
import {fileURLToPath} from 'url'
|
import {fileURLToPath} from 'url'
|
||||||
import {parseTemplateVariables, replaceTemplateVariables, loadPromptFile, isPromptYamlFile} from '../src/prompt'
|
import {
|
||||||
|
parseTemplateVariables,
|
||||||
|
replaceTemplateVariables,
|
||||||
|
loadPromptFile,
|
||||||
|
isPromptYamlFile,
|
||||||
|
parseFileTemplateVariables,
|
||||||
|
} from '../src/prompt'
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url)
|
const __filename = fileURLToPath(import.meta.url)
|
||||||
const __dirname = path.dirname(__filename)
|
const __dirname = path.dirname(__filename)
|
||||||
@@ -10,8 +16,8 @@ describe('prompt.ts', () => {
|
|||||||
describe('parseTemplateVariables', () => {
|
describe('parseTemplateVariables', () => {
|
||||||
it('should parse simple YAML variables', () => {
|
it('should parse simple YAML variables', () => {
|
||||||
const input = `
|
const input = `
|
||||||
a: hello
|
a: hello
|
||||||
b: world
|
b: world
|
||||||
`
|
`
|
||||||
const result = parseTemplateVariables(input)
|
const result = parseTemplateVariables(input)
|
||||||
expect(result).toEqual({a: 'hello', b: 'world'})
|
expect(result).toEqual({a: 'hello', b: 'world'})
|
||||||
@@ -19,10 +25,10 @@ b: world
|
|||||||
|
|
||||||
it('should parse multiline variables', () => {
|
it('should parse multiline variables', () => {
|
||||||
const input = `
|
const input = `
|
||||||
var1: hello
|
var1: hello
|
||||||
var2: |
|
var2: |
|
||||||
This is a
|
This is a
|
||||||
multiline string
|
multiline string
|
||||||
`
|
`
|
||||||
const result = parseTemplateVariables(input)
|
const result = parseTemplateVariables(input)
|
||||||
expect(result.var1).toBe('hello')
|
expect(result.var1).toBe('hello')
|
||||||
@@ -117,4 +123,17 @@ var2: |
|
|||||||
expect(() => loadPromptFile('non-existent.prompt.yml')).toThrow('Prompt file not found')
|
expect(() => loadPromptFile('non-existent.prompt.yml')).toThrow('Prompt file not found')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('parseFileTemplateVariables', () => {
|
||||||
|
it('reads file contents for variables', () => {
|
||||||
|
const configPath = path.join(__dirname, '../__fixtures__/prompts/json-schema.prompt.yml')
|
||||||
|
const data = parseFileTemplateVariables(`sample: ${configPath}`)
|
||||||
|
expect(data.sample).toContain('messages:')
|
||||||
|
expect(data.sample).toContain('responseFormat:')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('errors on missing files', () => {
|
||||||
|
expect(() => parseFileTemplateVariables('x: ./does-not-exist.txt')).toThrow('was not found')
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ inputs:
|
|||||||
description: Template variables in YAML format for .prompt.yml files
|
description: Template variables in YAML format for .prompt.yml files
|
||||||
required: false
|
required: false
|
||||||
default: ''
|
default: ''
|
||||||
|
file_input:
|
||||||
|
description: Template variables in YAML format mapping variable names to file paths. The file contents will be used for templating.
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
model:
|
model:
|
||||||
description: The model to use
|
description: The model to use
|
||||||
required: false
|
required: false
|
||||||
@@ -50,6 +54,10 @@ inputs:
|
|||||||
description: Enable Model Context Protocol integration with GitHub tools
|
description: Enable Model Context Protocol integration with GitHub tools
|
||||||
required: false
|
required: false
|
||||||
default: 'false'
|
default: 'false'
|
||||||
|
github-mcp-token:
|
||||||
|
description: The token to use for GitHub MCP server (defaults to GITHUB_TOKEN if not specified)
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
|
||||||
# Define your outputs here.
|
# Define your outputs here.
|
||||||
outputs:
|
outputs:
|
||||||
|
|||||||
+6726
-7077
File diff suppressed because it is too large
Load Diff
+1
-1
File diff suppressed because one or more lines are too long
Generated
+25
-57
@@ -12,12 +12,10 @@
|
|||||||
"@actions/core": "^1.11.1",
|
"@actions/core": "^1.11.1",
|
||||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
|
"openai": "^5.11.0",
|
||||||
"pkce-challenge": "^5.0.0"
|
"pkce-challenge": "^5.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@azure-rest/ai-inference": "latest",
|
|
||||||
"@azure/core-auth": "latest",
|
|
||||||
"@azure/core-sse": "latest",
|
|
||||||
"@eslint/compat": "^1.3.0",
|
"@eslint/compat": "^1.3.0",
|
||||||
"@github/local-action": "^5.1.0",
|
"@github/local-action": "^5.1.0",
|
||||||
"@github/prettier-config": "^0.0.6",
|
"@github/prettier-config": "^0.0.6",
|
||||||
@@ -518,44 +516,6 @@
|
|||||||
"integrity": "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==",
|
"integrity": "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@azure-rest/ai-inference": {
|
|
||||||
"version": "1.0.0-beta.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/@azure-rest/ai-inference/-/ai-inference-1.0.0-beta.6.tgz",
|
|
||||||
"integrity": "sha512-j5FrJDTHu2P2+zwFVe5j2edasOIhqkFj+VkDjbhGkQuOoIAByF0egRkgs0G1k03HyJ7bOOT9BkRF7MIgr/afhw==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@azure-rest/core-client": "^2.1.0",
|
|
||||||
"@azure/abort-controller": "^2.1.2",
|
|
||||||
"@azure/core-auth": "^1.9.0",
|
|
||||||
"@azure/core-lro": "^2.7.2",
|
|
||||||
"@azure/core-rest-pipeline": "^1.18.2",
|
|
||||||
"@azure/core-tracing": "^1.2.0",
|
|
||||||
"@azure/logger": "^1.1.4",
|
|
||||||
"tslib": "^2.8.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@azure-rest/core-client": {
|
|
||||||
"version": "2.4.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-2.4.0.tgz",
|
|
||||||
"integrity": "sha512-CjMFBcmnt0YNdRcxSSoZbtZNXudLlicdml7UrPsV03nHiWB+Bq5cu5ctieyaCuRtU7jm7+SOFtiE/g4pBFPKKA==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@azure/abort-controller": "^2.0.0",
|
|
||||||
"@azure/core-auth": "^1.3.0",
|
|
||||||
"@azure/core-rest-pipeline": "^1.5.0",
|
|
||||||
"@azure/core-tracing": "^1.0.1",
|
|
||||||
"@typespec/ts-http-runtime": "^0.2.2",
|
|
||||||
"tslib": "^2.6.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@azure/abort-controller": {
|
"node_modules/@azure/abort-controller": {
|
||||||
"version": "2.1.2",
|
"version": "2.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
|
||||||
@@ -666,19 +626,6 @@
|
|||||||
"node": ">=18.0.0"
|
"node": ">=18.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@azure/core-sse": {
|
|
||||||
"version": "2.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.3.0.tgz",
|
|
||||||
"integrity": "sha512-jKhPpdDbVS5GlpadSKIC7V6Q4P2vEcwXi1c4CLTXs01Q/PAITES9v5J/S73+RtCMqQpsX0jGa2yPWwXi9JzdgA==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tslib": "^2.6.2"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@azure/core-tracing": {
|
"node_modules/@azure/core-tracing": {
|
||||||
"version": "1.2.0",
|
"version": "1.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz",
|
||||||
@@ -2390,9 +2337,9 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@rollup/rollup-linux-x64-gnu": {
|
"node_modules/@rollup/rollup-linux-x64-gnu": {
|
||||||
"version": "4.45.1",
|
"version": "4.46.0",
|
||||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.45.1.tgz",
|
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.46.0.tgz",
|
||||||
"integrity": "sha512-+E/lYl6qu1zqgPEnTrs4WysQtvc/Sh4fC2nByfFExqgYrqkKWp1tWIbe+ELhixnenSpBbLXNi6vbEEJ8M7fiHw==",
|
"integrity": "sha512-Cv+moII5C8RM6gZbR3cb21o6rquVDZrN2o81maROg1LFzBz2dZUwIQSxFA8GtGZ/F2KtsqQ2z3eFPBb6akvQNg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@@ -7034,6 +6981,27 @@
|
|||||||
"wrappy": "1"
|
"wrappy": "1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/openai": {
|
||||||
|
"version": "5.11.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/openai/-/openai-5.11.0.tgz",
|
||||||
|
"integrity": "sha512-+AuTc5pVjlnTuA9zvn8rA/k+1RluPIx9AD4eDcnutv6JNwHHZxIhkFy+tmMKCvmMFDQzfA/r1ujvPWB19DQkYg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"openai": "bin/cli"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"ws": "^8.18.0",
|
||||||
|
"zod": "^3.23.8"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"ws": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"zod": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/optionator": {
|
"node_modules/optionator": {
|
||||||
"version": "0.9.4",
|
"version": "0.9.4",
|
||||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||||
|
|||||||
+1
-3
@@ -26,12 +26,10 @@
|
|||||||
"@actions/core": "^1.11.1",
|
"@actions/core": "^1.11.1",
|
||||||
"@modelcontextprotocol/sdk": "^1.15.1",
|
"@modelcontextprotocol/sdk": "^1.15.1",
|
||||||
"js-yaml": "^4.1.0",
|
"js-yaml": "^4.1.0",
|
||||||
|
"openai": "^5.11.0",
|
||||||
"pkce-challenge": "^5.0.0"
|
"pkce-challenge": "^5.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@azure-rest/ai-inference": "latest",
|
|
||||||
"@azure/core-auth": "latest",
|
|
||||||
"@azure/core-sse": "latest",
|
|
||||||
"@eslint/compat": "^1.3.0",
|
"@eslint/compat": "^1.3.0",
|
||||||
"@github/local-action": "^5.1.0",
|
"@github/local-action": "^5.1.0",
|
||||||
"@github/prettier-config": "^0.0.6",
|
"@github/prettier-config": "^0.0.6",
|
||||||
|
|||||||
+2
-33
@@ -1,5 +1,4 @@
|
|||||||
import * as core from '@actions/core'
|
import * as core from '@actions/core'
|
||||||
import {GetChatCompletionsDefaultResponse} from '@azure-rest/ai-inference'
|
|
||||||
import * as fs from 'fs'
|
import * as fs from 'fs'
|
||||||
import {PromptConfig} from './prompt.js'
|
import {PromptConfig} from './prompt.js'
|
||||||
import {InferenceRequest} from './inference.js'
|
import {InferenceRequest} from './inference.js'
|
||||||
@@ -29,36 +28,6 @@ export function loadContentFromFileOrInput(filePathInput: string, contentInput:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper function to handle unexpected responses from AI service
|
|
||||||
* @param response - The response object from the AI service
|
|
||||||
* @throws Error with appropriate error message based on response content
|
|
||||||
*/
|
|
||||||
export function handleUnexpectedResponse(response: GetChatCompletionsDefaultResponse): never {
|
|
||||||
// Extract x-ms-error-code from headers if available
|
|
||||||
const errorCode = response.headers['x-ms-error-code']
|
|
||||||
const errorCodeMsg = errorCode ? ` (error code: ${errorCode})` : ''
|
|
||||||
|
|
||||||
// Check if response body exists and contains error details
|
|
||||||
if (response.body && response.body.error) {
|
|
||||||
throw response.body.error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle case where response body is missing
|
|
||||||
if (!response.body) {
|
|
||||||
throw new Error(
|
|
||||||
`Failed to get response from AI service (status: ${response.status})${errorCodeMsg}. ` +
|
|
||||||
'Please check network connection and endpoint configuration.',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle other error cases
|
|
||||||
throw new Error(
|
|
||||||
`AI service returned error response (status: ${response.status})${errorCodeMsg}: ` +
|
|
||||||
(typeof response.body === 'string' ? response.body : JSON.stringify(response.body)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build messages array from either prompt config or legacy format
|
* Build messages array from either prompt config or legacy format
|
||||||
*/
|
*/
|
||||||
@@ -66,11 +35,11 @@ export function buildMessages(
|
|||||||
promptConfig?: PromptConfig,
|
promptConfig?: PromptConfig,
|
||||||
systemPrompt?: string,
|
systemPrompt?: string,
|
||||||
prompt?: string,
|
prompt?: string,
|
||||||
): Array<{role: string; content: string}> {
|
): Array<{role: 'system' | 'user' | 'assistant' | 'tool'; content: string}> {
|
||||||
if (promptConfig?.messages && promptConfig.messages.length > 0) {
|
if (promptConfig?.messages && promptConfig.messages.length > 0) {
|
||||||
// Use new message format
|
// Use new message format
|
||||||
return promptConfig.messages.map(msg => ({
|
return promptConfig.messages.map(msg => ({
|
||||||
role: msg.role,
|
role: msg.role as 'system' | 'user' | 'assistant' | 'tool',
|
||||||
content: msg.content,
|
content: msg.content,
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+92
-69
@@ -1,25 +1,16 @@
|
|||||||
import * as core from '@actions/core'
|
import * as core from '@actions/core'
|
||||||
import ModelClient, {isUnexpected} from '@azure-rest/ai-inference'
|
import OpenAI from 'openai'
|
||||||
import {AzureKeyCredential} from '@azure/core-auth'
|
import {GitHubMCPClient, executeToolCalls, ToolCall} from './mcp.js'
|
||||||
import {GitHubMCPClient, executeToolCalls, MCPTool, ToolCall} from './mcp.js'
|
|
||||||
import {handleUnexpectedResponse} from './helpers.js'
|
|
||||||
|
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
role: string
|
role: 'system' | 'user' | 'assistant' | 'tool'
|
||||||
content: string | null
|
content: string | null
|
||||||
tool_calls?: ToolCall[]
|
tool_calls?: ToolCall[]
|
||||||
}
|
tool_call_id?: string
|
||||||
|
|
||||||
interface ChatCompletionsRequestBody {
|
|
||||||
messages: ChatMessage[]
|
|
||||||
max_tokens: number
|
|
||||||
model: string
|
|
||||||
response_format?: {type: 'json_schema'; json_schema: unknown}
|
|
||||||
tools?: MCPTool[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface InferenceRequest {
|
export interface InferenceRequest {
|
||||||
messages: Array<{role: string; content: string}>
|
messages: Array<{role: 'system' | 'user' | 'assistant' | 'tool'; content: string}>
|
||||||
modelName: string
|
modelName: string
|
||||||
maxTokens: number
|
maxTokens: number
|
||||||
endpoint: string
|
endpoint: string
|
||||||
@@ -45,33 +36,38 @@ export interface InferenceResponse {
|
|||||||
export async function simpleInference(request: InferenceRequest): Promise<string | null> {
|
export async function simpleInference(request: InferenceRequest): Promise<string | null> {
|
||||||
core.info('Running simple inference without tools')
|
core.info('Running simple inference without tools')
|
||||||
|
|
||||||
const client = ModelClient(request.endpoint, new AzureKeyCredential(request.token), {
|
const client = new OpenAI({
|
||||||
userAgentOptions: {userAgentPrefix: 'github-actions-ai-inference'},
|
apiKey: request.token,
|
||||||
|
baseURL: request.endpoint,
|
||||||
})
|
})
|
||||||
|
|
||||||
const requestBody: ChatCompletionsRequestBody = {
|
const chatCompletionRequest: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||||
messages: request.messages,
|
messages: request.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[],
|
||||||
max_tokens: request.maxTokens,
|
max_tokens: request.maxTokens,
|
||||||
model: request.modelName,
|
model: request.modelName,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add response format if specified
|
// Add response format if specified
|
||||||
if (request.responseFormat) {
|
if (request.responseFormat) {
|
||||||
requestBody.response_format = request.responseFormat
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
chatCompletionRequest.response_format = request.responseFormat as any
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await client.path('/chat/completions').post({
|
try {
|
||||||
body: requestBody,
|
const response = await client.chat.completions.create(chatCompletionRequest)
|
||||||
})
|
|
||||||
|
|
||||||
if (isUnexpected(response)) {
|
if ('choices' in response) {
|
||||||
handleUnexpectedResponse(response)
|
const modelResponse = response.choices[0]?.message?.content
|
||||||
|
core.info(`Model response: ${modelResponse || 'No response content'}`)
|
||||||
|
return modelResponse || null
|
||||||
|
} else {
|
||||||
|
core.error(`Unexpected response format from API: ${JSON.stringify(response)}`)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
core.error(`API error: ${error}`)
|
||||||
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const modelResponse = response.body.choices[0].message.content
|
|
||||||
core.info(`Model response: ${modelResponse || 'No response content'}`)
|
|
||||||
|
|
||||||
return modelResponse
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -83,8 +79,9 @@ export async function mcpInference(
|
|||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
core.info('Running GitHub MCP inference with tools')
|
core.info('Running GitHub MCP inference with tools')
|
||||||
|
|
||||||
const client = ModelClient(request.endpoint, new AzureKeyCredential(request.token), {
|
const client = new OpenAI({
|
||||||
userAgentOptions: {userAgentPrefix: 'github-actions-ai-inference'},
|
apiKey: request.token,
|
||||||
|
baseURL: request.endpoint,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Start with the pre-processed messages
|
// Start with the pre-processed messages
|
||||||
@@ -92,57 +89,83 @@ export async function mcpInference(
|
|||||||
|
|
||||||
let iterationCount = 0
|
let iterationCount = 0
|
||||||
const maxIterations = 5 // Prevent infinite loops
|
const maxIterations = 5 // Prevent infinite loops
|
||||||
|
// We want to use response_format (e.g. JSON) on the last iteration only, so the model can output
|
||||||
|
// the final result in the expected format without interfering with tool calls
|
||||||
|
let finalMessage = false
|
||||||
|
|
||||||
while (iterationCount < maxIterations) {
|
while (iterationCount < maxIterations) {
|
||||||
iterationCount++
|
iterationCount++
|
||||||
core.info(`MCP inference iteration ${iterationCount}`)
|
core.info(`MCP inference iteration ${iterationCount}`)
|
||||||
|
|
||||||
const requestBody: ChatCompletionsRequestBody = {
|
const chatCompletionRequest: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||||
messages: messages,
|
messages: messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[],
|
||||||
max_tokens: request.maxTokens,
|
max_tokens: request.maxTokens,
|
||||||
model: request.modelName,
|
model: request.modelName,
|
||||||
tools: githubMcpClient.tools,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add response format if specified (only on first iteration to avoid conflicts)
|
// Add response format if specified (only on final iteration to avoid conflicts with tool calls)
|
||||||
if (iterationCount === 1 && request.responseFormat) {
|
if (finalMessage && request.responseFormat) {
|
||||||
requestBody.response_format = request.responseFormat
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
chatCompletionRequest.response_format = request.responseFormat as any
|
||||||
|
} else {
|
||||||
|
chatCompletionRequest.tools = githubMcpClient.tools as OpenAI.Chat.Completions.ChatCompletionTool[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await client.path('/chat/completions').post({
|
try {
|
||||||
body: requestBody,
|
const response = await client.chat.completions.create(chatCompletionRequest)
|
||||||
})
|
|
||||||
|
|
||||||
if (isUnexpected(response)) {
|
if (!('choices' in response)) {
|
||||||
handleUnexpectedResponse(response)
|
throw new Error(`Unexpected response format from API: ${JSON.stringify(response)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const assistantMessage = response.choices[0]?.message
|
||||||
|
const modelResponse = assistantMessage?.content
|
||||||
|
const toolCalls = assistantMessage?.tool_calls
|
||||||
|
|
||||||
|
core.info(`Model response: ${modelResponse || 'No response content'}`)
|
||||||
|
|
||||||
|
messages.push({
|
||||||
|
role: 'assistant',
|
||||||
|
content: modelResponse || '',
|
||||||
|
...(toolCalls && {tool_calls: toolCalls as ToolCall[]}),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!toolCalls || toolCalls.length === 0) {
|
||||||
|
core.info('No tool calls requested, ending GitHub MCP inference loop')
|
||||||
|
|
||||||
|
// If we have a response format set and we haven't explicitly run one final message iteration,
|
||||||
|
// do another loop with the response format set
|
||||||
|
if (request.responseFormat && !finalMessage) {
|
||||||
|
core.info('Making one more MCP loop with the requested response format...')
|
||||||
|
|
||||||
|
// Add a user message requesting JSON format and try again
|
||||||
|
messages.push({
|
||||||
|
role: 'user',
|
||||||
|
content: `Please provide your response in the exact ${request.responseFormat.type} format specified.`,
|
||||||
|
})
|
||||||
|
|
||||||
|
finalMessage = true
|
||||||
|
|
||||||
|
// Continue the loop to get a properly formatted response
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
return modelResponse || null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
core.info(`Model requested ${toolCalls.length} tool calls`)
|
||||||
|
|
||||||
|
// Execute all tool calls via GitHub MCP
|
||||||
|
const toolResults = await executeToolCalls(githubMcpClient.client, toolCalls as ToolCall[])
|
||||||
|
|
||||||
|
// Add tool results to the conversation
|
||||||
|
messages.push(...toolResults)
|
||||||
|
|
||||||
|
core.info('Tool results added, continuing conversation...')
|
||||||
|
} catch (error) {
|
||||||
|
core.error(`OpenAI API error: ${error}`)
|
||||||
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const assistantMessage = response.body.choices[0].message
|
|
||||||
const modelResponse = assistantMessage.content
|
|
||||||
const toolCalls = assistantMessage.tool_calls
|
|
||||||
|
|
||||||
core.info(`Model response: ${modelResponse || 'No response content'}`)
|
|
||||||
|
|
||||||
messages.push({
|
|
||||||
role: 'assistant',
|
|
||||||
content: modelResponse || '',
|
|
||||||
...(toolCalls && {tool_calls: toolCalls}),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!toolCalls || toolCalls.length === 0) {
|
|
||||||
core.info('No tool calls requested, ending GitHub MCP inference loop')
|
|
||||||
return modelResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
core.info(`Model requested ${toolCalls.length} tool calls`)
|
|
||||||
|
|
||||||
// Execute all tool calls via GitHub MCP
|
|
||||||
const toolResults = await executeToolCalls(githubMcpClient.client, toolCalls)
|
|
||||||
|
|
||||||
// Add tool results to the conversation
|
|
||||||
messages.push(...toolResults)
|
|
||||||
|
|
||||||
core.info('Tool results added, continuing conversation...')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
core.warning(`GitHub MCP inference loop exceeded maximum iterations (${maxIterations})`)
|
core.warning(`GitHub MCP inference loop exceeded maximum iterations (${maxIterations})`)
|
||||||
|
|||||||
+22
-5
@@ -5,7 +5,13 @@ import * as path from 'path'
|
|||||||
import {connectToGitHubMCP} from './mcp.js'
|
import {connectToGitHubMCP} from './mcp.js'
|
||||||
import {simpleInference, mcpInference} from './inference.js'
|
import {simpleInference, mcpInference} from './inference.js'
|
||||||
import {loadContentFromFileOrInput, buildInferenceRequest} from './helpers.js'
|
import {loadContentFromFileOrInput, buildInferenceRequest} from './helpers.js'
|
||||||
import {loadPromptFile, parseTemplateVariables, isPromptYamlFile, PromptConfig} from './prompt.js'
|
import {
|
||||||
|
loadPromptFile,
|
||||||
|
parseTemplateVariables,
|
||||||
|
isPromptYamlFile,
|
||||||
|
PromptConfig,
|
||||||
|
parseFileTemplateVariables,
|
||||||
|
} from './prompt.js'
|
||||||
|
|
||||||
const RESPONSE_FILE = 'modelResponse.txt'
|
const RESPONSE_FILE = 'modelResponse.txt'
|
||||||
|
|
||||||
@@ -18,6 +24,7 @@ export async function run(): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
const promptFilePath = core.getInput('prompt-file')
|
const promptFilePath = core.getInput('prompt-file')
|
||||||
const inputVariables = core.getInput('input')
|
const inputVariables = core.getInput('input')
|
||||||
|
const fileInputVariables = core.getInput('file_input')
|
||||||
|
|
||||||
let promptConfig: PromptConfig | undefined = undefined
|
let promptConfig: PromptConfig | undefined = undefined
|
||||||
let systemPrompt: string | undefined = undefined
|
let systemPrompt: string | undefined = undefined
|
||||||
@@ -27,8 +34,10 @@ export async function run(): Promise<void> {
|
|||||||
if (promptFilePath && isPromptYamlFile(promptFilePath)) {
|
if (promptFilePath && isPromptYamlFile(promptFilePath)) {
|
||||||
core.info('Using prompt YAML file format')
|
core.info('Using prompt YAML file format')
|
||||||
|
|
||||||
// Parse template variables
|
// Parse template variables from both string inputs and file-based inputs
|
||||||
const templateVariables = parseTemplateVariables(inputVariables)
|
const stringVars = parseTemplateVariables(inputVariables)
|
||||||
|
const fileVars = parseFileTemplateVariables(fileInputVariables)
|
||||||
|
const templateVariables = {...stringVars, ...fileVars}
|
||||||
|
|
||||||
// Load and process prompt file
|
// Load and process prompt file
|
||||||
promptConfig = loadPromptFile(promptFilePath, templateVariables)
|
promptConfig = loadPromptFile(promptFilePath, templateVariables)
|
||||||
@@ -49,6 +58,9 @@ export async function run(): Promise<void> {
|
|||||||
throw new Error('GITHUB_TOKEN is not set')
|
throw new Error('GITHUB_TOKEN is not set')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get GitHub MCP token (use dedicated token if provided, otherwise fall back to main token)
|
||||||
|
const githubMcpToken = core.getInput('github-mcp-token') || token
|
||||||
|
|
||||||
const endpoint = core.getInput('endpoint')
|
const endpoint = core.getInput('endpoint')
|
||||||
|
|
||||||
// Build the inference request with pre-processed messages and response format
|
// Build the inference request with pre-processed messages and response format
|
||||||
@@ -67,7 +79,7 @@ export async function run(): Promise<void> {
|
|||||||
let modelResponse: string | null = null
|
let modelResponse: string | null = null
|
||||||
|
|
||||||
if (enableMcp) {
|
if (enableMcp) {
|
||||||
const mcpClient = await connectToGitHubMCP(inferenceRequest.token)
|
const mcpClient = await connectToGitHubMCP(githubMcpToken)
|
||||||
|
|
||||||
if (mcpClient) {
|
if (mcpClient) {
|
||||||
modelResponse = await mcpInference(inferenceRequest, mcpClient)
|
modelResponse = await mcpInference(inferenceRequest, mcpClient)
|
||||||
@@ -91,9 +103,14 @@ export async function run(): Promise<void> {
|
|||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
core.setFailed(error.message)
|
core.setFailed(error.message)
|
||||||
} else {
|
} else {
|
||||||
core.setFailed('An unexpected error occurred')
|
core.setFailed(`An unexpected error occurred: ${JSON.stringify(error, null, 2)}`)
|
||||||
}
|
}
|
||||||
|
// Force exit to prevent hanging on open connections
|
||||||
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Force exit to prevent hanging on open connections
|
||||||
|
process.exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
function tempDir(): string {
|
function tempDir(): string {
|
||||||
|
|||||||
@@ -37,6 +37,47 @@ export function parseTemplateVariables(input: string): TemplateVariables {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse file-based template variables from YAML input string. The YAML should map
|
||||||
|
* variable names to file paths. File contents are read and returned as variables.
|
||||||
|
*/
|
||||||
|
export function parseFileTemplateVariables(fileInput: string): TemplateVariables {
|
||||||
|
if (!fileInput.trim()) {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = yaml.load(fileInput) as Record<string, unknown>
|
||||||
|
if (typeof parsed !== 'object' || parsed === null) {
|
||||||
|
throw new Error('File template variables must be a YAML object')
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: TemplateVariables = {}
|
||||||
|
for (const [key, value] of Object.entries(parsed)) {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new Error(`File template variable '${key}' must be a string file path`)
|
||||||
|
}
|
||||||
|
const filePath = value
|
||||||
|
if (!fs.existsSync(filePath)) {
|
||||||
|
throw new Error(`File for template variable '${key}' was not found: ${filePath}`)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
result[key] = fs.readFileSync(filePath, 'utf-8')
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to read file for template variable '${key}' at path '${filePath}': ${err instanceof Error ? err.message : 'Unknown error'}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to parse file template variables: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replace template variables in text using {{variable}} syntax
|
* Replace template variables in text using {{variable}} syntax
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user