Spaces:
Sleeping
Sleeping
Create agents.py
Browse files- whale_core/agents.py +47 -0
whale_core/agents.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
import openai
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# β
Set your OpenAI API key β use one of the two options below:
|
| 6 |
+
|
| 7 |
+
# π Option 1: Load from environment variable (recommended)
|
| 8 |
+
openai.api_key = "sk-z4C5B-O9hxSANw9drYaooVsp7SdXPw4Z29LUGkJEQhT3BlbkFJ0o-Gh0ALs1R5Zhiuchz-tn3bB_HizEuCx7s2xO_acA"
|
| 9 |
+
|
| 10 |
+
# π§ͺ Optional: fail early if key not set
|
| 11 |
+
if not openai.api_key:
|
| 12 |
+
raise ValueError("β No OpenAI API key found. Set the environment variable OPENAI_API_KEY.")
|
| 13 |
+
|
| 14 |
+
# π Option 2 (for development only): Hardcode the key
|
| 15 |
+
# openai.api_key = "sk-...your full key..."
|
| 16 |
+
|
| 17 |
+
# β
Load agent configurations from YAML
|
| 18 |
+
def load_agents(path="agents/config.yaml"):
|
| 19 |
+
with open(path, "r") as f:
|
| 20 |
+
return yaml.safe_load(f)
|
| 21 |
+
|
| 22 |
+
# β
Run each agent on the input document
|
| 23 |
+
def run_agents_on_text(agent_cfgs, doc):
|
| 24 |
+
responses = {}
|
| 25 |
+
|
| 26 |
+
for agent in agent_cfgs.get("agents", []):
|
| 27 |
+
name = agent.get("name", "UnnamedAgent")
|
| 28 |
+
system_msg = agent.get("persona", "You are a helpful assistant.")
|
| 29 |
+
instructions = agent.get("instructions", "Please analyze this document.")
|
| 30 |
+
user_prompt = f"{instructions}\n\nDocument:\n{doc[:4000]}" # Use full text or chunk
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
completion = openai.ChatCompletion.create(
|
| 34 |
+
model="gpt-4",
|
| 35 |
+
messages=[
|
| 36 |
+
{"role": "system", "content": system_msg},
|
| 37 |
+
{"role": "user", "content": user_prompt}
|
| 38 |
+
],
|
| 39 |
+
max_tokens=300,
|
| 40 |
+
temperature=0.7
|
| 41 |
+
)
|
| 42 |
+
responses[name] = completion.choices[0].message["content"].strip()
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
responses[name] = f"β οΈ Error calling OpenAI: {str(e)}"
|
| 46 |
+
|
| 47 |
+
return responses
|