More fixes for anthropic

This commit is contained in:
2024-08-18 10:40:59 -05:00
parent b5a421ea21
commit 0b28b9a39d
2 changed files with 67 additions and 46 deletions
+65 -44
View File
@@ -83,62 +83,78 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
logging.info(f"Message from user {user_id}: {user_message}") logging.info(f"Message from user {user_id}: {user_message}")
# Initialize conversation history for new users
if user_id not in conversation_history: if user_id not in conversation_history:
conversation_history[user_id] = [] conversation_history[user_id] = []
# Add user message to conversation history
conversation_history[user_id].append({"role": "user", "content": user_message}) conversation_history[user_id].append({"role": "user", "content": user_message})
# Prepare messages for OpenAI API
messages = conversation_history[user_id] messages = conversation_history[user_id]
response = get_chat_response(messages) response = get_chat_response(messages)
tool_calls = []
# Extract the assistant's reply if use_anthropic:
assistant_message = response.choices[0].message for message in response.content:
toolUseCount = 0 if message.type == "tool_use":
if hasattr(assistant_message, 'function_call') and assistant_message.function_call: tool_calls.append(message)
while hasattr(assistant_message, 'function_call') and assistant_message.function_call and toolUseCount < 50: # Todo: put amount in env assistant_message = ""
tool_response = call_tool(assistant_message.function_call) else:
assistant_message = message
conversation_history[user_id].append({"role": "function", "name": assistant_message.function_call.name, "content": json.dumps(tool_response)}) tool_calls = None
messages.append({
"role": "function",
"name": assistant_message.function_call.name,
"content": json.dumps(tool_response)
})
# Call API again to get the final response
assistant_message = get_chat_response(messages).choices[0].message
if not hasattr(assistant_message, 'function_call') or not assistant_message.function_call:
assistant_reply = assistant_message.content
conversation_history[user_id].append({"role": "assistant", "content": assistant_reply})
else: else:
assistant_reply = assistant_message.content assistant_message = response.choices[0].message
# Add assistant's reply to conversation history if hasattr(assistant_message, 'function_call'):
conversation_history[user_id].append({"role": "assistant", "content": assistant_reply}) tool_calls.append(assistant_message.function_call)
toolUseCount = 0
while len(tool_calls) > 0 and toolUseCount < 50:
# Trim conversation history if it gets too long (e.g., keep last 10 messages) tool_call = tool_calls.pop(0)
if len(conversation_history[user_id]) > 10: function_name = tool_call.name
conversation_history[user_id] = conversation_history[user_id][-10:]
# Send the reply back to the user tool_response = call_tool(tool_call)
await update.message.reply_text(assistant_reply)
conversation_history[user_id].append({"role": "function", "name": function_name, "content": json.dumps(tool_response)})
messages.append({
"role": "function",
"name": function_name,
"content": json.dumps(tool_response)
})
response = get_chat_response(messages)
if use_anthropic:
for message in response.content:
if message.type == "tool_use":
tool_calls.append(message)
assistant_message = ""
else:
assistant_message = message
tool_calls = None
else:
assistant_message = response.choices[0].message
if assistant_message.function_call is not None:
tool_calls.append(assistant_message.function_call)
toolUseCount += 1
assistant_reply = assistant_message
conversation_history[user_id].append({"role": "assistant", "content": assistant_reply})
if len(conversation_history[user_id]) > 20:
conversation_history[user_id] = conversation_history[user_id][-20:]
await update.message.reply_text(assistant_reply.content if not use_anthropic else assistant_reply)
except Exception as e: except Exception as e:
logging.error(f"An error occurred: {str(e)}") logging.error(f"An error occurred: {str(e)}")
await update.message.reply_text("Sorry, an error occurred while processing your request.") await update.message.reply_text("Sorry, an error occurred while processing your request.")
def call_tool(function_call): def call_tool(function_call):
# Execute the function function_name = function_call.name if use_anthropic else function_call.name
function_name = function_call.name function_args = "{}" if use_anthropic else function_call.arguments
function_args = function_call.arguments
for tool in tools: for tool in tools:
if function_name in [f["name"] for f in tool.get_functions()]: if function_name in [f["name"] for f in tool.get_functions()]:
return tool.execute(function_name, **eval(function_args)) return tool.execute(function_name, **json.loads(function_args))
def get_chat_response(messages): def get_chat_response(messages):
return get_claude_response(messages) if use_anthropic else get_openai_response(messages) return get_claude_response(messages) if use_anthropic else get_openai_response(messages)
@@ -163,13 +179,18 @@ def get_claude_response(messages):
} }
for function in functions for function in functions
] ]
response = anthropic_client.messages.create( try:
system=system_prompt, response = anthropic_client.messages.create(
messages=messages, model="claude-3-sonnet-20240229",
tools=anthropic_tools, system=system_prompt,
max_tokens=4096, messages=[{"role": m["role"], "content": m["content"]} for m in messages],
model="claude-3-5-sonnet-20240620" max_tokens=4096,
) tools=anthropic_tools
)
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
return None
return response return response
async def switch(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def switch(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
@@ -179,7 +200,7 @@ async def switch(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
logging.info(f"Switched to model: {model}") logging.info(f"Switched to model: {model}")
await update.message.reply_text(f"Switched to model: {model}") await update.message.reply_text(f"Switched to model: {model}")
async def switch_anthropic(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def switch_providers(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
global use_anthropic global use_anthropic
use_anthropic = not use_anthropic use_anthropic = not use_anthropic
logging.info("Using Anthropic" if use_anthropic else "Using OpenAI") logging.info("Using Anthropic" if use_anthropic else "Using OpenAI")
@@ -200,7 +221,7 @@ def main() -> None:
application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("clear", clear)) application.add_handler(CommandHandler("clear", clear))
application.add_handler(CommandHandler("switch", switch)) application.add_handler(CommandHandler("switch", switch))
application.add_handler(CommandHandler("toggle", switch_anthropic)) application.add_handler(CommandHandler("toggle", switch_providers))
application.add_handler(CommandHandler("status", status)) application.add_handler(CommandHandler("status", status))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
+1 -1
View File
@@ -59,7 +59,7 @@ class LogTool(BaseTool):
self.logger.error(error_message) self.logger.error(error_message)
return error_message return error_message
def _get_log_contents(self, line_count=None): def _get_log_contents(self, line_count=150):
log_file_path = 'logs/output.log' log_file_path = 'logs/output.log'
if not os.path.exists(log_file_path): if not os.path.exists(log_file_path):