Skip to content

fix(models): sanitize name field in OpenAIMessageConverter to satisfy…#2346

Merged
jujn merged 3 commits into
agentscope-ai:mainfrom
hhbin2026:fix/2345-agent-name-space-bad-request
Jul 23, 2026
Merged

fix(models): sanitize name field in OpenAIMessageConverter to satisfy…#2346
jujn merged 3 commits into
agentscope-ai:mainfrom
hhbin2026:fix/2345-agent-name-space-bad-request

Conversation

@hhbin2026

@hhbin2026 hhbin2026 commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

… (#2345 )

AgentScope-Java Version

[The version of AgentScope-Java you are working on, e.g. 2.0.1, check your pom.xml dependency version or run mvn dependency:tree | grep agentscope-parent:pom(only mac/linux)]

Description

Example:

 /** Logical name used to register and resolve the model via {@link ModelRegistry}. */
    private static final String MODEL_ALIAS = "my-gpt5";

    public static void main(String[] args) throws Exception {
        // ----------------------------------------------------------------
        // 1. Resolve API key and optional custom base URL
        //    Override via env vars so the binary contains no secrets.
        // ----------------------------------------------------------------
        String apiKey = System.getenv("OPENAI_API_KEY");
        
        // Custom base URL for compatible providers (leave null to use OpenAI's default).
        // Example: "https://api.ciyuanshen.top/v1"
        String baseUrl = System.getenv("OPENAI_BASE_URL");

        // ----------------------------------------------------------------
        // 2. Build OpenAIChatModel
        //    Use GenerateOptions to apply call-level defaults (temperature,
        //    maxTokens, etc.) without changing the model's core configuration.
        // ----------------------------------------------------------------
        OpenAIChatModel.Builder modelBuilder =
                OpenAIChatModel.builder()
                        .apiKey(apiKey)
                        .modelName("gpt-5.4")
                        .stream(true)
                        .generateOptions(
                                GenerateOptions.builder()
                                        .temperature(0.2)
                                        .maxCompletionTokens(2048)
                                        .build());

        if (baseUrl != null && !baseUrl.isBlank()) {
            modelBuilder.baseUrl(baseUrl);
        }

        // ----------------------------------------------------------------
        // 3. Register the model under a logical alias so HarnessAgent (and
        //    any other component) can resolve it by name via ModelRegistry.
        // ----------------------------------------------------------------
        ModelRegistry.register(MODEL_ALIAS, modelBuilder.build());

        // ----------------------------------------------------------------
        // 4. Prepare workspace directory
        // ----------------------------------------------------------------
        Path workspace = Paths.get(".agentscope/openai-chat");
        initWorkspaceIfAbsent(workspace);

        // ----------------------------------------------------------------
        // 5. Build HarnessAgent — references the model by its registered name
        // ----------------------------------------------------------------
        HarnessAgent agent =
                HarnessAgent.builder()
                        .name("demo")
                        .sysPrompt(
                                "You are a helpful AI assistant. Be friendly, accurate and"
                                        + " concise.")
                        .model(MODEL_ALIAS)
                        .workspace(workspace)
                        .stateStore(new InMemoryAgentStateStore())
                        .build();

        // ----------------------------------------------------------------
        // 6. Single RuntimeContext for the entire session so multi-turn
        //    history is preserved across invocations.
        // ----------------------------------------------------------------
        RuntimeContext ctx =
                RuntimeContext.builder()
                        .sessionId("openai-chat-session")
                        .userId("user-1")
                        .build();

        // ----------------------------------------------------------------
        // 7. Interactive chat loop with streaming output
        // ----------------------------------------------------------------
        System.out.println("\n" + "=".repeat(60));
        System.out.println("OpenAI Chat Example  (model: gpt-5.5)");
        System.out.println("=".repeat(60));
        System.out.println("Type your message and press Enter. Type 'exit' to quit.\n");

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            System.out.print("You: ");
            String input = reader.readLine();

            if (input == null || input.trim().equalsIgnoreCase("exit")) {
                System.out.println("\nGoodbye!");
                break;
            }
            if (input.isBlank()) {
                continue;
            }

            System.out.print("\nAssistant: ");

            agent.streamEvents(new UserMessage("test name",input.trim()), ctx)
                    .doOnNext(
                            event -> {
                                if (event instanceof TextBlockDeltaEvent e) {
                                    System.out.print(e.getDelta());
                                }
                            })
                    .blockLast();
            System.out.println("\n");
        }
    }

    private static void initWorkspaceIfAbsent(Path workspace) throws Exception {
        Files.createDirectories(workspace);
        Path agentsMd = workspace.resolve("AGENTS.md");
        if (Files.exists(agentsMd)) return;
        Files.writeString(
                agentsMd,
                """
                # OpenAI Chat Assistant

                You are a general-purpose assistant powered by GPT.

                ## Behavior Guidelines
                - Answer questions clearly and concisely
                - If you are unsure, say so rather than guessing
                - Use bullet lists for multi-step answers when helpful
                """);
    }

Checklist

Please check the following items before code is ready to be reviewed.

  • [X ] Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

@CLAassistant

CLAassistant commented Jul 21, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Jul 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@jujn
jujn merged commit d60414a into agentscope-ai:main Jul 23, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants