Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google search tool and cleanup #138

Merged
merged 2 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using LangChain.Providers;
using LangChain.Schema;
using System.Reflection;
using LangChain.Chains.StackableChains.Agents.Tools;
using static LangChain.Chains.Chain;

namespace LangChain.Chains.StackableChains.Agents;
Expand All @@ -27,9 +28,9 @@ public class ReActAgentExecutorChain : BaseStackableChain

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
Action: the tool name, should be one of [{tool_names}]
Action Input: the input to the tool
Observation: the result of the tool
(this Thought/Action/Action Input/Observation can repeat multiple times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Expand All @@ -42,7 +43,7 @@ Always add [END] after final answer

private StackChain? _chain;
private bool _useCache;
Dictionary<string, ReActAgentTool> _tools = new();
Dictionary<string, AgentTool> _tools = new();
private readonly IChatModel _model;
private readonly string _reActPrompt;
private readonly int _maxActions;
Expand Down Expand Up @@ -133,8 +134,8 @@ protected override async Task<IChainValues> InternalCall(IChainValues values)
if (res.Value[ReActAnswer] is AgentAction)
{
var action = (AgentAction)res.Value[ReActAnswer];
var tool = _tools[action.Action];
var toolRes = tool.ToolCall(action.ActionInput);
var tool = _tools[action.Action.ToLower()];
var toolRes = await tool.ToolTask(action.ActionInput);
await _conversationBufferMemory.ChatHistory.AddMessage(new Message("Observation: " + toolRes, MessageRole.System))
.ConfigureAwait(false);
await _conversationBufferMemory.ChatHistory.AddMessage(new Message("Thought:", MessageRole.System))
Expand All @@ -144,7 +145,7 @@ await _conversationBufferMemory.ChatHistory.AddMessage(new Message("Thought:", M
else if (res.Value[ReActAnswer] is AgentFinish)
{
var finish = (AgentFinish)res.Value[ReActAnswer];
values.Value.Add(OutputKeys[0], finish.Output);
values.Value[OutputKeys[0]]= finish.Output;
return values;
}
}
Expand All @@ -170,7 +171,7 @@ public ReActAgentExecutorChain UseCache(bool enabled = true)
/// </summary>
/// <param name="tool"></param>
/// <returns></returns>
public ReActAgentExecutorChain UseTool(ReActAgentTool tool)
public ReActAgentExecutorChain UseTool(AgentTool tool)
{
tool = tool ?? throw new ArgumentNullException(nameof(tool));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@


namespace LangChain.Chains.StackableChains.Agents.Tools.BuiltIn.Classes;

public class GoogleResult
{
public class Item
{
public string title { get; set; }
public string link { get; set; }
public string snippet { get; set; }

}
public List<Item> items { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System.Net.Http;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Text;
using System.Security.Cryptography;
using LangChain.Chains.StackableChains.Agents.Tools.BuiltIn.Classes;

namespace LangChain.Chains.StackableChains.Agents.Tools.BuiltIn;

public class GoogleCustomSearchTool(string key, string cx, bool useCache = true, int resultsLimit=3) : AgentTool("google",
"to search information on internet")
{
private const string CACHE_DIR = "cache";

private string Hash(string prompt)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(prompt));
string resultHex = "";
foreach (var b in hash)
resultHex += $"{b:x2}";
return resultHex;
}

string? GetCachedAnswer(string prompt)
{
var file = Path.Combine(CACHE_DIR, $"{Hash(prompt)}.googlecache");
if (File.Exists(file))
{
return File.ReadAllText(file);
}

return null;
}

void SaveCachedAnswer(string prompt, string answer)
{
Directory.CreateDirectory(CACHE_DIR);
var file = Path.Combine(CACHE_DIR, $"{Hash(prompt)}.googlecache");
File.WriteAllText(file, answer);
}

public override async Task<string> ToolTask(string input, CancellationToken token = default)
{
string responseString;
if (!useCache||(responseString = GetCachedAnswer(input))==null)
{
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://www.googleapis.com");
var response = await httpClient.GetAsync(
$"/customsearch/v1?key={key}&cx={cx}&q={input}", token).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}


GoogleResult results = JsonSerializer.Deserialize<GoogleResult>(responseString!)!;


var stringBuilder = new StringBuilder();
int cnt = 0;
foreach (var result in results.items)
{
stringBuilder.AppendLine($"{result.title}");
stringBuilder.AppendLine($"{result.snippet}");
stringBuilder.AppendLine($"Source url: {result.link}");
stringBuilder.AppendLine();
if (++cnt >= resultsLimit)
break;
}

if (results.items.Count == 0)
{
stringBuilder.AppendLine("No results found");
stringBuilder.AppendLine();
}

if (useCache)
SaveCachedAnswer(input, responseString);
return stringBuilder.ToString();
}
}

This file was deleted.