Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions hugegraph-llm/src/hugegraph_llm/config/prompt_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,4 +386,25 @@ class PromptConfig(BasePromptConfig):
doc_input_text_CN: str = """介绍一下Sarah,她是一位30岁的律师,还有她的室友James,他们从2010年开始一起合租。James是一名记者,
职业道路也很出色。另外,Sarah拥有一个个人网站www.sarahsplace.com,而James也经营着自己的网页,不过这里没有提到具体的网址。这两个人,
Sarah和James,不仅建立起了深厚的室友情谊,还各自在网络上开辟了自己的一片天地,展示着他们各自丰富多彩的兴趣和经历。
"""

review_prompt: str = """
## 评审任务
请根据以下标准答案对模型的回答进行专业评估:

## 评估要求
1. 从准确性(与标准答案一致性)、相关性(与问题相关度)、完整性(信息完整度)三个维度进行1-5分评分
2. 计算综合评分(三个维度平均分,保留1位小数)
3. 提供简明扼要的改进建议
4. 使用JSON格式返回以下字段(返回内容一定要被```json ```所包围):
- accuracy_score (int)
- relevance_score (int)
- completeness_score (int)
- overall_score (float)
- comment (str)

## 标准答案
{standard_answer}

## 待评审回答
Comment thread
MrJs133 marked this conversation as resolved.
Outdated
"""
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def apply_llm_config(current_llm_config, arg1, arg2, arg3, arg4, origin_call=Non
data = {
"model": arg3,
"temperature": 0.01,
"messages": [{"role": "user", "content": "test"}],
"messages": [{"role": "user", "content": "hello"}],
Comment thread
MrJs133 marked this conversation as resolved.
Comment on lines 219 to +222

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing the test message from 'test' to 'hello' is a minor change. Consider adding a comment explaining why this change was made or using a constant/configuration value instead of hardcoding the message. This would make the purpose of the change clearer and make it easier to update in the future.

Suggested change
data = {
"model": arg3,
"temperature": 0.01,
"messages": [{"role": "user", "content": "test"}],
"messages": [{"role": "user", "content": "hello"}],
"messages": [{"role": "user", "content": DEFAULT_TEST_MESSAGE}], # Using a configurable message

}
headers = {"Authorization": f"Bearer {arg1}"}
status_code = test_api_connection(test_url, method="POST", headers=headers, body=data, origin_call=origin_call)
Expand Down
38 changes: 37 additions & 1 deletion hugegraph-llm/src/hugegraph_llm/demo/rag_demo/other_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.

import os
import asyncio
from contextlib import asynccontextmanager

Expand All @@ -24,8 +25,10 @@
from fastapi import FastAPI

from hugegraph_llm.utils.hugegraph_utils import init_hg_test_data, run_gremlin_query, backup_data
from hugegraph_llm.utils.other_tool_utils import auto_test_llms
from hugegraph_llm.utils.log import log
from hugegraph_llm.demo.rag_demo.vector_graph_block import timely_update_vid_embedding
from hugegraph_llm.config import llm_settings, resource_path


def create_other_block():
Expand All @@ -42,14 +45,47 @@ def create_other_block():
out = gr.Textbox(label="Backup Graph Manually (Auto backup at 1:00 AM everyday)", show_copy_button=True)
btn = gr.Button("Backup Graph Data")
btn.click(fn=backup_data, inputs=inp, outputs=out) # pylint: disable=no-member
# auto test llm
with gr.Accordion("Evaluation Model Settings (only support openai)", open=True):
with gr.Row():
review_model_name = gr.Textbox(label="Model Name", value="ernie-4.5-8k-preview", interactive=True)
review_max_tokens = gr.Textbox(label="Max Tokens", value=2048)
key = gr.Textbox(value=getattr(llm_settings, "openai_chat_api_key"), label="API Key")
base = gr.Textbox(value=getattr(llm_settings, "openai_chat_api_base"),label="API Base")
with gr.Row():
with gr.Column():
with gr.Tab("file") as tab_upload_file: # pylint: disable=W0612
inp1_file = gr.File(
value=os.path.join(resource_path, "demo", "llm_review.yaml"),
label="yaml file",
file_count="single",
)
with gr.Tab("text") as tab_upload_text: # pylint: disable=W0612
inp1 = gr.Textbox(
value="openai, model_name, api_key, api_base, max_tokens\n" \
"qianfan_wenxin, model_name, api_key, secret_key\n" \
"ollama/local, model_name, host, port, max_tokens\n" \
"litellm, model_name, api_key, api_base, max_tokens\n",
label="LLMs Config (every line represents a different LLM)",
show_copy_button=True, lines=6
)
with gr.Row():
inp2 = gr.Textbox(value="hello, how are you?", label="Prompt", show_copy_button=True, lines=8)
inp3 = gr.Textbox(value="I am fine, thank you", label="Standard Answer", show_copy_button=True, lines=8)
out = gr.Code(label="Output", language="json", elem_classes="code-container-show")
btn = gr.Button("Run LLM Test")
btn.click( # pylint: disable=no-member
fn=auto_test_llms,
inputs=[inp1, inp1_file, inp2, inp3, review_model_name, review_max_tokens, key, base],
outputs=out
)
Comment on lines +48 to +81

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

验证 Tab 切换功能是否完整

注意到您添加了 Tab 切换界面,但缺少响应 Tab 选择的回调函数。如果用户在两个 Tab 间切换,可能会导致数据不一致。建议验证这种情况下的行为是否符合预期。


🏁 Script executed:

#!/bin/bash
# 检查之前是否存在 Tab 选择的实现或相关功能
grep -r "on_tab_select\|tab.*select\|select.*tab" --include="*.py" .

Length of output: 565


补充 Tab 切换回调以保持数据一致性

在 hugegraph-llm/src/hugegraph_llm/demo/rag_demo/other_block.py (约48–81行)中新增了“file”/“text”两个 Tab,但未绑定切换回调。建议参考已实现的 vector_graph_block.py 中的 on_tab_select,用法示例:

  • 文件:hugegraph-llm/src/hugegraph_llm/demo/rag_demo/other_block.py
    位置:约 48–81 行
    问题:tab_upload_filetab_upload_text 未调用 .select(...),切换时两个输入组件可能无法正确同步。

  • 示例(来自 vector_graph_block.py):

    def on_tab_select(input_f, input_t, evt: gr.SelectData):
        # …根据 evt.index 返回对应输入…
        return input_f, input_t
    
    tab_upload_file.select(
        fn=on_tab_select,
        inputs=[input_file, input_text],
        outputs=[input_file, input_text]
    )
    tab_upload_text.select(
        fn=on_tab_select,
        inputs=[input_file, input_text],
        outputs=[input_file, input_text]
    )

请在 other_block.py 中对 tab_upload_filetab_upload_text 分别添加类似的 select 回调,确保切换时两个组件的值能够正确切换。

🧰 Tools
🪛 Ruff (0.11.9)

49-50: Use a single with statement with multiple contexts instead of nested with statements

(SIM117)


53-53: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)


54-54: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)


