polojuan/agentic-workflows
0
1import json2from datetime import datetime3from tools import research_tools4from tools import medical_tools5import streamlit as st6from openai import OpenAI7from dotenv import find_dotenv, load_dotenv8 9# Load environment variables10load_dotenv(find_dotenv())11 12def run_tool(name, args):13 if name == "arxiv_search_tool":14 return research_tools.arxiv_search_tool(**args)15 if name == "tavily_search_tool":16 return research_tools.tavily_search_tool(**args)17 if name == "wikipedia_search_tool":18 return research_tools.wikipedia_search_tool(**args)19 return {"error": f"Unknown tool: {name}"}20 21def research_agent(task: str, model: str = "gpt-4o-mini", max_tool_call: int = 3):22 """23 Execute a research task using tools with aisuite (without manual loop).24 """25 # Get client from session state26 client = st.session_state.get("client") or OpenAI()27 28 print("==================================")29 print("๐ Research Agent")30 print("==================================")31 tool_calls = 032 prompt = f"""33You are a research assistant with 34 35Task:36{task}37 38Date today is {datetime.now().strftime('%Y-%m-%d')}39Limit tool calling into {max_tool_call} maximum.40 41"""42 messages = [43 {"role": "system", "content": """44 You are an expert researcher specialized in gathering academic or technical content. You have access to the following tools:45 - arxiv_tool: for finding academic papers46 - tavily_tool: for general web search47 - wikipedia_tool: for encyclopedic knowledge 48 โ
Make the research concise.49 ๐ซ DO NOT provde recommendations for the next steps at the end. 50 ๐ซ DO NOT ask any questions on the next steps at the end.51 """},52 {"role": "user", "content":prompt.strip()}]53 tools = [research_tools.arxiv_tool_def, research_tools.tavily_tool_def, research_tools.wikipedia_tool_def]54 try:55 response = client.chat.completions.create(56 model=model,57 messages=messages,58 tools=tools,59 tool_choice="auto"60 )61 62 msg = response.choices[0].message63 64 # messages.append(msg)65 kept = msg.tool_calls[:max_tool_call]66 sanitized_assistant = {67 "role": "assistant",68 "content": msg.content,69 "tool_calls": kept,70 }71 messages.append(sanitized_assistant)72 for call in msg.tool_calls:73 tool_calls += 174 print(call.function.name, call.function.arguments)75 if tool_calls <= max_tool_call:76 result = run_tool(call.function.name, json.loads(call.function.arguments))77 messages.append({78 "role": "tool",79 "tool_call_id": call.id,80 "name": call.function.name,81 "content": json.dumps(result)82 })83 if tool_calls > 3:84 messages.append({85 "role": "assistant",86 "content": "I have reached the maximum tool usage as instructed. ",87 })88 89 final_response = client.chat.completions.create(90 model=model,91 messages=messages,92 )93 94 content = final_response.choices[0].message.content95 print("โ
Output:\n", content)96 used_tokens = response.usage.total_tokens97 print("Used Tokens:\n", used_tokens)98 return content, used_tokens99 100 except Exception as e:101 print("โ Error:", e)102 return f"[Model Error: {str(e)}]", 0103 104 105# # Research agent:106# messages = [107# {"role": "system", "content": """108# You are an expert researcher specialized in gathering academic or technical content. You have access to the following tools:109# - arxiv_tool: for finding academic papers110# - tavily_tool: for general web search111# - wikipedia_tool: for encyclopedic knowledge 112# โ
Make the research concise.113# ๐ซ DO NOT provde recommendations for the next steps at the end. 114# ๐ซ DO NOT ask any questions on the next steps at the end.115# """},116# {"role": "user", "content":prompt.strip()}]117# tools = [research_tools.arxiv_tool_def, research_tools.tavily_tool_def, research_tools.wikipedia_tool_def]118# try:119# response = client.chat.completions.create(120# model=model,121# messages=messages,122# tools=tools,123# tool_choice="auto"124# )