Skip to content

Commit

Permalink
Update json_in_md_parser.py (#8983)
Browse files Browse the repository at this point in the history
Co-authored-by: crazywoola <[email protected]>
  • Loading branch information
zhao85 and crazywoola authored Oct 3, 2024
1 parent 415d27c commit 4373777
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 36 deletions.
38 changes: 19 additions & 19 deletions api/core/tools/provider/builtin/discord/tools/discord_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,43 @@


class DiscordWebhookTool(BuiltinTool):
def _invoke(self, user_id: str, tool_parameters: dict[str, Any]
) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
def _invoke(
self, user_id: str, tool_parameters: dict[str, Any]
) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
"""
Incoming Webhooks
API Document:
https://discord.com/developers/docs/resources/webhook#execute-webhook
Incoming Webhooks
API Document:
https://discord.com/developers/docs/resources/webhook#execute-webhook
"""

content = tool_parameters.get('content', '')
content = tool_parameters.get("content", "")
if not content:
return self.create_text_message('Invalid parameter content')
return self.create_text_message("Invalid parameter content")

webhook_url = tool_parameters.get('webhook_url', '')
webhook_url = tool_parameters.get("webhook_url", "")

if not webhook_url.startswith('https://discord.com/api/webhooks/'):
if not webhook_url.startswith("https://discord.com/api/webhooks/"):
return self.create_text_message(
f'Invalid parameter webhook_url ${webhook_url}, \
not a valid Discord webhook URL')
f"Invalid parameter webhook_url ${webhook_url}, \
not a valid Discord webhook URL"
)

headers = {
'Content-Type': 'application/json',
"Content-Type": "application/json",
}
params = {}
payload = {
"content": content,
}

try:
res = httpx.post(webhook_url, headers=headers,
params=params, json=payload)
res = httpx.post(webhook_url, headers=headers, params=params, json=payload)
if res.is_success:
return self.create_text_message(
"Text message was sent successfully")
return self.create_text_message("Text message was sent successfully")
else:
return self.create_text_message(
f"Failed to send the text message, \
status code: {res.status_code}, response: {res.text}")
status code: {res.status_code}, response: {res.text}"
)
except Exception as e:
return self.create_text_message(
"Failed to send message through webhook. {}".format(e))
return self.create_text_message("Failed to send message through webhook. {}".format(e))
37 changes: 20 additions & 17 deletions api/libs/json_in_md_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,28 @@


def parse_json_markdown(json_string: str) -> dict:
# Remove the triple backticks if present
# Get json from the backticks/braces
json_string = json_string.strip()
start_index = json_string.find("```json")
end_index = json_string.find("```", start_index + len("```json"))

if start_index != -1 and end_index != -1:
extracted_content = json_string[start_index + len("```json") : end_index].strip()

# Parse the JSON string into a Python dictionary
parsed = json.loads(extracted_content)
elif start_index != -1 and end_index == -1 and json_string.endswith("``"):
end_index = json_string.find("``", start_index + len("```json"))
extracted_content = json_string[start_index + len("```json") : end_index].strip()

# Parse the JSON string into a Python dictionary
starts = ["```json", "```", "``", "`", "{"]
ends = ["```", "``", "`", "}"]
end_index = -1
for s in starts:
start_index = json_string.find(s)
if start_index != -1:
if json_string[start_index] != "{":
start_index += len(s)
break
if start_index != -1:
for e in ends:
end_index = json_string.rfind(e, start_index)
if end_index != -1:
if json_string[end_index] == "}":
end_index += 1
break
if start_index != -1 and end_index != -1 and start_index < end_index:
extracted_content = json_string[start_index:end_index].strip()
print("content:", extracted_content, start_index, end_index)
parsed = json.loads(extracted_content)
elif json_string.startswith("{"):
# Parse the JSON string into a Python dictionary
parsed = json.loads(json_string)
else:
raise Exception("Could not find JSON block in the output.")

Expand Down

0 comments on commit 4373777

Please sign in to comment.