55-56: Use a single with statement with multiple contexts instead of nested with statements

Combine with statements

(SIM117)


57-57: Local variable tab_upload_file is assigned to but never used

Remove assignment to unused variable tab_upload_file

(F841)


63-63: Local variable tab_upload_text is assigned to but never used

Remove assignment to unused variable tab_upload_text

(F841)

🤖 Prompt for AI Agents
In hugegraph-llm/src/hugegraph_llm/demo/rag_demo/other_block.py around lines 48
to 81, the Tab components tab_upload_file and tab_upload_text lack select event
callbacks to handle tab switching. To fix this, define a callback function
similar to on_tab_select that synchronizes the values of the file and text
inputs based on the selected tab, then bind this function to both
tab_upload_file.select and tab_upload_text.select with appropriate inputs and
outputs to keep the input components consistent when switching tabs.

with gr.Accordion("Init HugeGraph test data (🚧)", open=False):
with gr.Row():
inp = []
out = gr.Textbox(label="Init Graph Demo Result", show_copy_button=True)
btn = gr.Button("(BETA) Init HugeGraph test data (🚧)")
btn.click(fn=init_hg_test_data, inputs=inp, outputs=out) # pylint: disable=no-member


@asynccontextmanager
async def lifespan(app: FastAPI): # pylint: disable=W0621
log.info("Starting background scheduler...")
Expand Down
11 changes: 11 additions & 0 deletions hugegraph-llm/src/hugegraph_llm/resources/demo/llm_review.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
- type: openai
model_name: ernie-4.5-8k-preview
api_key:
api_base:
max_tokens: 2048
Comment on lines +3 to +5

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The YAML file contains empty API keys and base URLs. Consider adding clear comments or documentation on how users should set these values or provide environment variable references instead of empty values.

