Skip to content

Commit 309b351

Browse files
committed
Update:
• Implemented minor adjustments to enhance Langchain compatibility. • Increased example quantity for improved functionality identification. • Updated tool detection handling; "content" is now set to an empty string, as opposed to "None" due to Langchain library. • Introduced a "groqchain" endpoint. • Provided an additional example.
1 parent d5ee25c commit 309b351

8 files changed

+272
-8
lines changed

app/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
# To be developed
2-
EVALUATION_CYCLES_COUNT=3
2+
EVALUATION_CYCLES_COUNT=1
33
PARSE_ERROR_TRIES = 5

app/libs/context.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def is_tool_call(self):
5858
return bool(
5959
self.last_message["role"] == "user"
6060
and self.tools
61-
and self.params.get("tool_choice", "none") != "none"
61+
and self.params.get("tool_choice", None) != "none"
6262
)
6363

6464
@property

app/libs/tools_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def call_route(messages):
302302
for func in tool_calls:
303303
tool_calls_count[func["name"]] += 1
304304

305-
pickup_threshold = max(evaluation_cycles_count, int(evaluation_cycles_count * 0.7))
305+
pickup_threshold = math.floor(evaluation_cycles_count * 0.7)
306306
final_tool_calls = []
307307
for tool_calls in tool_calls_list:
308308
for func in tool_calls:

app/prompts.py

