Skip to content

Commit

Permalink
fix: Fix example.ts, example.py, and example.js files
Browse files Browse the repository at this point in the history
  • Loading branch information
creatorrr committed Oct 8, 2024
1 parent 650e588 commit 966f7d8
Show file tree
Hide file tree
Showing 3 changed files with 343 additions and 179 deletions.
130 changes: 130 additions & 0 deletions example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
const { Julep } = require('@julep/sdk');
const yaml = require('js-yaml');
const readline = require('readline');

const client = new Julep({ apiKey: 'your_julep_api_key' });

async function createAgent() {
const agent = await client.agents.create({
name: "Storytelling Agent",
model: "gpt-4",
about: "You are a creative storytelling agent that can craft engaging stories and generate comic panels based on ideas.",
});

// 🛠️ Add an image generation tool (DALL·E) to the agent
await client.agents.tools.create(agent.id, {
name: "image_generator",
description: "Use this tool to generate images based on descriptions.",
integration: {
provider: "dalle",
method: "generate_image",
setup: {
api_key: "your_openai_api_key",
},
},
});

return agent;
}

const taskYaml = `
name: Story and Comic Creator
description: Create a story based on an idea and generate a 4-panel comic strip illustrating the story.
main:
# Step 1: Generate a story and outline into 4 panels
- prompt:
- role: system
content: You are {{agent.name}}. {{agent.about}}
- role: user
content: >
Based on the idea '{{_.idea}}', write a short story suitable for a 4-panel comic strip.
Provide the story and a numbered list of 4 brief descriptions for each panel illustrating key moments in the story.
unwrap: true
# Step 2: Extract the panel descriptions and story
- evaluate:
story: _.split('1. ')[0].trim()
panels: _.match(/\\d+\\.\\s*(.*?)(?=\\d+\\.\\s*|$)/g)
# Step 3: Generate images for each panel using the image generator tool
- foreach:
in: _.panels
do:
tool: image_generator
arguments:
description: _
# Step 4: Generate a catchy title for the story
- prompt:
- role: system
content: You are {{agent.name}}. {{agent.about}}
- role: user
content: >
Based on the story below, generate a catchy title.
Story: {{outputs[1].story}}
unwrap: true
# Step 5: Return the story, the generated images, and the title
- return:
title: outputs[3]
story: outputs[1].story
comic_panels: outputs[2].map(output => output.image.url)
`;

async function createTask(agent) {
const task = await client.tasks.create(agent.id, yaml.load(taskYaml));
return task;
}

async function executeTask(task) {
const execution = await client.executions.create(task.id, {
input: { idea: "A cat who learns to fly" }
});

// 🎉 Watch as the story and comic panels are generated
for await (const transition of client.executions.transitions.stream(execution.id)) {
console.log(transition);
}

// 📦 Once the execution is finished, retrieve the results
const result = await client.executions.get(execution.id);
return result;
}

async function chatWithAgent(agent) {
const session = await client.sessions.create({ agent_id: agent.id });

// 💬 Send messages to the agent
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

const chat = async () => {
rl.question("Enter a message (or 'quit' to exit): ", async (message) => {
if (message.toLowerCase() === 'quit') {
rl.close();
return;
}

const response = await client.sessions.chat(session.id, { message });
console.log(response);
chat();
});
};

chat();
}

// Run the example
async function runExample() {
const agent = await createAgent();
const task = await createTask(agent);
const result = await executeTask(task);
console.log("Task Result:", result);
await chatWithAgent(agent);
}

runExample().catch(console.error);
168 changes: 85 additions & 83 deletions example.py
Original file line number Diff line number Diff line change
@@ -1,107 +1,109 @@
from julep import Julep, AsyncJulep
import yaml
from julep import Julep

# 🔑 Initialize the Julep client
# Or alternatively, use AsyncJulep for async operations
client = Julep(api_key="your_api_key")
# Initialize the Julep client
client = Julep(api_key="your_julep_api_key")

##################
## 🤖 Agent 🤖 ##
##################

# Create a research agent
# Step 1: Create an Agent
agent = client.agents.create(
name="Research Agent",
about="You are a research agent designed to handle research inquiries.",
model="claude-3.5-sonnet",
name="Storytelling Agent",
model="gpt-4",
about="You are a creative storytelling agent that can craft engaging stories and generate comic panels based on ideas.",
)

