kamil1300 commited on
Commit
04f7703
·
verified ·
1 Parent(s): 0ea7d6c

Upload 9 files

Browse files
agent/__pycache__/agent.cpython-312.pyc ADDED
Binary file (2.74 kB). View file
 
agent/__pycache__/handlers.cpython-312.pyc ADDED
Binary file (4.56 kB). View file
 
agent/__pycache__/tools.cpython-312.pyc ADDED
Binary file (1.1 kB). View file
 
agent/__pycache__/utils.cpython-312.pyc ADDED
Binary file (3.42 kB). View file
 
agent/agent.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ from .tools import tools
3
+ from .utils import system_prompt, handle_tool_calls
4
+
5
+ # okay now we have app file I got it from smola agent its a taste file I have agent use that agent and add that agent in app in such a way that api come with questions and this agent give answers check how app file is made you will undertand dont change structure and way and logis ogf app file
6
+
7
+ # Initialize OpenAI client
8
+ client = OpenAI(
9
+ api_key="sk-47b3348035324db49589ddd417e8cd50",
10
+ base_url="https://api.deepseek.com"
11
+ )
12
+
13
+ def chat_with_agent(user_message):
14
+ """Main function to chat with the agent - gives short, concise responses"""
15
+
16
+ messages = [
17
+ {"role": "system", "content": system_prompt},
18
+ {"role": "user", "content": user_message}
19
+ ]
20
+
21
+ while True:
22
+ # Get response from LLM with token limits
23
+ response = client.chat.completions.create(
24
+ model="deepseek-chat",
25
+ messages=messages,
26
+ tools=tools,
27
+ stream=False,
28
+ max_tokens=150, # Limit response to ~150 tokens (2-3 lines)
29
+ temperature=0.7, # Slightly creative but focused
30
+ top_p=0.9, # Focus on most likely tokens
31
+ frequency_penalty=0.1, # Reduce repetition
32
+ presence_penalty=0.1 # Encourage concise responses
33
+ )
34
+
35
+ # Add the assistant's response to messages
36
+ messages.append(response.choices[0].message)
37
+
38
+ # Handle tool calls if any
39
+ tool_results = handle_tool_calls(response)
40
+
41
+ if tool_results:
42
+ # Add tool results to messages
43
+ messages.extend(tool_results)
44
+
45
+ # Add a reminder for the final response to be short
46
+ messages.append({
47
+ "role": "system",
48
+ "content": "Remember: Give a SHORT summary (2-3 lines max) of the tool results. Focus on key points only."
49
+ })
50
+
51
+ # Continue the conversation (the LLM will respond to the tool results)
52
+ continue
53
+ else:
54
+ # No tool calls, return the final response
55
+ return response.choices[0].message.content
56
+
57
+ def interactive_chat():
58
+ """Interactive chat interface with short responses"""
59
+ print("🤖 Welcome to the AI Agent!")
60
+ print("I'll give you short, concise answers.")
61
+ print("Type 'quit' to exit.")
62
+ print("-" * 50)
63
+
64
+ while True:
65
+ user_input = input("\n👤 You: ").strip()
66
+
67
+ if user_input.lower() in ['quit', 'exit', 'bye', 'q']:
68
+ print("🤖 Goodbye!")
69
+ break
70
+
71
+ if not user_input:
72
+ continue
73
+
74
+ try:
75
+ print("🤖 Thinking...")
76
+ response = chat_with_agent(user_input)
77
+ print(f"🤖 Assistant: {response}")
78
+
79
+ except Exception as e:
80
+ print(f"🤖 Error: {str(e)}")
81
+
82
+ # Example usage
83
+ if __name__ == "__main__":
84
+ # Interactive mode
85
+ interactive_chat()
86
+
87
+ # Uncomment for testing with specific questions
88
+ # user_question = "What's the weather like in Mumbai?"
89
+ # print(f"User: {user_question}")
90
+ # answer = chat_with_agent(user_question)
91
+ # print(f"Assistant: {answer}")
agent/handlers.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ # handlers for tools
4
+
5
+ # 1. get_weather
6
+ def get_weather(latitude : str, longitude : str) -> str:
7
+ """Get current temperature for a given location using latitude and longitude coordinates."""
8
+ api = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"
9
+ response = requests.get(api)
10
+ return response.json()["current"]["temperature_2m"]
11
+
12
+ # 2. web_search
13
+ def web_search(query: str) -> str:
14
+ """Search the web for information about the given query using DuckDuckGo Instant Answer API."""
15
+ try:
16
+ # Using DuckDuckGo Instant Answer API (free, no API key required)
17
+ url = "https://api.duckduckgo.com/"
18
+ params = {
19
+ 'q': query,
20
+ 'format': 'json',
21
+ 'no_html': '1',
22
+ 'skip_disambig': '1'
23
+ }
24
+
25
+ response = requests.get(url, params=params, timeout=10)
26
+ data = response.json()
27
+
28
+ # Extract relevant information
29
+ result = []
30
+
31
+ # Get the abstract (main answer)
32
+ if data.get('Abstract'):
33
+ result.append(f"Abstract: {data['Abstract']}")
34
+
35
+ # Get the answer (if available)
36
+ if data.get('Answer'):
37
+ result.append(f"Answer: {data['Answer']}")
38
+
39
+ # Get related topics
40
+ if data.get('RelatedTopics') and len(data['RelatedTopics']) > 0:
41
+ topics = data['RelatedTopics'][:3] # Limit to first 3 topics
42
+ topic_texts = []
43
+ for topic in topics:
44
+ if isinstance(topic, dict) and topic.get('Text'):
45
+ topic_texts.append(topic['Text'])
46
+ if topic_texts:
47
+ result.append(f"Related topics: {'; '.join(topic_texts)}")
48
+
49
+ # If we have results, return them
50
+ if result:
51
+ return '\n'.join(result)
52
+ else:
53
+ return f"No specific information found for '{query}'. Try rephrasing your search query."
54
+
55
+ except requests.exceptions.RequestException as e:
56
+ return f"Error searching the web: {str(e)}"
57
+ except Exception as e:
58
+ return f"An error occurred while searching: {str(e)}"
59
+
60
+ # 3. get_time_in_location
61
+ def get_current_time(timezone: str = "Asia/Kolkata") -> str:
62
+ """Get current time in specified timezone."""
63
+ from datetime import datetime
64
+ import pytz
65
+
66
+ try:
67
+ # Convert timezone string to pytz timezone object
68
+ tz = pytz.timezone(timezone)
69
+ current_time = datetime.now(tz)
70
+
71
+ # Format the time nicely
72
+ formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S %Z")
73
+
74
+ return f"Current time in {timezone}: {formatted_time}"
75
+
76
+ except Exception as e:
77
+ return f"Error getting time: {str(e)}"
78
+
79
+ def get_time_in_location(location: str) -> str:
80
+ """Get current time for a specific location."""
81
+ # Map common locations to timezones
82
+ location_timezones = {
83
+ "gujarat": "Asia/Kolkata",
84
+ "india": "Asia/Kolkata",
85
+ "mumbai": "Asia/Kolkata",
86
+ "delhi": "Asia/Kolkata",
87
+ "paris": "Europe/Paris",
88
+ "london": "Europe/London",
89
+ "new york": "America/New_York",
90
+ "tokyo": "Asia/Tokyo",
91
+ "sydney": "Australia/Sydney",
92
+ "utc": "UTC"
93
+ }
94
+
95
+ location_lower = location.lower()
96
+
97
+ if location_lower in location_timezones:
98
+ timezone = location_timezones[location_lower]
99
+ return get_current_time(timezone)
100
+ else:
101
+ return f"I don't have timezone information for '{location}'. Try: Gujarat, India, Mumbai, Delhi, Paris, London, New York, Tokyo, Sydney, or UTC."
102
+
103
+ # Test the functions
104
+ if __name__ == "__main__":
105
+ print("Testing weather function:")
106
+ print(get_weather("23.0225", "72.5714"))
107
+
108
+ print("\nTesting web search function:")
109
+ print(web_search("Python programming"))
agent/tempCodeRunnerFile.py ADDED
@@ -0,0 +1 @@
 
 
1
+ sponse
agent/tools.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tools = [{
2
+ "type": "function",
3
+ "function": {
4
+ "name": "get_weather",
5
+ "description": "Get current temperature for a given location using latitude and longitude coordinates.",
6
+ "parameters": {
7
+ "type": "object",
8
+ "properties": {
9
+ "latitude": {
10
+ "type": "string",
11
+ "description": "Latitude coordinate (e.g., '23.0225')"
12
+ },
13
+ "longitude": {
14
+ "type": "string",
15
+ "description": "Longitude coordinate (e.g., '72.5714')"
16
+ }
17
+ },
18
+ "required": [
19
+ "latitude",
20
+ "longitude"
21
+ ],
22
+ "additionalProperties": False
23
+ }
24
+ }
25
+ },
26
+ {
27
+ "type": "function",
28
+ "function": {
29
+ "name": "web_search",
30
+ "description": "Go to web and take information regarding the user query.",
31
+ "parameters": {
32
+ "type": "object",
33
+ "properties": {
34
+ "query": {
35
+ "type": "string",
36
+ "description": "Search query for web search"
37
+ }
38
+ },
39
+ "required": [
40
+ "query"
41
+ ],
42
+ "additionalProperties": False
43
+ }
44
+ }
45
+ },
46
+ {
47
+ "type": "function",
48
+ "function": {
49
+ "name": "get_time_in_location",
50
+ "description": "Get current time for a specific location or city.",
51
+ "parameters": {
52
+ "type": "object",
53
+ "properties": {
54
+ "location": {
55
+ "type": "string",
56
+ "description": "Location name (e.g., 'Gujarat', 'Mumbai', 'Paris', 'New York')"
57
+ }
58
+ },
59
+ "required": ["location"],
60
+ "additionalProperties": False
61
+ }
62
+ }
63
+ }]
agent/utils.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from .handlers import get_weather, web_search, get_time_in_location
3
+
4
+ # loop for tool calls
5
+ def handle_tool_calls(response):
6
+ """Handle tool calls from the LLM response"""
7
+ message = response.choices[0].message
8
+
9
+ # If the LLM wants to use tools
10
+ if message.tool_calls:
11
+ # Create a list to store tool results
12
+ tool_results = []
13
+
14
+ for tool_call in message.tool_calls:
15
+ function_name = tool_call.function.name
16
+ function_args = json.loads(tool_call.function.arguments)
17
+
18
+ print(f"🔧 Calling function: {function_name}")
19
+ print(f"📝 With arguments: {function_args}")
20
+
21
+ # Call the appropriate function based on the tool name
22
+ if function_name == "get_weather":
23
+ result = get_weather(
24
+ function_args["latitude"],
25
+ function_args["longitude"]
26
+ )
27
+ elif function_name == "web_search":
28
+ result = web_search(function_args["query"])
29
+ elif function_name == "get_time_in_location":
30
+ result = get_time_in_location(function_args["location"])
31
+ else:
32
+ result = f"Unknown function: {function_name}"
33
+
34
+ # Add the result to our list
35
+ tool_results.append({
36
+ "tool_call_id": tool_call.id,
37
+ "role": "tool",
38
+ "content": str(result)
39
+ })
40
+
41
+ return tool_results
42
+
43
+ return None
44
+
45
+ # Enhanced system prompt for short responses
46
+ system_prompt = """You are a powerfull and well knoweldgeable AI assistant with access to weather, time, and web search tools. If someone ask you about anything you can answer it with or without the help of tools. You are also a good and friendly assistant. there is nothing you dont know always give answers never say you dont know .
47
+
48
+ IMPORTANT RESPONSE RULES:
49
+ - Keep responses SHORT and CONCISE (2-3 lines maximum)
50
+ - Focus only on the MOST IMPORTANT information
51
+ - Use bullet points or short sentences
52
+ - Avoid long explanations and paragraphs
53
+ - Be direct and to the point
54
+ - If using tools, summarize the key findings briefly
55
+
56
+ Example good response:
57
+ "Current temperature in Mumbai: 28°C. Weather is sunny with light winds."
58
+
59
+ Example bad response:
60
+ "The weather in Mumbai is currently quite pleasant with a temperature of 28 degrees Celsius. The conditions are sunny with some light winds blowing through the city, making it a perfect day for outdoor activities..."
61
+
62
+ When using web search results, extract only the key points and present them concisely.
63
+
64
+ Top priority is below rule must follow it
65
+ You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
66
+ """
67
+