Suggested change
api_key:
api_base:
max_tokens: 2048
api_key: ${OPENAI_API_KEY} # Set this to your API key or use environment variable
api_base: ${OPENAI_API_BASE} # Set this to your API base URL or use environment variable
max_tokens: 2048


- type: openai
model_name: gpt-4.1-mini
api_key:
api_base:
max_tokens: 4096
236 changes: 236 additions & 0 deletions hugegraph-llm/src/hugegraph_llm/utils/other_tool_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.

import time
import json
import re
import gradio as gr
import yaml

from hugegraph_llm.config import PromptConfig
from hugegraph_llm.utils.log import log
from hugegraph_llm.models.llms.ollama import OllamaClient
from hugegraph_llm.models.llms.openai import OpenAIClient
from hugegraph_llm.models.llms.qianfan import QianfanClient
from hugegraph_llm.models.llms.litellm import LiteLLMClient
def judge(answers, standard_answer, review_model_name, review_max_tokens, key, base):
Comment thread
MrJs133 marked this conversation as resolved.
try:
review_client = OpenAIClient(
api_key=key,
api_base=base,
model_name=review_model_name,
max_tokens=int(review_max_tokens)
)
review_prompt = PromptConfig.review_prompt.format(standard_answer=standard_answer)
for _, (model_name, answer) in enumerate(answers.items(), start=1):
review_prompt += f"### {model_name}:\n{answer.strip()}\n\n"
log.debug("Review_prompt: %s", review_prompt)
response = review_client.generate(prompt=review_prompt)
log.debug("orig_review_response: %s", response)
match = re.search(r'```json\n(.*?)\n```', response, re.DOTALL)
if match:
response = match.group(1).strip()
reviews = json.loads(response)
return reviews
Comment thread
MrJs133 marked this conversation as resolved.
Comment thread
MrJs133 marked this conversation as resolved.
except Exception as e: # pylint: disable=W0718
log.error("Review failed: %s", str(e))
reviews = {"error": f"Review error: {str(e)}"}
return reviews

def parse_llm_configurations(config_text: str):
configs = []
lines = config_text.strip().split("\n")
for i, line in enumerate(lines, 1):
fields = [x.strip() for x in line.split(",")]
if not fields:

Copilot AI May 23, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check if not fields: will never skip lines because fields is always a non-empty list; consider testing if not line.strip(): to properly skip blank or whitespace-only lines.

Suggested change
if not fields:
if not line.strip():

Copilot uses AI. Check for mistakes.
continue
llm_type = fields[0]
Comment on lines +54 to +61

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

跳过空行 / 注释行以避免误解析

line.split(",") 即使原行为空,也会得到长度为 1 的 [""],接下来会误进入各分支并抛 “字段数量不足” 异常。

-    lines = config_text.strip().split("\n")
+    lines = [l for l in config_text.split("\n") if l.strip() and not l.strip().startswith("#")]

