-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlangchain_tool.py
More file actions
executable file
·228 lines (185 loc) · 7.19 KB
/
Copy pathlangchain_tool.py
File metadata and controls
executable file
·228 lines (185 loc) · 7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env python3
"""
LangChain Tool Wrapper for BulkPublish
=======================================
Defines LangChain-compatible tools for creating posts and listing channels
via the BulkPublish API, then runs an agent conversation that uses them.
Usage:
export BULKPUBLISH_API_KEY=bp_your_key
export OPENAI_API_KEY=sk_your_key
pip install langchain langchain-openai requests
python langchain_tool.py
Requirements:
pip install langchain langchain-openai requests
"""
import os
import sys
import json
import requests
from typing import Optional
API_KEY = os.environ.get("BULKPUBLISH_API_KEY")
BASE_URL = os.environ.get("BULKPUBLISH_BASE_URL", "https://app.bulkpublish.com")
if not API_KEY:
print("Error: Set the BULKPUBLISH_API_KEY environment variable.")
sys.exit(1)
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
# ============================================================================
# Tool Definitions
# ============================================================================
try:
from langchain.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
except ImportError:
print("Error: Install required packages:")
print(" pip install langchain langchain-openai requests")
sys.exit(1)
@tool
def list_channels() -> str:
"""List all connected social media channels.
Returns a JSON list of channels with their IDs, platform names,
account names, and token status.
"""
try:
resp = requests.get(f"{BASE_URL}/api/channels", headers=HEADERS, timeout=30)
resp.raise_for_status()
data = resp.json()
channels = data.get("channels", [])
result = []
for ch in channels:
result.append({
"id": ch["id"],
"platform": ch["platform"],
"accountName": ch["accountName"],
"tokenStatus": ch.get("tokenStatus", "unknown"),
})
return json.dumps(result, indent=2)
except requests.RequestException as e:
return f"Error fetching channels: {e}"
@tool
def create_post(
content: str,
channel_ids: str,
status: str = "draft",
scheduled_at: Optional[str] = None,
timezone: str = "UTC",
) -> str:
"""Create a social media post on BulkPublish.
Args:
content: The post text content.
channel_ids: Comma-separated channel IDs and platforms, e.g. "1:x,2:linkedin".
Get IDs from list_channels.
status: "draft" (default) or "scheduled".
scheduled_at: ISO datetime for scheduling, e.g. "2025-02-01T14:00:00Z".
Required when status is "scheduled".
timezone: Timezone string, e.g. "America/New_York". Defaults to "UTC".
Returns:
JSON response with the created post details.
"""
# Parse channel_ids string into channel entries
channels = []
for entry in channel_ids.split(","):
entry = entry.strip()
if ":" in entry:
cid, platform = entry.split(":", 1)
channels.append({"channelId": int(cid.strip()), "platform": platform.strip()})
else:
return f"Error: Invalid channel format '{entry}'. Use 'id:platform' format, e.g. '1:x,2:linkedin'"
payload = {
"content": content,
"channels": channels,
"status": status,
}
if scheduled_at:
payload["scheduledAt"] = scheduled_at
if timezone:
payload["timezone"] = timezone
try:
resp = requests.post(
f"{BASE_URL}/api/posts", headers=HEADERS, json=payload, timeout=30
)
resp.raise_for_status()
post = resp.json()
return json.dumps({
"id": post.get("id"),
"status": post.get("status"),
"content": post.get("content", "")[:100],
"scheduledAt": post.get("scheduledAt"),
"platforms": [p.get("platform") for p in post.get("postPlatforms", [])],
}, indent=2)
except requests.RequestException as e:
try:
error_body = e.response.json() if hasattr(e, "response") and e.response else {}
except Exception:
error_body = {}
return f"Error creating post: {e}\nDetails: {json.dumps(error_body)}"
@tool
def get_quota_usage() -> str:
"""Check current BulkPublish quota usage.
Returns plan limits and current usage for posts, channels,
media storage, and API calls.
"""
try:
resp = requests.get(f"{BASE_URL}/api/quotas/usage", headers=HEADERS, timeout=30)
resp.raise_for_status()
return json.dumps(resp.json(), indent=2)
except requests.RequestException as e:
return f"Error fetching quota: {e}"
# ============================================================================
# Agent Setup & Conversation
# ============================================================================
def main():
print("BulkPublish — LangChain Agent Example")
print("=" * 38)
print()
if not os.environ.get("OPENAI_API_KEY"):
print("Error: Set the OPENAI_API_KEY environment variable.")
print("This example uses OpenAI as the LLM backend for the LangChain agent.")
sys.exit(1)
# Define the tools
tools = [list_channels, create_post, get_quota_usage]
# Create the LLM
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Create the prompt
prompt = ChatPromptTemplate.from_messages([
(
"system",
"You are a helpful social media assistant. You help users manage "
"their social media posts using BulkPublish. You can list their "
"connected channels, create posts, and check quota usage. "
"Always confirm with the user before publishing or scheduling posts."
),
MessagesPlaceholder(variable_name="chat_history", optional=True),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
# Create the agent
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Run a sample conversation
print("Running sample conversation...\n")
print("-" * 50)
# Turn 1: List channels
print("\nUser: What channels do I have connected?\n")
result = agent_executor.invoke({"input": "What channels do I have connected?"})
print(f"\nAssistant: {result['output']}\n")
print("-" * 50)
# Turn 2: Create a draft post
print("\nUser: Create a draft post saying 'Excited about our Q2 launch!' to all my channels.\n")
result = agent_executor.invoke({
"input": "Create a draft post saying 'Excited about our Q2 launch!' to all my channels."
})
print(f"\nAssistant: {result['output']}\n")
print("-" * 50)
# Turn 3: Check quotas
print("\nUser: How much of my quota have I used?\n")
result = agent_executor.invoke({"input": "How much of my quota have I used?"})
print(f"\nAssistant: {result['output']}\n")
print("=" * 50)
print("Agent conversation complete.")
if __name__ == "__main__":
main()