+205-3
Original file line numberDiff line numberDiff line change
@@ -452,11 +452,213 @@ def get_image_desc_guide(ref_index: int, description: str) -> str:
452452
}
453453
</selected_tools>""",
454454
},
455-
]
455+
{
456+
"input": """# Conversation History:
457+
<user>
458+
What was the closing price of Apple Inc. (AAPL) stock yesterday?
459+
</user>
460+
461+
# Available Tools:
462+
[
463+
{
464+
"name": "get_stock_price",
465+
"description": "Use this function to retrieve the latest price information for a given stock symbol.\n\n:param symbol: The stock symbol to retrieve the price for (e.g., 'AAPL' for Apple Inc.).\n:return: A string containing the latest price information for the specified stock.",
466+
"parameters": {
467+
"type": "object",
468+
"properties": {
469+
"symbol": {
470+
"type": "string"
471+
}
472+
}
473+
}
474+
},
475+
{
476+
"name": "get_stock_history",
477+
"description": "Use this function to retrieve the historical price data for a given stock symbol over a specified period.\n\n:param symbol: The stock symbol to retrieve the historical data for.\n:param period: The time period for the historical data (e.g., '1d', '5d', '1mo', '1y').\n:return: A string containing the historical price data for the specified stock and period.",
478+
"parameters": {
479+
"type": "object",
480+
"properties": {
481+
"symbol": {
482+
"type": "string"
483+
},
484+
"period": {
485+
"type": "string"
486+
}
487+
}
488+
}
489+
}
490+
]""",
491+
"output": """<justification>
492+
The user is asking for the closing price of Apple Inc. (AAPL) stock from the previous day. We can use the "get_stock_price" tool to retrieve the latest price information for the AAPL stock symbol. The "get_stock_history" tool is not needed in this case, as the user is only asking for the closing price from yesterday.
493+
</justification>
494+
495+
<selected_tools>
496+
{
497+
"tool_calls": [
498+
{
499+
"name": "get_stock_price",
500+
"arguments": {
501+
"symbol": "AAPL"
502+
}
503+
}
504+
]
505+
}
506+
</selected_tools>""",
507+
},
508+
{
509+
"input": """# Conversation History:
510+
<user>
511+
I'm considering investing in Tesla (TSLA) stock. Can you provide me with some information to help me make a decision?
512+
</user>
513+
<assistant>
514+
To help you make an informed decision about investing in Tesla (TSLA) stock, I can provide you with the following information:
515+
516+
1. Latest price: The current price of TSLA stock can give you an idea of its market value.
517+
518+
2. Historical performance: Analyzing the stock's price history over different periods (e.g., 1 month, 6 months, 1 year) can help you understand its volatility and potential for growth.
519+
520+
3. Company fundamentals: Researching Tesla's financial statements, revenue growth, profitability, and future projects can provide insights into the company's overall health and potential.
521+
522+
4. Market sentiment: Monitoring news, analyst ratings, and investor sentiment can help gauge the market's perception of Tesla stock.
523+
524+
Let me know which specific information you'd like me to provide first, and I'll be happy to assist you further.
525+
</assistant>
526+
<user>
527+
Thanks for the overview. Let's start with the latest price and the historical performance over the past 6 months. That should give me a good starting point.
528+
</user>
529+
530+
# Available Tools:
531+
[
532+
{
533+
"name": "get_stock_price",
534+
"description": "Use this function to retrieve the latest price information for a given stock symbol.\n\n:param symbol: The stock symbol to retrieve the price for (e.g., 'AAPL' for Apple Inc.).\n:return: A string containing the latest price information for the specified stock.",
535+
"parameters": {
536+
"type": "object",
537+
"properties": {
538+
"symbol": {
539+
"type": "string"
540+
}
541+
}
542+
}
543+
},
544+
{
545+
"name": "get_stock_history",
546+
"description": "Use this function to retrieve the historical price data for a given stock symbol over a specified period.\n\n:param symbol: The stock symbol to retrieve the historical data for.\n:param period: The time period for the historical data (e.g., '1d', '5d', '1mo', '1y').\n:return: A string containing the historical price data for the specified stock and period.",
547+
"parameters": {
548+
"type": "object",
549+
"properties": {
550+
"symbol": {
551+
"type": "string"
552+
},
553+
"period": {
554+
"type": "string"
555+
}
556+
}
557+
}
558+
}
559+
]""",
560+
"output": """<justification>
561+
The user has requested two specific pieces of information to help them make a decision about investing in Tesla (TSLA) stock: the latest price and the historical performance over the past 6 months. To provide this information, we need to use both the "get_stock_price" and "get_stock_history" tools.
456562
563+
1. "get_stock_price" will be used to retrieve the current price of TSLA stock.
564+
2. "get_stock_history" will be used to retrieve the price history of TSLA stock over the past 6 months (period: '6mo').
565+
566+
By combining the results from these two tools, we can give the user the requested information to support their investment decision.
567+
</justification>
568+
569+
<selected_tools>
570+
{
571+
"tool_calls": [
572+
{
573+
"name": "get_stock_price",
574+
"arguments": {
575+
"symbol": "TSLA"
576+
}
577+
},
578+
{
579+
"name": "get_stock_history",
580+
"arguments": {
581+
"symbol": "TSLA",
582+
"period": "6mo"
583+
}
584+
}
585+
]
586+
}
587+
</selected_tools>""",
588+
},
589+
{
590+
"input": """# Conversation History:
591+
<user>
592+
What do you think about the recent performance of the stock market?
593+
</user>
594+
<assistant>
595+
The stock market's recent performance has been mixed, with some sectors showing strong growth while others have experienced volatility. Here are a few key points:
596+
597+
1. Tech stocks: Many technology companies have seen significant gains, driven by strong earnings and optimism about the sector's long-term prospects.
598+
599+
2. Energy sector: Oil and gas stocks have been under pressure due to fluctuating crude oil prices and concerns about the global economic recovery.
600+
601+
3. Health care: The health care sector has been a mixed bag, with some companies benefiting from the focus on COVID-19 treatments and vaccines, while others have faced challenges.
602+
603+
4. Overall market: The broader stock market indices, such as the S&P 500 and Dow Jones Industrial Average, have reached record highs recently, supported by positive economic data and optimism about the post-pandemic recovery.
604+
605+
It's important to remember that the stock market's performance is influenced by various factors, including economic indicators, geopolitical events, and investor sentiment. As an AI language model, I cannot provide personalized investment advice, but I suggest researching specific sectors and companies, and consulting with a financial advisor before making investment decisions.
606+
</assistant>
607+
<user>
608+
Thanks for the insights. It's helpful to get a general overview of the market's performance across different sectors. I'll definitely do more research and consult with a financial advisor before making any investment decisions.
609+
</user>
610+
611+
# Available Tools:
612+
[
613+
{
614+
"name": "get_stock_price",
615+
"description": "Use this function to retrieve the latest price information for a given stock symbol.\n\n:param symbol: The stock symbol to retrieve the price for (e.g., 'AAPL' for Apple Inc.).\n:return: A string containing the latest price information for the specified stock.",
616+
"parameters": {
617+
"type": "object",
618+
"properties": {
619+
"symbol": {
620+
"type": "string"
621+
}
622+
}
623+
}
624+
},
625+
{
626+
"name": "get_stock_history",
627+
"description": "Use this function to retrieve the historical price data for a given stock symbol over a specified period.\n\n:param symbol: The stock symbol to retrieve the historical data for.\n:param period: The time period for the historical data (e.g., '1d', '5d', '1mo', '1y').\n:return: A string containing the historical price data for the specified stock and period.",
628+
"parameters": {
629+
"type": "object",
630+
"properties": {
631+
"symbol": {
632+
"type": "string"
633+
},
634+
"period": {
635+
"type": "string"
636+
}
637+
}
638+
}
639+
}
640+
]""",
641+
"output": """<justification>
642+
The user's question about the recent performance of the stock market is broad and does not require the use of the available tools. The conversation history shows that the assistant has provided a general overview of the market's performance across different sectors, which sufficiently addresses the user's question. The user also acknowledges that the insights are helpful and expresses their intention to conduct further research and consult with a financial advisor. As a result, no specific tools are needed to answer this query.
643+
</justification>
644+
645+
<selected_tools>
646+
{
647+
"tool_calls": []
648+
}
649+
</selected_tools>""",
650+
},
651+
]
457652

653+
import random
458654
def get_suffix():
655+
random.shuffle(FEW_SHOTS)
459656
# Turn each element of FEW_SHOTS into a string like '-- EXAMPLE i ---\nINPUT:\n{input}\n\nOUTPUT:\n{output}\n\n', then join them by \n\n
460-
few_shots = "\n\n".join([f'-- EXAMPLE {i} ---\nINPUT:\n{example["input"]}\n\nOUTPUT:\n{example["output"]}\n\n' for i, example in enumerate(FEW_SHOTS, 1)])
657+
few_shots = "\n\n".join(
658+
[
659+
f'-- EXAMPLE {i} ---\nINPUT:\n{example["input"]}\n\nOUTPUT:\n{example["output"]}\n\n'
660+
for i, example in enumerate(FEW_SHOTS, 1)
661+
]
662+
)
461663
# Replace FEW_SHOTS with the actual examples
462-
return SUFFIX.replace("FEW_SHOTS", few_shots)
664+
return SUFFIX.replace("FEW_SHOTS", few_shots)

app/providers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def clean_params(self, params):
2020
pass
2121

2222

23-
class OpenAIProvider(BaseProvider):
23+
class OpenaiProvider(BaseProvider):
2424
def __init__(self, api_key: str, base_url = None):
2525
super().__init__(api_key)
2626
self._client = OpenAI(api_key=api_key)

app/routes/proxy.py

+9
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,15 @@ async def get_openai_v1(
3434
return JSONResponse(content={"message": f"GET request to {provider} v1"})
3535

3636

37+
@router.post("/groqchain/{provider}/v1/chat/completions")
38+
async def post_groq_chat_completions(
39+
request: Request,
40+
provider: str = Path(..., title="Provider")
41+
) -> JSONResponse:
42+
# Call the original post_chat_completions method with provider set to "groq"
43+
return await post_chat_completions(request, provider="groq")
44+
45+
3746
@router.post("/{provider}/v1/chat/completions")
3847
async def post_chat_completions(
3948
request: Request,

app/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def get_tool_call_response(tool_calls_result, unresolved_tol_calls, resolved_res
4242
"index": 0,
4343
"message": {
4444
"role": "assistant",
45-
"content": None,
45+
"content": "", # None,
4646
"tool_calls": unresolved_tol_calls,
4747
},
4848
"logprobs": None,
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# pip install --upgrade --quiet langchain-groq tavily-python langchain langchainhub langchain-openai
2+
3+
from langchain_core.prompts import ChatPromptTemplate
4+
from langchain_groq import ChatGroq
5+
import os
6+
from dotenv import load_dotenv
7+
load_dotenv()
8+
from langchain import hub
9+
from langchain.agents import create_openai_tools_agent
10+
from langchain_community.tools.tavily_search import TavilySearchResults, TavilyAnswer
11+
from langchain.agents import AgentExecutor
12+
13+
# The following code raise an error.
14+
chat = ChatGroq(
15+
temperature=0,
16+
groq_api_key=os.environ["GROQ_API_KEY"],
17+
model_name="mixtral-8x7b-32768",
18+
)
19+
20+
prompt = hub.pull("hwchase17/openai-tools-agent")
21+
tools = [TavilySearchResults(max_results=1)]
22+
agent = create_openai_tools_agent(chat, tools, prompt)
23+
24+
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, stream_runnable = False)
25+
agent_executor.invoke({"input": "What is Langchain?"})
26+
27+
28+
# The following code works fine using GroqCall (Funckycall) proxy
29+
chat = ChatGroq(
30+
temperature=0,
31+
groq_api_key=os.environ["GROQ_API_KEY"],
32+
model_name="mixtral-8x7b-32768",
33+
groq_api_base= "http://localhost:8000/proxy/groqchain"
34+
# groq_api_base= "http://groqcall.ai/proxy/groqchain"
35+
)
36+
37+
# Example 1: Chat with tools
38+
prompt = hub.pull("hwchase17/openai-tools-agent")
39+
tools = [TavilySearchResults(max_results=1)]
40+
agent = create_openai_tools_agent(chat, tools, prompt)
41+
42+
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, stream_runnable = False)
43+
result = agent_executor.invoke({"input": "What is Langchain?"})
44+
print(result)
45+
46+
# Example 1: Simple chat
47+
system = "You are a helpful assistant."
48+
human = "{text}"
49+
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
50+
51+
chain = prompt | chat
52+
result = chain.invoke({"text": "Explain the importance of low latency LLMs."})
53+
print(result)

0 commit comments

Comments
 (0)