这样能容忍用户在文本中添加空行或 # 开头的注释。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def parse_llm_configurations(config_text: str):
configs = []
lines = config_text.strip().split("\n")
for i, line in enumerate(lines, 1):
fields = [x.strip() for x in line.split(",")]
if not fields:
continue
llm_type = fields[0]
def parse_llm_configurations(config_text: str):
configs = []
- lines = config_text.strip().split("\n")
+ lines = [l for l in config_text.split("\n") if l.strip() and not l.strip().startswith("#")]
for i, line in enumerate(lines, 1):
fields = [x.strip() for x in line.split(",")]
if not fields:
continue
llm_type = fields[0]
# …
🤖 Prompt for AI Agents
In hugegraph-llm/src/hugegraph_llm/utils/other_tool_utils.py around lines 54 to
61, the current code does not properly skip empty lines or comment lines
starting with '#', causing incorrect parsing and potential "insufficient fields"
errors. Modify the loop to explicitly skip lines that are empty after stripping
or that start with '#' before splitting and processing them, ensuring these
lines do not cause parsing errors.

try:
if llm_type == "openai":
# openai, model_name, api_key, api_base, max_tokens
model_name, api_key, api_base, max_tokens = fields[1:5]
configs.append({
"type": "openai",
"model_name": model_name,
"api_key": api_key,
"api_base": api_base,
"max_tokens": int(max_tokens),
})
elif llm_type == "qianfan_wenxin":
# qianfan_wenxin, model_name, api_key, secret_key
model_name, api_key, secret_key = fields[1:4]
configs.append({
"type": "qianfan_wenxin",
"model_name": model_name,
"api_key": api_key,
"secret_key": secret_key,
})
elif llm_type == "ollama/local":
# ollama/local, model_name, host, port, max_tokens
model_name, host, port, max_tokens = fields[1:5]
configs.append({
"type": "ollama/local",
"model_name": model_name,
"host": host,
"port": int(port),
"max_tokens": int(max_tokens),
})
elif llm_type == "litellm":
# litellm, model_name, api_key, api_base, max_tokens
model_name, api_key, api_base, max_tokens = fields[1:5]
configs.append({
"type": "litellm",
"model_name": model_name,
"api_key": api_key,
"api_base": api_base,
"max_tokens": int(max_tokens),
})
else:
raise ValueError(f"Unsupported llm type '{llm_type}' in line {i}")
except Exception as e:
Comment thread
MrJs133 marked this conversation as resolved.
raise ValueError(f"Error parsing line {i}: {line}\nDetails: {e}") from e
return configs

def parse_llm_configurations_from_yaml(yaml_file_path: str):
configs = []
with open(yaml_file_path, "r", encoding="utf-8") as f:
raw_configs = yaml.safe_load(f)
if not isinstance(raw_configs, list):
raise ValueError("YAML 文件内容必须是一个 LLM 配置列表。")
for i, config in enumerate(raw_configs, 1):
try:
llm_type = config.get("type")
if llm_type == "openai":
configs.append({
"type": "openai",
"model_name": config["model_name"],
"api_key": config["api_key"],
"api_base": config["api_base"],
"max_tokens": int(config["max_tokens"]),
})
elif llm_type == "qianfan_wenxin":
configs.append({
"type": "qianfan_wenxin",
"model_name": config["model_name"],
"api_key": config["api_key"],
"secret_key": config["secret_key"],
})
elif llm_type == "ollama/local":
configs.append({
"type": "ollama/local",
"model_name": config["model_name"],
"host": config["host"],
"port": int(config["port"]),
"max_tokens": int(config["max_tokens"]),
})
elif llm_type == "litellm":
configs.append({
"type": "litellm",
"model_name": config["model_name"],
"api_key": config["api_key"],
"api_base": config["api_base"],
"max_tokens": int(config["max_tokens"]),
})
else:
raise ValueError(f"不支持的 llm type '{llm_type}',在配置第 {i} 项")
except Exception as e:
raise ValueError(f"解析配置第 {i} 项失败: {e}") from e
Comment thread
MrJs133 marked this conversation as resolved.

return configs


def auto_test_llms(
llm_configs,
llm_configs_file,
prompt,
standard_answer,
review_model_name,
review_max_tokens,
key,
base,
fmt=True
):
configs = None
if llm_configs_file and llm_configs:
raise gr.Error("Please only choose one between file and text.")
if llm_configs:
configs = parse_llm_configurations(llm_configs)
elif llm_configs_file:
configs = parse_llm_configurations_from_yaml(llm_configs_file)
log.debug("LLM_configs: %s", configs)
answers = {}
for config in configs:
output = None
Comment on lines +175 to +177

