This guide showcases advanced use cases and patterns for HelpingAI, demonstrating how to leverage emotional intelligence, Chain of Recursive Thoughts, and tool calling for sophisticated applications.
Build a chatbot that provides empathetic support with emotional awareness.
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.helpingai.co/v1",
api_key="YOUR_API_KEY"
)
class EmotionalSupportBot:
def __init__(self):
self.conversation_history = [
{
"role": "system",
"content": """You are a compassionate emotional support assistant.
You have high emotional intelligence and can:
- Detect emotional states from text
- Respond with appropriate empathy
- Provide gentle guidance and support
- Validate feelings without judgment
- Suggest coping strategies when appropriate
Always prioritize emotional validation before offering solutions."""
}
]
def respond(self, user_message):
self.conversation_history.append({
"role": "user",
"content": user_message
})
response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=self.conversation_history,
temperature=0.7,
max_tokens=300,
hideThink=False # Show emotional reasoning
)
assistant_message = response.choices[0].message.content
self.conversation_history.append({
"role": "assistant",
"content": assistant_message
})
return assistant_message
# Usage example {#usage-example}
bot = EmotionalSupportBot()
# Simulate conversation {#simulate-conversation}
responses = [
"I've been feeling really overwhelmed at work lately",
"My manager keeps piling on more tasks and I can't keep up",
"I'm starting to think I'm just not good enough for this job"
]
for user_input in responses:
print(f"User: {user_input}")
response = bot.respond(user_input)
print(f"Assistant: {response}\n")import OpenAI from 'openai';
const openai = new OpenAI({
baseURL: 'https://api.helpingai.co/v1',
apiKey: 'YOUR_API_KEY'
});
class EmotionalSupportBot {
constructor() {
this.conversationHistory = [
{
role: "system",
content: `You are a compassionate emotional support assistant with high emotional intelligence.
Detect emotions, respond empathetically, validate feelings, and provide gentle guidance.`
}
];
}
async respond(userMessage) {
this.conversationHistory.push({
role: "user",
content: userMessage
});
const response = await openai.chat.completions.create({
model: 'Dhanishtha-2.0-preview',
messages: this.conversationHistory,
temperature: 0.7,
max_tokens: 300,
hideThink: false
});
const assistantMessage = response.choices[0].message.content;
this.conversationHistory.push({
role: "assistant",
content: assistantMessage
});
return assistantMessage;
}
}
// Usage
const bot = new EmotionalSupportBot();
async function runConversation() {
const userInputs = [
"I just broke up with my partner and I'm heartbroken",
"We were together for three years and I thought we'd get married",
"I don't know how to move on from this"
];
for (const input of userInputs) {
console.log(`User: ${input}`);
const response = await bot.respond(input);
console.log(`Assistant: ${response}\n`);
}
}
runConversation();Create an AI that reviews code with reasoning and provides constructive feedback.
from helpingai import HelpingAI
import json
client = HelpingAI(api_key="YOUR_API_KEY")
def review_code(code, language="python"):
tools = [{
"type": "function",
"function": {
"name": "analyze_complexity",
"description": "Analyze code complexity and performance",
"parameters": {
"type": "object",
"properties": {
"code": {"type": "string"},
"language": {"type": "string"}
},
"required": ["code", "language"]
}
}
}]
messages = [
{
"role": "system",
"content": """You are an expert code reviewer with deep knowledge of software engineering best practices.
Provide constructive, detailed feedback on:
- Code quality and readability
- Performance considerations
- Security issues
- Best practices
- Suggestions for improvement
Be encouraging while being thorough."""
},
{
"role": "user",
"content": f"Please review this {language} code:\n\n```{language}\n{code}\n```"
}
]
response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=messages,
tools=tools,
hideThink=False, # Show reasoning process
temperature=0.3,
max_tokens=600
)
return response.choices[0].message.content
# Example usage {#example-usage}
code_to_review = """
def find_max(numbers):
max_num = numbers[0]
for i in range(len(numbers)):
if numbers[i] > max_num:
max_num = numbers[i]
return max_num
def calculate_average(numbers):
total = 0
for num in numbers:
total = total + num
return total / len(numbers)
"""
review = review_code(code_to_review, "python")
print(review)Build an assistant that can research topics, analyze information, and provide comprehensive reports.
from openai import OpenAI
import json
import requests
client = OpenAI(
base_url="https://api.helpingai.co/v1",
api_key="YOUR_API_KEY"
)
class ResearchAssistant:
def __init__(self):
self.tools = [
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web for information on a topic",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"num_results": {"type": "integer", "description": "Number of results", "default": 5}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "analyze_data",
"description": "Analyze numerical data and trends",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to analyze"},
"analysis_type": {"type": "string", "description": "Type of analysis needed"}
},
"required": ["data", "analysis_type"]
}
}
}
]
def search_web(self, query, num_results=5):
# Mock web search function
return f"Found {num_results} results for '{query}': Recent studies show significant developments in {query}."
def analyze_data(self, data, analysis_type):
# Mock data analysis function
return f"Analysis of {analysis_type}: The data shows clear trends and patterns that indicate..."
def research_topic(self, topic):
messages = [
{
"role": "system",
"content": """You are a thorough research assistant. When researching a topic:
1. Search for current information
2. Analyze relevant data
3. Synthesize findings into a comprehensive report
4. Provide balanced perspectives
5. Cite sources and evidence
Think through your research process step by step."""
},
{
"role": "user",
"content": f"Research the topic: {topic}. Provide a comprehensive analysis with current information and data."
}
]
response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=messages,
tools=self.tools,
hideThink=False,
temperature=0.4,
max_tokens=800
)
message = response.choices[0].message
if message.tool_calls:
messages.append(message)
for tool_call in message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if function_name == "search_web":
result = self.search_web(function_args['query'], function_args.get('num_results', 5))
elif function_name == "analyze_data":
result = self.analyze_data(function_args['data'], function_args['analysis_type'])
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
final_response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=messages,
hideThink=False,
temperature=0.4,
max_tokens=800
)
return final_response.choices[0].message.content
return message.content
# Usage {#usage}
assistant = ResearchAssistant()
report = assistant.research_topic("The impact of artificial intelligence on healthcare in 2024")
print(report)Create a tutor that adapts to student emotions and learning pace.
import { HelpingAI } from 'helpingai';
const client = new HelpingAI({
apiKey: 'YOUR_API_KEY'
});
class AdaptiveTutor {
constructor(subject) {
this.subject = subject;
this.studentProfile = {
learningStyle: 'visual',
currentLevel: 'beginner',
strugglingAreas: [],
strengths: []
};
this.conversationHistory = [
{
role: "system",
content: `You are an adaptive ${subject} tutor with high emotional intelligence.
You can:
- Detect student frustration, confusion, or excitement
- Adapt explanations to emotional state
- Provide encouragement when needed
- Adjust difficulty based on student responses
- Use different teaching methods for different learning styles
Always be patient, encouraging, and supportive.`
}
];
}
async teach(studentQuestion, emotionalContext = null) {
let userMessage = studentQuestion;
if (emotionalContext) {
userMessage += ` [Student seems ${emotionalContext}]`;
}
this.conversationHistory.push({
role: "user",
content: userMessage
});
const response = await client.chat.completions.create({
model: 'Dhanishtha-2.0-preview',
messages: this.conversationHistory,
hideThink: false, // Show teaching reasoning
temperature: 0.6,
max_tokens: 400
});
const tutorResponse = response.choices[0].message.content;
this.conversationHistory.push({
role: "assistant",
content: tutorResponse
});
return tutorResponse;
}
async assessUnderstanding(studentAnswer, correctAnswer) {
const assessmentPrompt = `
Student's answer: "${studentAnswer}"
Correct answer: "${correctAnswer}"
Assess the student's understanding and provide feedback. Be encouraging and help them learn from any mistakes.
`;
const response = await client.chat.completions.create({
model: 'Dhanishtha-2.0-preview',
messages: [
...this.conversationHistory,
{ role: "user", content: assessmentPrompt }
],
hideThink: false,
temperature: 0.4,
max_tokens: 300
});
return response.choices[0].message.content;
}
}
// Usage example
async function runTutoringSession() {
const tutor = new AdaptiveTutor('mathematics');
// Student seems confused
let response = await tutor.teach(
"I don't understand how to solve quadratic equations",
"confused and frustrated"
);
console.log("Tutor:", response);
// Student shows some understanding
response = await tutor.teach(
"So I need to use the quadratic formula?",
"slightly more confident"
);
console.log("Tutor:", response);
// Assess student's attempt
const assessment = await tutor.assessUnderstanding(
"x = (-b ± √(b² - 4ac)) / 2a",
"x = (-b ± √(b² - 4ac)) / 2a"
);
console.log("Assessment:", assessment);
}
runTutoringSession();Build an AI that collaborates on creative writing with emotional depth.
import requests
import json
class CreativeWritingPartner:
def __init__(self):
self.story_context = {
"genre": None,
"characters": [],
"setting": None,
"plot_points": [],
"tone": None
}
self.conversation_history = [
{
"role": "system",
"content": """You are a creative writing partner with deep understanding of:
- Character development and emotional depth
- Plot structure and pacing
- Literary techniques and style
- Genre conventions
- Emotional resonance in storytelling
Collaborate creatively while maintaining story consistency and emotional authenticity."""
}
]
def collaborate(self, user_input, show_reasoning=True):
self.conversation_history.append({
"role": "user",
"content": user_input
})
url = "https://api.helpingai.co/v1/chat/completions"
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
data = {
"model": "Dhanishtha-2.0-preview",
"messages": self.conversation_history,
"hideThink": not show_reasoning,
"temperature": 0.8, # Higher creativity
"max_tokens": 500
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
assistant_response = result['choices'][0]['message']['content']
self.conversation_history.append({
"role": "assistant",
"content": assistant_response
})
return assistant_response
def develop_character(self, character_description):
prompt = f"""Help me develop this character: {character_description}
Consider:
- Emotional depth and psychology
- Backstory and motivations
- Character arc potential
- Relationships with other characters
- Unique voice and mannerisms"""
return self.collaborate(prompt)
def continue_story(self, current_scene):
prompt = f"""Here's the current scene: {current_scene}
Help me continue this story. Consider:
- Emotional continuity
- Character consistency
- Plot advancement
- Tension and pacing
- Sensory details"""
return self.collaborate(prompt)
# Usage example {#usage-example}
writer = CreativeWritingPartner()
# Character development {#character-development}
character_response = writer.develop_character(
"A lonely lighthouse keeper who discovers they can communicate with ships from the past"
)
print("Character Development:")
print(character_response)
print("\n" + "="*50 + "\n")
# Story continuation {#story-continuation}
story_response = writer.continue_story(
"The lighthouse keeper heard the familiar creak of the radio, but this time, the voice that came through was speaking in an accent from a century ago..."
)
print("Story Continuation:")
print(story_response)class ContextManager:
def __init__(self, max_context_length=4000):
self.max_context_length = max_context_length
self.conversation_history = []
def add_message(self, role, content):
self.conversation_history.append({"role": role, "content": content})
self.trim_context()
def trim_context(self):
# Keep system message and recent messages within token limit
if len(self.conversation_history) > 10: # Arbitrary limit
system_msg = self.conversation_history[0]
recent_msgs = self.conversation_history[-8:]
self.conversation_history = [system_msg] + recent_msgsdef robust_api_call(client, messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=messages,
temperature=0.7,
max_tokens=400
)
return response.choices[0].message.content
except Exception as e:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
else:
return f"I apologize, but I'm having technical difficulties. Please try again later."class EmotionalStateTracker:
def __init__(self):
self.emotional_history = []
def analyze_emotion(self, text):
# Use HelpingAI to analyze emotional state
response = client.chat.completions.create(
model="Dhanishtha-2.0-preview",
messages=[
{"role": "system", "content": "Analyze the emotional state in this text. Return only the primary emotion and intensity (1-10)."},
{"role": "user", "content": text}
],
temperature=0.3,
max_tokens=50
)
return response.choices[0].message.content
def track_emotion(self, user_input):
emotion = self.analyze_emotion(user_input)
self.emotional_history.append({
"timestamp": time.time(),
"emotion": emotion,
"text": user_input
})
return emotion