Skip to content

Commit 9eccd8d

Browse files
committed
🐛 FIX: agent examples
1 parent 12c4e1e commit 9eccd8d

File tree

3 files changed

+150
-142
lines changed

3 files changed

+150
-142
lines changed

examples/agent/agent.run.memory.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"""
66

77
import os
8+
from io import BytesIO
89

910
from dotenv import load_dotenv
1011

@@ -59,28 +60,32 @@ def create_memory():
5960
langbase_api_key = os.environ.get("LANGBASE_API_KEY")
6061
langbase = Langbase(api_key=langbase_api_key)
6162

62-
if not langbase.memories.list():
63+
memories = langbase.memories.list()
64+
memory_names = [memory["name"] for memory in memories]
65+
career_advisor_memory_name = "career-advisor-memory"
66+
67+
if career_advisor_memory_name not in memory_names:
6368
memory = langbase.memories.create(
6469
name="career-advisor-memory",
6570
description="A memory for the career advisor agent",
6671
)
6772

6873
print("Memory created: ", memory)
6974

70-
content = """
71-
An AI Engineer is a software engineer who specializes in building AI systems.
72-
"""
75+
content = """
76+
An AI Engineer is a software engineer who specializes in building AI systems.
77+
"""
7378

74-
langbase.memories.documents.upload(
75-
memory_name="career-advisor-memory",
76-
document_name="career-advisor-document",
77-
document=content,
78-
content_type="text/plain",
79-
)
79+
content_buffer = BytesIO(content.encode("utf-8"))
80+
81+
langbase.memories.documents.upload(
82+
memory_name="career-advisor-memory",
83+
document_name="career-advisor-document.txt",
84+
document=content_buffer,
85+
content_type="text/plain",
86+
)
8087

81-
print("Document uploaded")
82-
else:
83-
print("Memory already exists")
88+
print("Document uploaded")
8489

8590

8691
if __name__ == "__main__":

examples/agent/agent.run.tool.py

Lines changed: 52 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,23 @@ def send_email(args):
4646
html = args.get("html")
4747
text = args.get("text")
4848

49-
response = requests.post(
50-
"https://api.resend.com/emails",
51-
headers={
52-
"Authorization": f"Bearer {os.environ.get('RESEND_API_KEY')}",
53-
"Content-Type": "application/json",
54-
},
55-
json={
56-
"from": from_email,
57-
"to": to_email,
58-
"subject": subject,
59-
"html": html,
60-
"text": text,
61-
},
62-
)
63-
64-
if not response.ok:
65-
raise Exception("Failed to send email")
49+
# response = requests.post(
50+
# "https://api.resend.com/emails",
51+
# headers={
52+
# "Authorization": f"Bearer {os.environ.get('RESEND_API_KEY')}",
53+
# "Content-Type": "application/json",
54+
# },
55+
# json={
56+
# "from": from_email,
57+
# "to": to_email,
58+
# "subject": subject,
59+
# "html": html,
60+
# "text": text,
61+
# },
62+
# )
63+
64+
# if not response.ok:
65+
# raise Exception("Failed to send email")
6666

6767
return f"✅ Email sent successfully to {to_email}!"
6868

@@ -71,7 +71,7 @@ def main():
7171
# Check for required environment variables
7272
langbase_api_key = os.environ.get("LANGBASE_API_KEY")
7373
llm_api_key = os.environ.get("LLM_API_KEY")
74-
resend_api_key = os.environ.get("RESEND_API_KEY")
74+
# resend_api_key = os.environ.get("RESEND_API_KEY")
7575

7676
if not langbase_api_key:
7777
print("❌ Missing LANGBASE_API_KEY in environment variables.")
@@ -81,9 +81,9 @@ def main():
8181
print("❌ Missing LLM_API_KEY in environment variables.")
8282
exit(1)
8383

84-
if not resend_api_key:
85-
print("❌ Missing RESEND_API_KEY in environment variables.")
86-
exit(1)
84+
# if not resend_api_key:
85+
# print("❌ Missing RESEND_API_KEY in environment variables.")
86+
# exit(1)
8787

8888
# Initialize Langbase client
8989
langbase = Langbase(api_key=langbase_api_key)
@@ -102,16 +102,22 @@ def main():
102102
response = langbase.agent.run(
103103
model="openai:gpt-4.1-mini",
104104
api_key=llm_api_key,
105-
instructions="You are an email sending assistant.",
105+
instructions="You are an email agent. You are given a task to send an email to a recipient. You have the ability to send an email using the send_email tool.",
106106
input=input_messages,
107107
tools=[send_email_tool_schema],
108108
stream=False,
109109
)
110110

111111
# Check if response contains choices (for tool calls)
112112
choices = response.get("choices", [])
113+
114+
print("\n📨 Initial Response:")
115+
print(
116+
f"Output: {response.get('output', 'No direct output - checking for tool calls...')}"
117+
)
118+
113119
if not choices:
114-
print("No choices found in response")
120+
print("No choices found in response")
115121
return
116122

117123
# Push agent tool call to messages
@@ -122,28 +128,42 @@ def main():
122128
has_tool_calls = tool_calls and len(tool_calls) > 0
123129

124130
if has_tool_calls:
125-
for tool_call in tool_calls:
131+
print(f"\n🔧 Tool calls detected: {len(tool_calls)}")
132+
133+
for i, tool_call in enumerate(tool_calls, 1):
126134
# Process each tool call
127135
function = tool_call.get("function", {})
128136
name = function.get("name")
129137
args = function.get("arguments")
130138

139+
print(f"\n Tool Call #{i}:")
140+
print(f" - Name: {name}")
141+
print(f" - Raw Arguments: {args}")
142+
131143
try:
132144
parsed_args = json.loads(args)
145+
print(f" - Parsed Arguments: {json.dumps(parsed_args, indent=4)}")
133146
except json.JSONDecodeError:
134-
print(f"Error parsing tool call arguments: {args}")
147+
print(f"Error parsing tool call arguments: {args}")
135148
continue
136149

137150
# Set email parameters
151+
print("\n 📧 Preparing email with full details...")
138152
parsed_args["from"] = "[email protected]"
139153
parsed_args["to"] = recipient_info["email"]
140154
parsed_args["subject"] = email["subject"]
141155
parsed_args["html"] = email["html_email"]
142156
parsed_args["text"] = email["full_email"]
143157

158+
print(f" - From: {parsed_args['from']}")
159+
print(f" - To: {parsed_args['to']}")
160+
print(f" - Subject: {parsed_args['subject']}")
161+
144162
# Execute the tool
145163
try:
164+
print(f"\n ⚡ Executing {name}...")
146165
result = send_email(parsed_args)
166+
print(f" ✅ Tool result: {result}")
147167

148168
# Add tool result to messages
149169
input_messages.append(
@@ -155,19 +175,23 @@ def main():
155175
}
156176
)
157177
except Exception as e:
158-
print(f"Error executing tool: {e}")
178+
print(f"Error executing tool: {e}")
159179
continue
160180

181+
print("\n🤖 Sending tool results back to agent for final response...")
182+
161183
# Final agent response with tool result
162184
final_response = langbase.agent.run(
163185
model="openai:gpt-4.1-mini",
164-
api_key=os.environ.get("OPENAI_API_KEY"),
186+
api_key=llm_api_key,
165187
instructions="You are an email sending assistant. Confirm the email has been sent successfully.",
166188
input=input_messages,
167189
stream=False,
168190
)
169191

170-
print("Final Output:", final_response.get("output"))
192+
print("\n✨ Final Response:")
193+
print(f"Agent: {final_response.get('output')}")
194+
print("\n" + "=" * 50)
171195

172196

173197
if __name__ == "__main__":

0 commit comments

Comments
 (0)