Created
June 2, 2023 02:37
-
-
Save reachlin/41434000fb0cc6e2f9a57dab642f42d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A very simple ask and search AI bot. | |
from langchain import OpenAI | |
from langchain.utilities import GoogleSearchAPIWrapper | |
from langchain.agents import initialize_agent, Tool | |
from langchain.agents import AgentType | |
from flask import jsonify, request, Response, Flask | |
import os | |
app = Flask(__name__) | |
@app.route('/') | |
def hello_world(): | |
return 'Hello from Flask!' | |
@app.route('/search') | |
def search(): | |
key = request.headers.get('Authorization').strip() | |
query = request.args.get('query').strip() | |
print(query) | |
if key.endswith(os.getenv('API_KEY').strip()) and len(os.getenv('SEARCH_API_KEY'))>0 and len(query)>0 and len(query)<600: | |
rsp = ask_with_search(os.getenv('OPENAI_API_KEY'), os.getenv('OPENAI_ORG'), os.getenv('SEARCH_API_ID'), os.getenv('SEARCH_API_KEY'), query) | |
print(f"result:{rsp}") | |
return jsonify(answer=rsp) | |
else: | |
return Response(status=404, mimetype='application/json') | |
def ask_with_search(openai_key, openai_org, search_api_id, search_api_key, query): | |
try: | |
llm = OpenAI(temperature=0, openai_api_key=openai_key, openai_organization=openai_org) | |
# google_api_key: Optional[str] = None | |
# google_cse_id: Optional[str] = None | |
search = GoogleSearchAPIWrapper(google_api_key=search_api_key, google_cse_id=search_api_id) | |
#search = SlackSearchAPIWrapper() | |
tools = [ | |
Tool( | |
name="Intermediate Answer", | |
func=search.run, | |
description="useful for when you need to ask with search" | |
) | |
] | |
self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True) | |
return self_ask_with_search.run(query) | |
except Exception as e: | |
return f"ask_with_search error: {e}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment