import openai
import random
import io
import sys
import requests
import json
# 改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=’utf8’)
# 示例用法
api_key = "****************************************************" # 替换为你的 API 密钥
openai.api_key = api_key
class Leader:
def __init__(self):
self.task = None
def create_task(self, prompt):
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "你是一个非常有用的智能助手."},
{"role": "user", "content": prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
return response.json()[’choices’][0][’message’][’content’]
else:
return f"Error: {response.text}"
class Agent:
def __init__(self, name):
self.name = name
def complete_task(self, task):
completion_prompt = f"{self.name} 需要一个有效的解决方案为了这个任务: {task}"
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "你是一个非常有用的智能助手."},
{"role": "user", "content": completion_prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
solution=response.json()[’choices’][0][’message’][’content’]
else:
solution=f"Error: {response.text}"
print(f"\n\n{self.name} 完成了任务: ")
print(f"解决方案: {solution}")
return solution
class Evaluator:
def evaluate(self, task, solutions):
prompt = f"对以下任务{task}的两种解决方案进行评分: 方案1: {solutions[0]},方案2: {solutions[1]}"
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "你是一个非常有用的智能助手."},
{"role": "user", "content": prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
return response.json()[’choices’][0][’message’][’content’]
else:
return f"Error: {response.text}"
# 示例执行流程
leader = Leader()
agent1 = Agent("B1")
agent2 = Agent("B2")
evaluator = Evaluator()
task_prompt = "初中阶段有效提高学生英语听力的方法"
task = leader.create_task(task_prompt)
print(f"任务: {task}")
solution1 = agent1.complete_task(task)
solution2 = agent2.complete_task(task)
scores = evaluator.evaluate(task, [solution1, solution2])
print(f"\n\n得分: {scores}")