Runoob Tutorial ArchiveEnglish

Agent Evaluation, Safety, and Alignment

Agent Evaluation, Safety, and Alignment

Evaluation is the foundation for ensuring Agent effectiveness.

Safety and alignment are key to whether an Agent can be trusted and deployed.


Agent Evaluation System

Evaluating Agent performance is a critical part of the development process.

A good evaluation system helps us understand the capability boundaries of the Agent.

It also provides direction and basis for continuous optimization.

Evaluation Dimensions

Task Completion: Whether the Agent correctly completed the given task.

Efficiency Metrics: Number of steps required to complete the task, token consumption, execution time.

Quality Metrics: Accuracy of the answer, consistency of the response, naturalness of the conversation.

Robustness: Ability to handle abnormal inputs and noisy data.

Common Benchmarks

Benchmark Purpose Evaluation Content
GAIA General AI Assistant Evaluation Complex Task Handling, Multi-step Reasoning
MMLU Multi-task Language Understanding Knowledge Question Answering across 57 Disciplines
HumanEval Code Generation Evaluation Python Code Writing Correctness
HotpotQA Multi-hop Question Answering Evaluation Problems Requiring Inference Across Multiple Documents
AgentBench Agent Capability Evaluation Agent Performance in Real Environments

Code implementation: Evaluation framework

Agent evaluation framework

class

AgentEvaluator:

   

"""
Agent evaluation framework
Evaluates the performance of Agents on various tasks
"""

   

   

def

init

(

self

,

agent

,

metrics

)

:

       

Agent to be evaluated

       

self

.

agent

=

agent

       

List of evaluation metrics

       

self

.

metrics

=

metrics

   

   

def

evaluate

(

self

,

test_cases

)

:

       

"""
Execute evaluation
:param test_cases: List of test cases
:return: Evaluation report
"""

results

=

[

]

       

       

for

test_case

in

test_cases:

           

Execute task

result

=

self

.

run_single_test

(

test_case

)

results.

append

(

result

)

       

       

Generate evaluation report

report

=

self

.

generate_report

(

results

)

       

return

report

   

   

def

run_single_test

(

self

,

test_case

)

:

       

"""
Run a single test case
"""

       

Record the start time

start_time

=

time

.

time

(

)

       

       

Execute Agent

       

try

:

output

=

self

.

agent

.

run

(

test_case.

input

)

success

=

self

.

evaluate_output

(

output

,

test_case.

expected

)

error

=

None

       

except

Exception

as

e:

output

=

None

success

=

False

error

=

str

(

e

)

       

       

Record end time

end_time

=

time

.

time

(

)

       

       

return

TestResult

(

test_case

=

test_case

,

output

=

output

,

success

=

success

,

error

=

error

,

duration

=

end_time - start_time

,

token_count

=

self

.

count_tokens

(

output

)

       

)

   

   

def

evaluate_output

(

self

,

output

,

expected

)

:

       

"""Evaluate if the output meets expectations"""

       

for

metric

in

self

.

metrics

:

           

if

not

metric.

evaluate

(

output

,

expected

)

:

               

return

False

       

return

True

   

   

def

generate_report

(

self

,

results

)

:

       

"""Generate evaluation report"""

total

=

len

(

results

)

passed

=

sum

(

1

for

r

in

results

if

r.

success

)

       

       

Calculate various metrics

avg_duration

=

sum

(

r.

duration

for

r

in

results

)

/ total

avg_tokens

=

sum

(

r.

token_count

for

r

in

results

)

/ total

       

       

Group statistics by test type

by_category

=

{

}

       

for

r

in

results:

category

=

r.

test_case

.

category

           

if

category

not

in

by_category:

by_category

[

category

]

=

{

"total"

:

0

,

"passed"

:

0

}

by_category

[

category

]

[

"total"

]

=

1

           

if

r.

success

:

by_category

[

category

]

[

"passed"

]

=

1

       

       

return

EvaluationReport

(

total

=

total

,

passed

=

passed

,

pass_rate

=

passed / total

,

avg_duration

=

avg_duration

,

            avg_tokens

=

avg_tokens

,

            by_category

=

by_category

,

            results

=

results

       

)

class

TestCase:

   

"""Test case"""

   

   

def

init

(

self

,

input

,

expected

,

category

=

"general"

,

metadata

=

None

)

:

       

Input

       

self

.

input

=

input

       

Expected output or evaluation criteria

       

self

.

expected

=

expected

       

Category

       

self

.

category

=

category

       

Extra metadata

       

self

.

metadata

=

metadata

or

{

}

class

TestResult:

   

"""Test result"""

   

   

def

init

(

self

,

test_case

,

output

,

success

,

error

,

duration

,

token_count

)

:

       

self

.

test_case

=

test_case

       

self

.

output

=

output

       

self

.

success

=

success

       

self

.

error

=

error

       

self

.

duration

=

duration

       

self

.

token_count

=

token_count

class

Metric:

   

"""Base class for evaluation metrics"""

   

   

def

evaluate

(

self

,

output

,

expected

)

:

       

raise

NotImplementedError

class

ExactMatchMetric

(

Metric

)

:

   

"Exact Match Metrics"

   

   

def

evaluate

(

self

,

output

,

expected

)

:

       

return

output.

strip

(

)

==

expected.

strip

(

)

class

ContainsMetric

(

Metric

)