# 🔍 Add a web search tool to the agent
# Add an image generation tool (DALL·E) to the agent
client.agents.tools.create(
agent_id=agent.id,
name="web_search", # Should be python valid variable name
description="Use this tool to research inquiries.",
name="image_generator",
description="Use this tool to generate images based on descriptions.",
integration={
"provider": "brave",
"method": "search",
"provider": "dalle",
"method": "generate_image",
"setup": {
"api_key": "your_brave_api_key",
"api_key": "your_openai_api_key",
},
},
)

#################
## 💬 Chat 💬 ##
#################
# Step 2: Create a Task that generates a story and comic strip
task_yaml = """
name: Story and Comic Creator
description: Create a story based on an idea and generate a 4-panel comic strip illustrating the story.
# Start an interactive chat session with the agent
session = client.sessions.create(
agent_id=agent.id,
context_overflow="adaptive", # 🧠 Julep will dynamically compute the context window if needed
)
main:
# Step 1: Generate a story and outline into 4 panels
- prompt:
- role: system
content: You are {{agent.name}}. {{agent.about}}
- role: user
content: >
Based on the idea '{{_.idea}}', write a short story suitable for a 4-panel comic strip.
Provide the story and a numbered list of 4 brief descriptions for each panel illustrating key moments in the story.
unwrap: true
# 🔄 Chat loop
while (user_input := input("You: ")) != "exit":
response = client.sessions.chat(
session_id=session.id,
message=user_input,
)
# Step 2: Extract the panel descriptions and story
- evaluate:
story: _.split('1. ')[0].strip()
panels: re.findall(r'\\d+\\.\\s*(.*?)(?=\\d+\\.\\s*|$)', _)
# Step 3: Generate images for each panel using the image generator tool
- foreach:
in: _.panels
do:
tool: image_generator
arguments:
description: _
print("Agent: ", response.choices[0].message.content)
# Step 4: Generate a catchy title for the story
- prompt:
- role: system
content: You are {{agent.name}}. {{agent.about}}
- role: user
content: >
Based on the story below, generate a catchy title.
Story: {{outputs[1].story}}
unwrap: true
#################
## 📋 Task 📋 ##
#################
# Step 5: Return the story, the generated images, and the title
- return:
title: outputs[3]
story: outputs[1].story
comic_panels: "[output.image.url for output in outputs[2]]"
"""

# Create a recurring research task for the agent
task = client.tasks.create(
agent_id=agent.id,
name="Research Task",
description="Research the given topic every 24 hours.",
#
# 🛠️ Task specific tools
tools=[
{
"name": "send_email",
"description": "Send an email to the user with the results.",
"api_call": {
"method": "post",
"url": "https://api.sendgrid.com/v3/mail/send",
"headers": {"Authorization": "Bearer YOUR_SENDGRID_API_KEY"},
},
}
],
#
# 🔢 Task main steps
main=[
#
# Step 1: Research the topic
{
# `_` (underscore) variable refers to the previous step's output
# Here, it points to the topic input from the user
"prompt": "Look up topic '{{_.topic}}' and summarize the results.",
"tools": [{"ref": {"name": "web_search"}}], # 🔍 Use the web search tool from the agent
"unwrap": True,
},
#
# Step 2: Send email with research results
{
"tool": "send_email",
"arguments": {
"subject": "Research Results",
"body": "'Here are the research results for today: ' + _.content",
"to": "inputs[0].email", # Reference the email from the user's input
},
},
#
# Step 3: Wait for 24 hours before repeating
{"sleep": "24 * 60 * 60"},
],
**yaml.safe_load(task_yaml)
)

# 🚀 Start the recurring task
client.executions.create(task_id=task.id, input={"topic": "Python"})
# Step 3: Execute the Task
execution = client.executions.create(
task_id=task.id,
input={"idea": "A cat who learns to fly"}
)

# Watch as the story and comic panels are generated
for transition in client.executions.transitions.stream(execution_id=execution.id):
print(transition)

# Once the execution is finished, retrieve the results
result = client.executions.get(execution_id=execution.id)
print("Task Result:", result)

# Step 4: Chat with the Agent
session = client.sessions.create(agent_id=agent.id)

# Send messages to the agent
while True:
message = input("Enter a message (or 'quit' to exit): ")
if message.lower() == 'quit':
break

response = client.sessions.chat(
session_id=session.id,
message=message,
)
print("Agent:", response.choices[0].message.content)

# 🔁 This will run the task every 24 hours,
# research for the topic "Python", and
# send the results to the user's email
print("Chat session ended.")
Loading

0 comments on commit 966f7d8

Please sign in to comment.