-
Notifications
You must be signed in to change notification settings - Fork 342
Generate ListChatCompletions with pagination #549
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
christothes
merged 12 commits into
openai:main
from
christothes:chriss/listChatCompletions
Jul 29, 2025
Merged
Changes from 10 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c4f7be7
GetChatCompletions with generated pagination initial
christothes 38037d6
wip with options
christothes 2786c95
comments
christothes 7970bdf
fixup params
christothes 7977507
fixup metadata query param
christothes 62ba97e
add readme for debugging the generator
christothes edb42b9
fb
christothes c02ccc3
fb
christothes d2ccb54
merge
christothes 5f2db73
fb
christothes 982d239
fb
christothes 016b08d
fb
christothes 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Debugging the generator | ||
|
|
||
| To configure VS Code for debugging the generator, specifically visitors, add the following to your `launch.json` in the root of the workspace | ||
|
|
||
| ```json | ||
| { | ||
| "version": "0.2.0", | ||
| "configurations": [ | ||
| { | ||
| "name": "Debug OpenAI Library Plugin", | ||
| "type": "coreclr", | ||
| "request": "launch", | ||
| "program": "dotnet", | ||
| "args": [ | ||
| "${workspaceFolder}/codegen/dist/generator/Microsoft.TypeSpec.Generator.dll", | ||
| "${workspaceFolder}", | ||
| "-g", | ||
| "OpenAILibraryGenerator" | ||
| ], | ||
| } | ||
| ] | ||
| } | ||
| ``` |
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
130 changes: 130 additions & 0 deletions
130
codegen/generator/src/Visitors/MetadataQueryParamVisitor.cs
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,130 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using Microsoft.TypeSpec.Generator.ClientModel; | ||
| using Microsoft.TypeSpec.Generator.Expressions; | ||
| using Microsoft.TypeSpec.Generator.Primitives; | ||
| using Microsoft.TypeSpec.Generator.Providers; | ||
| using Microsoft.TypeSpec.Generator.Snippets; | ||
| using Microsoft.TypeSpec.Generator.Statements; | ||
| using static OpenAILibraryPlugin.Visitors.VisitorHelpers; | ||
|
|
||
| namespace OpenAILibraryPlugin.Visitors; | ||
|
|
||
| /// <summary> | ||
| /// This visitor modifies GetRawPagesAsync methods to consider HasMore in addition to LastId when deciding whether to continue pagination. | ||
| /// It also replaces specific parameters with an options type for pagination methods. | ||
| /// </summary> | ||
| public class MetadataQueryParamVisitor : ScmLibraryVisitor | ||
| { | ||
|
|
||
| private static readonly string[] _chatParamsToReplace = ["after", "before", "limit", "order", "model", "metadata"]; | ||
| private static readonly Dictionary<string, string> _paramReplacementMap = new() | ||
| { | ||
| { "after", "AfterId" }, | ||
| { "before", "LastId" }, | ||
| { "limit", "PageSizeLimit" }, | ||
| { "order", "Order" }, | ||
| { "model", "Model" }, | ||
| { "metadata", "Metadata" } | ||
| }; | ||
| private static readonly Dictionary<string, (string ReturnType, string OptionsType, string[] ParamsToReplace)> _optionsReplacements = new() | ||
| { | ||
| { | ||
| "GetChatCompletions", | ||
| ("ChatCompletion", "ChatCompletionCollectionOptions", _chatParamsToReplace) | ||
| }, | ||
| { | ||
| "GetChatCompletionsAsync", | ||
| ("ChatCompletion", "ChatCompletionCollectionOptions", _chatParamsToReplace) | ||
| } | ||
| }; | ||
christothes marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| /// <summary> | ||
| /// Visits Create*Request methods to modify how metadata query parameters are handled. | ||
| /// It replaces the following statements: | ||
| /// <code> | ||
| /// List<object> list = new List<object>(); | ||
| /// foreach (var @param in metadata) | ||
| /// { | ||
| /// uri.AppendQuery($"metadata[{@param.Key}]", @param.Value, true); | ||
| /// list.Add(@param.Key); | ||
| /// list.Add(@param.Value); | ||
| /// } | ||
| /// uri.AppendQueryDelimited("metadata", list, ",", null, true); | ||
| /// </code> | ||
| /// with: | ||
| /// <code> | ||
| /// foreach (var @param in metadata) | ||
| /// { | ||
| /// uri.AppendQuery($"metadata[{@param.Key}]", @param.Value, true); | ||
| /// } | ||
| /// </summary> | ||
| /// <param name="method"></param> | ||
| /// <returns></returns> | ||
| protected override MethodProvider? VisitMethod(MethodProvider method) | ||
christothes marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| // Check if the method is one of the Create*Request methods and has a signature that takes a metadata parameter like IDictionary<string, string> metadata | ||
| if (method.Signature.Name.StartsWith("Create") && method.Signature.Name.EndsWith("Request") && | ||
| method.Signature.Parameters.Any(p => p.Type.IsDictionary && p.Name == "metadata")) | ||
| { | ||
| ValueExpression? uri = null; | ||
| var statements = method.BodyStatements?.ToList() ?? new List<MethodBodyStatement>(); | ||
| VisitExplodedMethodBodyStatements( | ||
| statements!, | ||
| statement => | ||
| { | ||
| // Check if the statement is an assignment to a variable named "uri" | ||
| // Capture it if so | ||
| if (statement is ExpressionStatement expressionStatement && | ||
| expressionStatement.Expression is AssignmentExpression assignmentExpression && | ||
| assignmentExpression.Variable is DeclarationExpression declarationExpression && | ||
| declarationExpression.Variable is VariableExpression variableExpression && | ||
| variableExpression.Declaration.RequestedName == "uri") | ||
| { | ||
| uri = variableExpression; | ||
| } | ||
| // Try to remove the unnecessary list declaration | ||
| if (statement is ExpressionStatement expressionStatement2 && | ||
| expressionStatement2.Expression is AssignmentExpression assignmentExpression2 && | ||
| assignmentExpression2.Variable is DeclarationExpression declarationExpression2 && | ||
| declarationExpression2.Variable is VariableExpression variableExpression2 && | ||
| variableExpression2.Declaration.RequestedName == "list" && | ||
| variableExpression2.Type.IsCollection && variableExpression2.Type.IsGenericType) | ||
| { | ||
| // Remove the list declaration | ||
| return new SingleLineCommentStatement("Plugin customization: remove unnecessary list declaration"); | ||
| } | ||
|
|
||
| if (uri is not null && | ||
| statement is ForEachStatement foreachStatement && | ||
| foreachStatement.Enumerable is DictionaryExpression dictionaryExpression && | ||
| dictionaryExpression.Original is VariableExpression variable && | ||
| variable.Declaration.RequestedName == "metadata") | ||
| { | ||
| var formatString = new FormattableStringExpression("metadata[{0}]", [foreachStatement.ItemVariable.Property("Key")]); | ||
| var appendQueryStatement = uri.Invoke("AppendQuery", [formatString, foreachStatement.ItemVariable.Property("Value"), Snippet.True]); | ||
| foreachStatement.Body.Clear(); | ||
| foreachStatement.Body.Add(new SingleLineCommentStatement("Plugin customization: Properly handle metadata query parameters")); | ||
| foreachStatement.Body.Add(appendQueryStatement.Terminate()); | ||
| } | ||
|
|
||
| // Remove the call to AppendQueryDelimited for metadata | ||
| if (statement is ExpressionStatement expressionStatement3 && | ||
| expressionStatement3.Expression is InvokeMethodExpression invokeMethodExpression && | ||
| invokeMethodExpression.MethodName == "AppendQueryDelimited" && | ||
| invokeMethodExpression.Arguments.Count == 5 && | ||
| invokeMethodExpression.Arguments[0].ToDisplayString() == "\"metadata\"") | ||
| { | ||
| return new SingleLineCommentStatement("Plugin customization: remove unnecessary AppendQueryDelimited for metadata"); | ||
| } | ||
| return statement; | ||
| }); | ||
|
|
||
| // Rebuild the method body with the modified statements | ||
| method.Update(bodyStatements: statements); | ||
| } | ||
|
|
||
| return base.VisitMethod(method); | ||
| } | ||
| } | ||
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.