Copilot AI May 23, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LLM requests are made sequentially, which could increase total latency; consider running these calls concurrently (e.g., with asyncio or threads) to improve throughput.

Suggested change
answers = {}
for config in configs:
output = None
async def generate_output(config):

Copilot uses AI. Check for mistakes.
time_start = time.perf_counter()
try:
if config["type"] == "openai":
client = OpenAIClient(
api_key=config["api_key"],
api_base=config["api_base"],
model_name=config["model_name"],
max_tokens=config["max_tokens"],
)
output = client.generate(prompt=prompt)
elif config["type"] == "qianfan_wenxin":
client = QianfanClient(
model_name=config["model_name"],
api_key=config["api_key"],
secret_key=config["secret_key"]
)
output = client.generate(prompt=prompt)
elif config["type"] == "ollama/local":
client = OllamaClient(
model_name=config["model_name"],
host=config["host"],
port=config["port"],
)
output = client.generate(prompt=prompt)
elif config["type"] == "litellm":
client = LiteLLMClient(
api_key=config["api_key"],
api_base=config["api_base"],
model_name=config["model_name"],
max_tokens=config["max_tokens"],
)
output = client.generate(prompt=prompt)
except Exception as e: # pylint: disable=broad-except
log.error("Generate failed for %s: %s", config["model_name"], e)
output = f"[ERROR] {e}"
time_end = time.perf_counter()
latency = time_end - time_start
answers[config["model_name"]] = {
"answer": output,
"latency": f"{round(latency, 2)}s"
}
reviews = judge(
{k: v["answer"] for k, v in answers.items()},
standard_answer,
review_model_name,
review_max_tokens,
key,
base
)
log.debug("reviews: %s", reviews)
result = {}
reviews_dict = {item["model"]: item for item in reviews} if isinstance(reviews, list) else reviews
for model_name, infos in answers.items():
result[model_name] = {
"answer": infos["answer"],
"latency": infos["latency"],
"review": reviews_dict.get(model_name, {})
}
return json.dumps(result, indent=4, ensure_ascii=False) if fmt else reviews
Comment on lines +214 to +236

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function is not validating that the returned reviews match the expected format before trying to transform them. This could lead to errors if the review model doesn't return data in the expected format.

Suggested change
latency = time_end - time_start
answers[config["model_name"]] = {
"answer": output,
"latency": f"{round(latency, 2)}s"
}
reviews = judge(
{k: v["answer"] for k, v in answers.items()},
standard_answer,
review_model_name,
review_max_tokens,
key,
base
)
log.debug("reviews: %s", reviews)
result = {}
reviews_dict = {item["model"]: item for item in reviews} if isinstance(reviews, list) else reviews
for model_name, infos in answers.items():
result[model_name] = {
"answer": infos["answer"],
"latency": infos["latency"],
"review": reviews_dict.get(model_name, {})
}
return json.dumps(result, indent=4, ensure_ascii=False) if fmt else reviews
reviews = judge(
{k: v["answer"] for k, v in answers.items()},
standard_answer,
review_model_name,
review_max_tokens,
key,
base
)
log.debug("reviews: %s", reviews)
# Validate reviews format
if isinstance(reviews, dict) and "error" in reviews:
# Handle error case
result = {}
for model_name, infos in answers.items():
result[model_name] = {
"answer": infos["answer"],
"latency": infos["latency"],
"review": {"error": reviews["error"]}
}
return json.dumps(result, indent=4, ensure_ascii=False) if fmt else reviews
# Process valid reviews
result = {}
reviews_dict = {item["model"]: item for item in reviews} if isinstance(reviews, list) else reviews
for model_name, infos in answers.items():
result[model_name] = {
"answer": infos["answer"],
"latency": infos["latency"],
"review": reviews_dict.get(model_name, {})
}