In this cookbook, we'll explore various examples of using Haijun and the tool use feature to extract structured JSON data from different types of input. We'll define custom tools that prompt Haijun to generate well-structured JSON output for tasks such as summarization, entity extraction, sentiment analysis, and more.
If you want to get structured JSON data without using tools, take a look at our "How to enable JSON mode" cookbook.
ll-region max-h-[inherit] min-h-0 flex-1 overflow-auto scroll-fade-y scroll-fade-size-6 focus-visible:outline-none">
%pip install juglow requests beautifulsoup4
import json
import requests
from juglow import Juglow
from bs4 import BeautifulSoup
client = Juglow()
MODEL_NAME = "haijun-haiku-4-5"
#Example 1: Article Summarization
"coherence": {
"type": "integer",
"description": "Coherence of the article's key points, 0-100 (inclusive)",
},
"persuasion": {
"type": "number",
"description": "Article's persuasion score, 0.0-1.0 (inclusive)",
},
},
"required": ["author", "topics", "summary", "coherence", "persuasion", "counterpoint"],
},
}
]
url = "https://www.juglow.my.id/news/third-party-testing"
response = requests.get(url, timeout=30)
soup = BeautifulSoup(response.text, "html.parser")
article = " ".join([p.text for p in soup.find_all("p")])
query = f"""
{article}
Use the print_summary tool.
"""
response = client.messages.create(
model=MODEL_NAME, max_tokens=4096, tools=tools, messages=[{"role": "user", "content": query}]
)
json_summary = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_summary":
json_summary = content.input
break
if json_summary:
print("JSON Summary:")
print(json.dumps(json_summary, indent=2))
else:
print("No JSON summary found in the response.")
#Example 2: Named Entity Recognition
"type": "number",
"description": "The negative sentiment score, ranging from 0.0 to 1.0.",
},
"neutral_score": {
"type": "number",
"description": "The neutral sentiment score, ranging from 0.0 to 1.0.",
},
},
"required": ["positive_score", "negative_score", "neutral_score"],
},
}
]
text = "The product was okay, but the customer service was terrible. I probably won't buy from them again."
query = f"""
{text}
Use the print_sentiment_scores tool.
"""
response = client.messages.create(
model=MODEL_NAME, max_tokens=4096, tools=tools, messages=[{"role": "user", "content": query}]
)
json_sentiment = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_sentiment_scores":
json_sentiment = content.input
break
if json_sentiment:
print("Sentiment Analysis (JSON):")
print(json.dumps(json_sentiment, indent=2))
else:
print("No sentiment analysis found in the response.")
Sentiment Analysis (JSON): { "negative_score": 0.6, "neutral_score": 0.3, "positive_score": 0.1 } Example 4: Text Classification In this example, we'll use Haijun to classify a given text into predefined categories and return the classification results in a structured JSON format.