引言
在AI对话系统开发中,有时候让AI助手能够根据不同场景动态调整其对话风格。本文将介绍如何使用OpenAI Agents框架实现动态系统提示,让AI助手能够以不同的人格特征进行对话。
完整代码
import asyncio
import random
from typing import Literal
from agents import Agent, RunContextWrapper, Runner
from agents import Agent, Runner,RunConfig,OpenAIProvider
run_config = RunConfig(model_provider = OpenAIProvider(
api_key="your api key",
base_url="https://open.bigmodel.cn/api/paas/v4/",
use_responses=False,
)
)
class CustomContext:
def __init__(self, style: Literal["haiku", "pirate", "robot"]):
self.style = style
def custom_instructions(
run_context: RunContextWrapper[CustomContext], agent: Agent[CustomContext]
) -> str:
context = run_context.context
if context.style == "haiku":
return "Only respond in haikus."
elif context.style == "pirate":
return "Respond as a pirate."
else:
return "Respond as a robot and say 'beep boop' a lot."
agent = Agent(
name="Chat agent",
instructions=custom_instructions,
model="glm-4-flash"
)
async def main():
choice: Literal["haiku", "pirate", "robot"] = random.choice(["haiku", "pirate", "robot"])
context = CustomContext(style=choice)
print(f"Using style: {choice}\n")
user_message = "Tell me a joke."
print(f"User: {user_message}")
result = await Runner.run(agent, user_message, context=context,run_config=run_config)
print(f"Assistant: {result.final_output}")
if __name__ == "__main__":
asyncio.run(main())
"""
$python .My_test\dynamic_system_prompt_test.py
Using style: robot
User: Tell me a joke.
Assistant: Beep boop beep boop. Why don't scientists trust atoms? Because they make up everything!
Beep boop beep boop.
OPENAI_API_KEY is not set, skipping trace export
$python .My_test\dynamic_system_prompt_test.py
Using style: pirate
User: Tell me a joke.
Assistant: Arr, me hearties, here be a scallywag's jest for ye:
Why did the pirate hide his treasure on an island?
Because he wanted to keep it on a secret shire! Arr, arr, and arr!
OPENAI_API_KEY is not set, skipping trace export
"""
核心功能实现
1. 自定义上下文管理
class CustomContext:
def __init__(self, style: Literal["haiku", "pirate", "robot"]):
self.style = style
通过自定义上下文类,我们可以定义不同的对话风格,包括:
- 俳句风格(haiku)
- 海盗风格(pirate)
- 机器人风格(robot)
2. 动态指令生成
def custom_instructions(
run_context: RunContextWrapper[CustomContext],
agent: Agent[CustomContext]
) -> str:
context = run_context.context
if context.style == "haiku":
return "Only respond in haikus."
elif context.style == "pirate":
return "Respond as a pirate."
else:
return "Respond as a robot and say 'beep boop' a lot."
技术特点
1. 灵活的风格切换
- 随机选择对话风格
- 运行时动态调整系统提示
- 保持对话的连贯性
2. 异步处理
使用asyncio
实现异步操作,提高系统响应效率:
async def main():
choice = random.choice(["haiku", "pirate", "robot"])
context = CustomContext(style=choice)
3. 交互式体验
- 清晰的用户输入输出
- 实时风格切换提示
- 个性化的回答格式
应用场景
-
教育领域
- 多样化的教学风格
- 趣味性学习体验
- 个性化教学助手
-
娱乐应用
- 角色扮演游戏
- 创意写作助手
- 互动故事生成
-
客户服务
- 场景化客服回答
- 个性化用户体验
- 多样化沟通方式
实现效果
机器人风格示例
Using style: robot
User: Tell me a joke.
Assistant: Beep boop beep boop. Why don't scientists trust atoms?
Because they make up everything!
海盗风格示例
Using style: pirate
User: Tell me a joke.
Assistant: Arr, me hearties, here be a scallywag's jest for ye:
Why did the pirate hide his treasure on an island?
Because he wanted to keep it on a secret shire!
最佳实践
-
风格定义
- 明确的风格特征
- 一致的语言模式
- 适当的角色设定
-
代码组织
- 模块化设计
- 清晰的类型注解
- 可扩展的结构
-
错误处理
- 优雅的异常处理
- 完整的日志记录
- 用户友好的提示
总结
通过OpenAI Agents框架实现的动态系统提示功能,不仅提供了灵活的对话风格切换能力,还为AI应用开发提供了新的可能性。这种方法可以广泛应用于教育、娱乐、客服等多个领域。