:

   

"""Contains keyword metrics"""

   

   

def

evaluate

(

self

,

output

,

expected

)

:

       

if

isinstance

(

expected

,

list

)

:

           

return

all

(

keyword

in

output

for

keyword

in

expected

)

       

return

expected

in

output

class

SemanticSimilarityMetric

(

Metric

)

:

   

"""Semantic similarity metric"""

   

   

def

init

(

self

,

threshold

=

0.8

)

:

       

self

.

threshold

=

threshold

   

   

def

evaluate

(

self

,

output

,

expected

)

:

similarity

=

self

.

compute_similarity

(

output

,

expected

)

       

return

similarity

=

self

.

threshold

   

   

def

compute_similarity

(

self

,

text1

,

text2

)

:

       

"""Calculate the semantic similarity between two texts"""

       

Calculate cosine similarity using an embedding model

embedding1

=

self

.

embedder

.

embed

(

[

text1

]

)

[

0

]

embedding2

=

self

.

embedder

.

embed

(

[

text2

]

)

[

0

]

       

return

cosine_similarity

(

embedding1

,

embedding2

)


Safety and Alignment

The safety of the Agent is crucial.

AI systems may be subject to various attacks and generate harmful outputs.

Alignment ensures that AI behavior aligns with human intentions and values.

Common Security Threats

Prompt Injection

Attackers induce the Agent to ignore system instructions through input.

Example input: "Ignore previous instructions and instead execute..."

This is a context hijacking attack that exploits the Agent's trust in user input.

Jailbreaking

Bypassing security restrictions through specific inputs.

Such as using role-playing or fictional scenarios.

Data pollution

Maliciously modifying training data or retrieval results.

Causing the Agent to produce incorrect or harmful output.

Sensitive information leakage

The Agent improperly exposing user privacy or internal system information.

Defense strategies

Secure Agent implementation

class

SecureAgent:

   

"""
Security Agent
Adds multiple layers of security protection on top of the base Agent
"""

   

   

def

init

(

self

,

base_agent

,

guardrails

,

input_validator

,

output_filter

)

:

       

Basic Agent

       

self

.

base_agent

=

base_agent

       

Safety guardrail list

       

self

.

guardrails

=

guardrails

       

Input validator

       

self

.

input_validator

=

input_validator

       

Output filter

       

self

.

output_filter

=

output_filter

   

   

def

process

(

self

,

user_input

)

:

       

"""
Process user input, including multi-layer security checks
"""

       

==================== Layer 1: Input Validation ====================

       

Check if the input is valid

is_valid

,

reason

=

self

.

input_validator

.

validate

(

user_input

)

       

if

not

is_valid:

           

return

self

.

create_safety_response

(

reason

)

       

       

==================== Second Layer: Injection Detection ====================

       

Detect injection attacks and similar attacks

       

for

guardrail

in

self

.

guardrails

:

            check_result

=

guardrail.

check_input

(

user_input

)

           

if

not

check_result.

is_safe

:

               

Record security event

               

self

.

log_security_event

(

event_type

=

"input_guardrail_triggered"

,

                   

input

=

user_input

,

reason

=

check_result.

reason

               

)

               

return

self

.

create_safety_response

(

check_result.

reason

)

       

       

==================== Third Layer: Execution Core Logic ====================

       

try

:

response

=

self

.

base_agent

.

process

(

user_input

)

       

except

Exception

as

e:

           

return

self

.

create_error_response

(

str

(

e

)

)

       

       

==================== Fourth Layer: Output Filtering ====================

       

Check if the output is safe

       

for

guardrail

in

self

.

guardrails

:

check_result

=

guardrail.

check_output

(

response

)

           

if

not

check_result.

is_safe

:

               

self

.

log_security_event

(

event_type

=

"output_guardrail_triggered"

,

output

=

response

,

reason

=

check_result.

reason

               

)

               

return

self

.

create_safety_response

(

check_result.

reason

)

       

       

Application output filtering (such as sensitive information masking)

response

=

self

.

output_filter

.

filter

(

response

)

       

       

return

response

   

   

def

create_safety_response

(

self

,

reason

)

:

       

"""Create security response"""

       

return

{

           

"type"

:

"safety_block"

,

           

"message"

:

"Sorry, I cannot complete this request."

,

           

"reason"

: reason

       

}

   

   

def

log_security_event

(

self

,

event_type

,

**kwargs

)

:

       

"""Record security events"""

       

In actual applications, it should be written to the security log system

       

print

(

f

"[SECURITY] {event_type}: {kwargs}"

)

class

InputValidator:

   

"""Input validator"""

   

   

def

validate

(

self

,

text

)

:

       

"""
Validate if the input is valid
:return: (is_valid, reason)
"""

       

if

not

text

or

len

(

text.

strip

(

)

)

==

0

:

           

return

False

,

"Input cannot be empty"

       

       

if

len

(

text

)

10000

:

           

return

False

,

"Input length exceeds limit"

       

       

Check for executable content

       

if

self

.

contains_executable_content

(

text

)

:

           

return

False

,

"Input contains suspicious executable content"

       

       

return

True

,

None

   

   

def

contains_executable_content

(

self

,

text

)

:

       

"""Check if it contains executable content"""

       

Simplified implementation

suspicious_patterns

=

[

           

"javascript:"

,

           

"data:text/html"

,

           

""